<!-- Generated from the concise canonical handbook pages by `pnpm docs:agent`. Long-form deep dives remain in the human site. Do not edit this file directly. Every internal link points at a page's Markdown twin (`.md`), so following links keeps you in Markdown. -->

# 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`](https://github.com/Effect-TS/effect/tree/effect%404.1.4), commit [`289a53f7`](https://github.com/Effect-TS/effect/commit/289a53f7b1fc40049219c6e69022db2fb859c356) (released 2026-11-11). Each module is labelled with its public import path and stability marker.

---

## Orientation

### Version and validation scope

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](./foundations/getting-started.md) — 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](./foundations/getting-started.md#first-session-route-a-small-approval-worker) through errors, a tested service, resource ownership, Layers, and shutdown — five small exercises with observable self-checks.

### Stability and support

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](./interfaces/graphql.md) and [Platform & Runtime Hosts](./interfaces/platform-runtime-hosts.md). |

"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](./reference/release-history.md); the per-package `CHANGELOG.md` files in the Effect repository remain the authoritative record of every change.

### Official upstream companions

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.

| Official Effect resource | Best use |
| --- | --- |
| [Effect v4 guides](https://effect.website/docs/v4/getting-started) | 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. |
| [API reference](https://effect.website/docs/v4/api) | Generated per-module reference for every `effect` and `@effect/*` package, versioned per release. |
| [Onboarding track](https://effect.website/docs/v4/onboarding) and [Installation](https://effect.website/docs/v4/getting-started/installation) | The motivational on-ramp and setup steps; the handbook's short version is [Getting Started](./foundations/getting-started.md). |
| [`AGENTS.md` and `ai-docs/`](https://github.com/Effect-TS/effect/blob/effect%404.1.4/LLMS.md) shipped inside the `effect` package | 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](#coding-conventions-for-agents) below for how this handbook relates to it. |
| [Migration guide](https://github.com/Effect-TS/effect/blob/effect%404.1.4/MIGRATION.md) | The official v3 → v4 guide: import and API rename maps, services, causes, error handling, forking, layers, scopes, and the Schema v4 migration. |
| [Arbitrary guide](https://github.com/Effect-TS/effect/blob/effect%404.1.4/packages/effect/ARBITRARY.md) | The long-form reference for the native property-testing engine. |
| [Comprehensive Schema guide](https://github.com/Effect-TS/effect/blob/effect%404.1.4/packages/effect/SCHEMA.md) | 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.

### The through-line: one type

Everything orbits a single type:

```ts
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.

Official guides: [The Effect Type](https://effect.website/docs/v4/getting-started/the-effect-type), [Why Effect?](https://effect.website/docs/v4/getting-started/why-effect).

### 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).

```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`:

```ts
import { Context, Effect, Layer } from "effect"

class Hris extends Context.Service<Hris, {
  readonly getEmployee: (id: string) => Effect.Effect<Employee>
}>()("comp/Hris") {
  static layer = Layer.effect(Hris, Effect.gen(function*() {
    yield* Effect.log("connecting to HRIS…")
    return Hris.of({ getEmployee: (id) => Effect.succeed({ id, level: "L4" } as Employee) })
  }))
}
```

**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`](./data/functional-toolkit.md#function) builds the same pair for your own functions.

Official guides: [Guidelines](https://effect.website/docs/v4/code-style/guidelines), [Do notation vs generators](https://effect.website/docs/v4/code-style/do), [Dual APIs](https://effect.website/docs/v4/code-style/dual).

### Coding conventions for agents

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.Class`es. 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](./foundations/getting-started.md#effect-diagnostics-in-the-editor-and-in-ci)) 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.

### The lay of the land

- **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](https://effect.website/docs/v4/getting-started/importing-effect).

### How to use this handbook

- **⌘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](./reference/agent-guide.md) 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.

# Getting Started

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](https://effect.website/docs/v4/getting-started/installation) (asks for Node.js 22.18+; the release-matched README states Node.js 22.19+ as the general minimum), [Importing Effect](https://effect.website/docs/v4/getting-started/importing-effect), [The Effect Type](https://effect.website/docs/v4/getting-started/the-effect-type), [Creating Effects](https://effect.website/docs/v4/getting-started/creating-effects), [Running Effects](https://effect.website/docs/v4/getting-started/running-effects) (it names the `runFork` result `RuntimeFiber`; the type is `Fiber`), [Using Generators](https://effect.website/docs/v4/getting-started/using-generators), [Building Pipelines](https://effect.website/docs/v4/getting-started/building-pipelines) (it calls `Option` and `Result` yieldable inside `Effect.gen`; they are not — use `Effect.fromOption` and `Effect.fromResult`), [Devtools](https://effect.website/docs/v4/getting-started/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.

## Install Effect 4

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.

```sh
pnpm add effect@4.1.4 @effect/platform-node@4.1.4
pnpm add -D typescript@7 @types/node
```

**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 | `@effect/platform-node`, `@effect/platform-bun`, `@effect/platform-deno`, `@effect/platform-browser` |
| A SQL driver | `@effect/sql-pg`, `@effect/sql-pglite`, `@effect/sql-sqlite-node`, and the other `@effect/sql-*` packages |
| A language-model provider | `@effect/ai-openai`, `@effect/ai-anthropic`, `@effect/ai-openrouter`, `@effect/ai-openai-compat` |
| OpenTelemetry SDK export, UI bindings, test helpers | `@effect/opentelemetry`, `@effect/atom-react` (also `-solid`, `-vue`), `@effect/vitest` |

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

## Runtime and compiler requirements

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`:

```json
{
  "compilerOptions": {
    "target": "ES2025",
    "lib": ["ES2025"],
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "moduleDetection": "force",
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "rewriteRelativeImportExtensions": true,
    "skipLibCheck": true,
    "types": ["node"],
    "plugins": [{ "name": "@effect/language-service" }]
  }
}
```

| Setting | Status | Why it matters for Effect code |
| --- | --- | --- |
| `strict` | **required** | 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. |
| `verbatimModuleSyntax`, `erasableSyntaxOnly`, `rewriteRelativeImportExtensions` | recommended; on in the Effect repository | 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`. |
| `plugins: @effect/language-service` | recommended | Enables Effect diagnostics; see [Effect diagnostics in the editor and in CI](#effect-diagnostics-in-the-editor-and-in-ci). |

## A first complete program

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.

```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) | one `ManagedRuntime` | per runner, as above; dispose it on shutdown |

Details: [Effect](./foundations/core-runtime-execution.md#effect), [Runtime](./foundations/fibers-scopes-runtimes.md#runtime), and [ManagedRuntime](./foundations/fibers-scopes-runtimes.md#managedruntime). `BrowserRuntime.runMain` is the browser equivalent; see [Platform & Runtime Hosts](./interfaces/platform-runtime-hosts.md).

## Import forms

```ts
// 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.

## Stable and unstable modules

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.

## Effect diagnostics in the editor and in CI

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](./tooling/testing-dev-tooling.md) covers the tooling in depth.

## First-session route: a small approval worker

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.

1. **Model errors.** Read [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model), then [Effect error handling](./foundations/errors-option-result.md#effect-error-handling).

   **Exercise:** Give an over-limit proposal a tagged failure and recover from that tag at the worker boundary; keep an unexpected bug distinct.

   **Done when:** An accepted proposal succeeds, an over-limit proposal reaches its named handler, and a defect does not reach that handler.

2. **Define and test a service.** Read [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract), then the service recipe's [Complete file](./recipes/service-and-layers.md#complete-file) and [Variations](./recipes/service-and-layers.md#variations).

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

3. **Own resources.** Read [Scope](./foundations/fibers-scopes-runtimes.md#scope), then the bounded worker's [Complete file](./recipes/resource-safe-bounded-worker.md#complete-file).

   **Exercise:** Adapt its counted per-job acquisition/release around approval. Try success, a typed failure, and interruption while a job is active.

   **Done when:** Each acquired handle is released exactly once after its job ends, including the failed and interrupted cases.

4. **Compose Layers.** Read [Resourceful services](./foundations/services-context-layers.md#resourceful-services), then [Reading and composing the graph](./foundations/services-context-layers.md#reading-and-composing-the-graph).

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

5. **Run and shut down.** Read the graceful entrypoint's [Complete file](./recipes/graceful-entrypoint-and-shutdown.md#complete-file) and [Why these primitives?](./recipes/graceful-entrypoint-and-shutdown.md#why-these-primitives).

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

Keep the first pass small: no network, database, or readiness endpoint. Once these checks are clear, add a bounded retry policy using [Typed Retry with TestClock: Assert the shape of the policy](./recipes/retry-with-test-clock.md#assert-the-shape-of-the-policy), or extend shutdown with [Adding readiness and a bounded drain](./recipes/graceful-entrypoint-and-shutdown.md#adding-readiness-and-a-bounded-drain).

## Where next

| You want to | Go to |
| --- | --- |
| Understand `Effect`, fibers, scopes, and runners | [Core Runtime & Execution](./foundations/core-runtime-execution.md) |
| Model failures, absence, and recoverable results | [Errors, Option & Result](./foundations/errors-option-result.md) |
| Inject dependencies and own resource lifetimes | [Services, Context & Layers](./foundations/services-context-layers.md), then [Recipe: A Service with Live and Test Layers](./recipes/service-and-layers.md) |
| Read environment variables and secrets | [Configuration & Secrets](./foundations/configuration-secrets.md) |
| Validate and transform data at a boundary | [Schema](./data/schema.md) |
| Pick between similar primitives | [Choosing Effect Primitives](./reference/choosing-effect-primitives.md) |
| See the whole application shape | [Anatomy of a Real Effect Application](./deep-dives/anatomy-of-a-real-effect-application.md) |
| Bring Effect into a Promise-based codebase | [Adopting Effect in an Existing TypeScript Codebase](./deep-dives/adopting-effect-in-an-existing-codebase.md) |
| Write a production entrypoint | [Recipe: A Graceful Node Entrypoint](./recipes/graceful-entrypoint-and-shutdown.md) |
| Test with virtual time and replaceable services | [Testing & Dev Tooling](./tooling/testing-dev-tooling.md) and [Testing an Effect Application](./deep-dives/testing-an-effect-application.md) |
| Diagnose a confusing type error or a hang | [Troubleshooting & Anti-Patterns](./troubleshooting/troubleshooting-and-anti-patterns.md) |
| Review a change before it ships | [Review Checklists](./reference/review-checklists.md) |

# Core Runtime & Execution

`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](./foundations/fibers-scopes-runtimes.md).

> **Official examples:** The release-matched `ai-docs` corpus has runnable examples for [Effect basics](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/01_effect/01_basics), [resource safety](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/01_effect/05_resources), [running programs](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/01_effect/06_running), and [ManagedRuntime integration](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/04_integration).

> **Official guides:** [Creating Effects](https://effect.website/docs/v4/getting-started/creating-effects), [Running Effects](https://effect.website/docs/v4/getting-started/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

`effect/Effect` — stable

`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](./foundations/fibers-scopes-runtimes.md#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](#6-interruption-resource-safety)), a fork owner ([Fiber](./foundations/fibers-scopes-runtimes.md#fiber)), a `{ concurrency }` bound ([section 4](#4-concurrency)), and a finalizer.

### 1. Creating effects

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` |
| A Promise that is not expected to reject | `Effect.promise((signal) => ...)` | a **defect** |
| A Promise that can reject (`fetch`, SDK calls) | `Effect.tryPromise({ try: (signal) => ..., catch })` | the typed error `catch` returns (`Cause.UnknownError` for the bare-thunk form); a synchronous throw while creating the Promise goes through the same `catch` |
| A one-shot callback API | `Effect.callback<A, E>((resume, signal) => ...)` | whatever you pass to `resume`; only the first `resume` call counts |
| "Building the next effect is itself work" — recursion, a mutable read, branches of different effect types | `Effect.suspend(() => effect)` | a **defect** if the thunk throws |
| An `Option`, `Result`, or nullable value | `Effect.fromOption`, `Effect.fromResult`, `Effect.fromNullishOr` | not applicable |

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

```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 it
const fromSync = Effect.sync(() => crypto.randomUUID())            // side effect that cannot throw
const 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`](./concurrency/streaming-channels.md) 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](#8-cancellable-adapters-for-promises-and-callbacks).

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

```ts
import { Effect } from "effect"

let attempts = 0
const captured = Effect.succeed(++attempts)                      // incremented once, while building
const 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))
```

### 2. Sequencing with gen & fn

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.

```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”](./troubleshooting/troubleshooting-and-anti-patterns.md).

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

```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
})
```

Official guides: [Using Generators](https://effect.website/docs/v4/getting-started/using-generators), [Building Pipelines](https://effect.website/docs/v4/getting-started/building-pipelines) (it says `Option` and `Result` can be yielded inside `Effect.gen`; they cannot), [Simplifying Excessive Nesting](https://effect.website/docs/v4/code-style/do).

### 3. Error handling

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

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

```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](./foundations/errors-option-result.md#effect-error-handling). 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](./foundations/fibers-scopes-runtimes.md#recovering-from-a-mixed-cause).

Official guide: [Expected Errors](https://effect.website/docs/v4/error-management/expected-errors) (it defines errors with `Data.TaggedError`; the handbook's house style is `Schema.TaggedError`, and both are valid constructors).

### 4. Concurrency

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.

```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](./foundations/errors-option-result.md#effect-error-handling). |

```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](#9-branching-and-looping).

Official guide: [Basic Concurrency](https://effect.website/docs/v4/concurrency/basic-concurrency) (its printed `Cause` output shows nested `Parallel` / `Sequential` nodes; a `Cause` here is flat — see [Cause](./foundations/fibers-scopes-runtimes.md#cause)). The guide for `zip`, `forEach`, and `all` shapes is linked from [section 9](#9-branching-and-looping).

### 5. Racing & timeouts

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

```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).

```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](#8-cancellable-adapters-for-promises-and-callbacks).

Official guides: [Timing Out](https://effect.website/docs/v4/error-management/timing-out), [Basic Concurrency](https://effect.website/docs/v4/concurrency/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).

### 6. Interruption & resource safety

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.

```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 | no — the release effect's error type is `never` |
| The whole application (pool, client, exporter) | `Layer.effect(Service, ...)` whose build uses `acquireRelease` | 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 |

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

```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](#8-cancellable-adapters-for-promises-and-callbacks), a driver-level cancel, or a process kill. What to do when the cleanup itself can fail is [section 10](#10-when-cleanup-can-fail); manual scopes and finalizer order are under [Scope](./foundations/fibers-scopes-runtimes.md#scope). For the full startup, readiness, and shutdown story see [Owning Lifetimes — Startup, Readiness, and Shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md).

Official guide: [Resource Management: Introduction](https://effect.website/docs/v4/resource-management/introduction).

### 7. Sequential folds and context control

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

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

The host side of the same chain — turning a request's `AbortSignal` into fiber interruption with `{ signal }` — is in [section 11](#11-running-effects-at-an-owned-edge), with a complete walk-through in [Recipe: Request Cancellation Through a Host](./recipes/request-cancellation-through-a-host.md).

### 9. Branching and looping

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.

```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](https://effect.website/docs/v4/code-style/control-flow) (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`).

### 10. When cleanup can fail

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.

| Policy | Shape | Choose when |
| --- | --- | --- |
| Log and ignore | `close.pipe(Effect.ignore({ log: "Warn", message: "..." }))` | nobody can act on the failure |
| Bound, then ignore | `close.pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: "Warn" }))` | 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](./foundations/errors-option-result.md#recovery-and-mixed-causes)). Remember that `Effect.ignore` absorbs typed failures only; use `Effect.ignoreCause` to absorb defects as well.

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

### 11. Running effects at an owned edge

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](./foundations/fibers-scopes-runtimes.md#runtime) | the process entry point |
| `ManagedRuntime` | the same family as methods | same as above | a host that calls in repeatedly — see [ManagedRuntime](./foundations/fibers-scopes-runtimes.md#managedruntime) |

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.

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

## ExecutionPlan

`effect/ExecutionPlan` — unstable

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.

```ts
import { Context, Effect, ExecutionPlan, Layer, Schedule } from "effect"

const Endpoint = Context.Service<{ readonly url: string }>("handbook/HrisEndpoint")

const fetchEmployees = Effect.gen(function*() {
  const endpoint = yield* Endpoint
  if (endpoint.url === "https://primary.invalid") {
    return yield* Effect.fail("HRIS unavailable" as const)
  }
  return endpoint.url
})

const hrisPlan = ExecutionPlan.make(
  {
    provide: Layer.succeed(Endpoint, { url: "https://primary.invalid" }),
    attempts: 2,
    schedule: Schedule.exponential("100 millis")
  },
  {
    provide: Layer.succeed(Endpoint, { url: "https://backup.example" })
  }
)

const events: Array<string> = []
const program = Effect.withExecutionPlan(fetchEmployees, hrisPlan, {
  onEvent: (event) =>
    Effect.sync(() => events.push(`${event._tag}:${event.stepIndex}`))
})

const selectedEndpoint = await Effect.runPromise(program)
console.log(selectedEndpoint) // "https://backup.example"
console.log(events) // ["AttemptStart:0", "AttemptFailure:0", "AttemptStart:0", "AttemptFailure:0", "AttemptStart:1", "AttemptSuccess:1"]
```

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.

## Effectable

`effect/Effectable` — stable

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.

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

# Fibers, Scopes & Runtimes

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](./foundations/core-runtime-execution.md) covers building and combining Effects; this page covers owning them while they run.

![Diagram: an Effect is run on a root fiber; forkChild, forkScoped, and forkDetach give forked fibers different owners; acquireRelease and Layers register finalizers in a Scope; the run ends in an Exit](./diagrams/effect-fiber-scope-ownership.svg)

_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

`effect/Exit` — stable

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

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

Official guides: [Exit](https://effect.website/docs/v4/data-types/exit), [Unexpected Errors](https://effect.website/docs/v4/error-management/unexpected-errors).

**Reach for it when** you've crossed out of the Effect world and need to inspect success-or-cause synchronously.

## Cause

`effect/Cause` — stable

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.

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

```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](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail)), 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.

Official guides: [Cause](https://effect.website/docs/v4/data-types/cause), [Parallel and Sequential Errors](https://effect.website/docs/v4/error-management/parallel-and-sequential-errors), [Sandboxing](https://effect.website/docs/v4/error-management/sandboxing).

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

### Recovering from a mixed Cause

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.

```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](./foundations/errors-option-result.md#effect-error-handling).

## Fiber

`effect/Fiber` — stable

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

```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](https://effect.website/docs/v4/concurrency/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 }`.

### Choosing a fork by its owner

**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](#fiberhandle), [FiberMap](#fibermap), or [FiberSet](#fiberset) instead of hand-kept handles; the worked example is [Structured Concurrency Through a Bounded Worker](./deep-dives/structured-concurrency-through-a-bounded-worker.md).

```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.
}))
```

### When a forked fiber starts

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

```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"]
```

### Requesting cancellation versus awaiting cleanup

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

## FiberHandle

`effect/FiberHandle` — stable

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.

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

## FiberMap

`effect/FiberMap` — stable

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.

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

## FiberSet

`effect/FiberSet` — stable

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.

```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](https://effect.website/docs/v4/observability/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`.

## Runtime

`effect/Runtime` — stable

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.

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

```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`:

```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](./recipes/graceful-entrypoint-and-shutdown.md). Official guide: [Platform Runtime](https://effect.website/docs/v4/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`.

## Scope

`effect/Scope` — stable

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.

```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](./foundations/core-runtime-execution.md#6-interruption-resource-safety).

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

```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)
```

Official guide: [Scope](https://effect.website/docs/v4/resource-management/scope).

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

## Scheduler

`effect/Scheduler` — stable

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

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

## Clock

`effect/Clock` — stable

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.

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

## Deferred

`effect/Deferred` — stable

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.

```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>>`).

| Complete with | Function |
| --- | --- |
| a value | `Deferred.succeed(d, value)`, `Deferred.sync(d, () => value)` |
| a typed failure | `Deferred.fail(d, error)`, `Deferred.failSync(d, () => error)` |
| a defect, a full cause, or interruption | `Deferred.die(d, defect)`, `Deferred.failCause(d, cause)`, `Deferred.interrupt(d)` |
| an already computed `Exit` | `Deferred.done(d, exit)` |
| 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](#latch).

```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](https://effect.website/docs/v4/concurrency/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.

## Latch

`effect/Latch` — stable

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.

```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](https://effect.website/docs/v4/concurrency/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.

## ManagedRuntime

`effect/ManagedRuntime` — stable

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.

```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](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks)). 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)`).

```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 = false

export 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()
}
```

The complete host-side walk-through — request signal to adapter abort, with its tests — is [Recipe: Request Cancellation Through a Host](./recipes/request-cancellation-through-a-host.md); the embedding recipe is [Recipe: ManagedRuntime at an Imperative Boundary](./recipes/managed-runtime-integration.md); readiness, draining, and shutdown ordering are in [Owning Lifetimes — Startup, Readiness, and Shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md). When the host already holds a `Context<R>`, the lighter `Effect.run*With(context)` runners in [section 11 of Core Runtime & Execution](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) avoid a managed runtime altogether.

Official guide: [Runtime](https://effect.website/docs/v4/runtime).

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

## Pull

`effect/Pull` — stable

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.

```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](https://effect.website/docs/v4/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`.

## Version

`effect/Version` — unstable

The `effect` package version string reported in OTLP resources, telemetry headers, and span scopes. Added in 4.0.2.

```ts twoslash
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.

# Services, Context & Layers

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/01_effect/03_services) cover `Context.Service`, `Context.Reference`, Layer composition, and dynamically constructed Layers.

> **Official guides:** [Managing Services](https://effect.website/docs/v4/requirements-management/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.

![Diagram: Layers build dependencies first (Config, Database, Repository, HttpServer), the program runs with the services, and teardown releases them in reverse order](./diagrams/layer-build-teardown.svg)

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

## Context

`effect/Context` — stable

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.

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

### Reading a service

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

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

### Designing a service contract

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.

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

### Providing one value or building a graph

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

```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](#what-is-shared-and-what-is-rebuilt)). It is the Effect spelling of `new HttpClient()` inside a function body.

### Optional services

`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`](#references), 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.

```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")
  }
})
```

### Declaring the constructor with `make`

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

```ts
import { Context, Effect, FileSystem, Layer } from "effect"

class OfferLetterTemplates extends Context.Service<OfferLetterTemplates>()("hr/OfferLetterTemplates", {
  make: Effect.gen(function*() {
    const fs = yield* FileSystem.FileSystem
    return {
      load: (name: string) => fs.readFileString(`templates/${name}.html`)
    } as const
  })
}) {
  // Layer<OfferLetterTemplates, never, FileSystem> — dependencies still open.
  static readonly layerNoDeps = Layer.effect(this, this.make)
}
```

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.

## Layer

`effect/Layer` — stable

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.

```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](https://effect.website/docs/v4/requirements-management/layers) (it names the dependency-free Layer `layerWithoutDependencies`; the actual property is `layerNoDeps`), [Layer Memoization](https://effect.website/docs/v4/requirements-management/layer-memoization) (its "providing locally" section describes only the sibling case; nested reuse and `{ local: true }` are covered below).

### Resourceful services

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.

```ts
import { Config, Context, Effect, Layer, Redacted, Schema } from "effect"

class PayrollUnavailable extends Schema.TaggedError<PayrollUnavailable>()("PayrollUnavailable", {
  reason: Schema.String
}) {}

interface PayrollConnection {
  readonly submit: (runId: string) => Promise<void>
  readonly close: () => Promise<void>
}
declare const connectPayroll: (url: URL, token: string) => Promise<PayrollConnection>

class PayrollGateway extends Context.Service<PayrollGateway, {
  readonly submitRun: (runId: string) => Effect.Effect<void, PayrollUnavailable>
}>()("hr/PayrollGateway") {
  // Layer<PayrollGateway, PayrollUnavailable | ConfigError> — no Scope in the inputs.
  static readonly layer = Layer.effect(PayrollGateway, Effect.gen(function*() {
    const url = yield* Config.URL("PAYROLL_URL")
    const token = yield* Config.Redacted("PAYROLL_TOKEN")
    const connection = yield* Effect.acquireRelease(
      Effect.tryPromise({
        try: () => connectPayroll(url, Redacted.value(token)),
        catch: (cause) => new PayrollUnavailable({ reason: String(cause) })
      }),
      (open) => Effect.promise(() => open.close())
    )
    return PayrollGateway.of({
      submitRun: (runId) =>
        Effect.tryPromise({
          try: () => connection.submit(runId),
          catch: (cause) => new PayrollUnavailable({ reason: String(cause) })
        })
    })
  }))
}
```

- **`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`](#layermap).

### What is shared, and what is rebuilt

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

```ts
import { Context, Effect, Layer } from "effect"

class PayrollPool extends Context.Service<PayrollPool, { readonly id: number }>()("hr/PayrollPool") {}

let opened = 0
const 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`](./foundations/fibers-scopes-runtimes.md#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.

### Reading and composing the graph

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.

### Observing and recovering construction

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.

```ts
import { Context, Effect, Layer, Schema } from "effect"

class BandCatalogUnavailable extends Schema.TaggedError<BandCatalogUnavailable>()("BandCatalogUnavailable", {
  reason: Schema.String
}) {}

class BandCatalog extends Context.Service<BandCatalog, {
  readonly source: "remote" | "bundled-snapshot"
}>()("hr/BandCatalog") {}

declare const BandCatalogRemote: Layer.Layer<BandCatalog, BandCatalogUnavailable>
declare const BandCatalogSnapshot: Layer.Layer<BandCatalog>

// Layer<BandCatalog, never, never>
const BandCatalogLive = BandCatalogRemote.pipe(
  Layer.tapError((error) => Effect.logWarning("band catalog unreachable; serving bundled snapshot", error)),
  Layer.catchTag("BandCatalogUnavailable", () => BandCatalogSnapshot),
  Layer.tap((context) => Effect.logInfo(`band catalog ready: ${Context.get(context, BandCatalog).source}`))
)
```

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](./foundations/configuration-secrets.md#deciding-required-optional-and-defaulted)).

### Test layers and substitution

The service-side rules are short; the strategy (stub, fake, recording fake, failure layer, contract suite) lives in [Testing & Dev Tooling](./tooling/testing-dev-tooling.md) and [Testing an Effect Application](./deep-dives/testing-an-effect-application.md).

- **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](#references) never appear in `R`, so forgetting to install a test override compiles and silently uses the real one.

## LayerMap

`effect/LayerMap` — unstable

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.

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

## LayerRef

`effect/LayerRef` — unstable

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.

```ts
import { Context, Effect, Layer, LayerRef } from "effect"

class CompBands extends Context.Service<CompBands, {
  readonly version: string
}>()("handbook/CompBands") {}

declare const loadVersion: () => string
const CompBandsLive = Layer.sync(CompBands, () => ({ version: loadVersion() }))

const program = Effect.scoped(Effect.gen(function*() {
  const bandsRef = yield* LayerRef.make(CompBandsLive, {
    idleTimeToLive: "5 minutes",
    preload: true
  })

  const readVersion = Effect.gen(function*() {
    return (yield* CompBands).version
  })

  const before = yield* Effect.provide(readVersion, bandsRef.get)
  yield* bandsRef.refresh
  const after = yield* Effect.provide(readVersion, bandsRef.get)
  return [before, after] as const
}))
```

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.

## References

`effect/References` — stable

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.Reference`s — 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.

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

### Default services

Five everyday capabilities are `Context.Reference`s 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.

| Reference key | Default | Replace it with | More |
| --- | --- | --- | --- |
| `Clock.Clock` | System clock | `TestClock.layer()` from `effect/testing` | [Clock](./foundations/fibers-scopes-runtimes.md#clock), [TestClock](./tooling/testing-dev-tooling.md#testclock) |
| `ConfigProvider.ConfigProvider` | `ConfigProvider.fromEnv()` | `ConfigProvider.layer(ConfigProvider.fromUnknown({...}))` | [ConfigProvider](./foundations/configuration-secrets.md#configprovider) |
| `Console.Console` | The global `console` | `TestConsole.layer` from `effect/testing` | [Console](./operations/observability.md#console), [TestConsole](./tooling/testing-dev-tooling.md#testconsole) |
| `Random.Random` | `Math.random` | `Random.withSeed(seed)` for a reproducible sequence | [Random](./concurrency/scheduling-time.md#random) |
| `Tracer.Tracer` | In-memory native tracer that exports nothing | An exporter layer such as OTLP | [Tracer](./operations/observability.md#tracer) |

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.

Official guide: [Default Services](https://effect.website/docs/v4/requirements-management/default-services).

## Resource

`effect/Resource` — stable

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.

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

# Configuration & Secrets

`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](https://effect.website/docs/v4/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

`effect/Config` — stable

`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](#built-in-constructors)) 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.

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

### Built-in constructors

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)`. |
| `Config.Port` | integer 1–65535 | Rejects `0`, `65536`, `80.5`. |
| `Config.Boolean` | `boolean` | Exactly `true` `false` `yes` `no` `on` `off` `1` `0` `y` `n`, **case-sensitive** — `TRUE` fails. |
| `Config.Duration` | `Duration` | 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. |
| `Config.ByteSize` | [`ByteSize`](./data/functional-toolkit.md#bytesize) | `"10 MiB"` (powers of 1,024), `"10MB"` (powers of 1,000), `"1.5 GiB"`; rejects a bare `"512"`. |
| `Config.URL` | `URL` | Absolute URLs only; `hris.example.com` fails. |
| `Config.Date` | `Date` | Rejects text that produces an invalid `Date`. |
| `Config.LogLevel` | `LogLevel` | `All` `Fatal` `Error` `Warn` `Info` `Debug` `Trace` `None`, case-sensitive. |
| `Config.Literal(value, name?)`, `Config.Literals(values, name?)` | the literal union | The constructor for an explicit mode switch such as `"live" \| "sandbox"`. |
| `Config.Redacted` | `Redacted<string>` | See [Redacted](#redacted). |
| `Config.Array(schema, name?, options?)`, `Config.Record(key, value, name?, options?)` | array / record | See below. |

**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](./concurrency/scheduling-time.md#duration).

### Lists and maps from flat values

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.

```ts
import { Config, ConfigProvider, Effect, Schema } from "effect"

const PayrollRegions = Config.Array(Schema.Literals(["us", "eu", "apac"]), "PAYROLL_REGIONS")
const BandOwners = Config.Record(Schema.String, Schema.String, "BAND_OWNERS")

const fromEnv = ConfigProvider.fromEnv({
  env: { PAYROLL_REGIONS: "us,eu", BAND_OWNERS: "L4=comp-eng,L5=comp-staff" }
})
const fromObject = ConfigProvider.fromUnknown({
  PAYROLL_REGIONS: ["apac"],
  BAND_OWNERS: { L4: "comp-eng" }
})

const regionsFromEnv = Effect.runSync(PayrollRegions.parse(fromEnv)) // ["us", "eu"]
const regionsFromObject = Effect.runSync(PayrollRegions.parse(fromObject)) // ["apac"]
const owners = Effect.runSync(BandOwners.parse(fromEnv)) // { L4: "comp-eng", L5: "comp-staff" }
```

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`).

### Validating more than syntax

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

```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({}))
```

### Absence is not malformed input

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 |

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

## ConfigProvider

`effect/ConfigProvider` — stable

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.

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

```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 })))
)
```

### Precedence and composition

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

```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. |
| `ConfigProvider.layerAdd(provider, { asPrimary: true })` | 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 `SourceError` **only** 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.

## Designing the startup contract

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

```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))
}
```

### Deciding required, optional, and defaulted

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`](./foundations/services-context-layers.md#resource) and [`LayerRef`](./foundations/services-context-layers.md#layerref) are the building blocks.

### Testing the contract

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` | The explicit value survives |
| Primary source valid / absent / malformed / unreadable, fallback valid | primary / fallback / decode failure / source failure |
| 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](#redacted)). Test-layer mechanics live in [Testing & Dev Tooling](./tooling/testing-dev-tooling.md) and [Testing an Effect Application](./deep-dives/testing-an-effect-application.md).

## Redacted

`effect/Redacted` — stable

`Redacted<string>` holds a secret value; stringifying, logging, or inspecting it prints `<redacted>`. The real value is only accessible via `Redacted.value`.

```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 `ConfigError`s, pretty-printed `Cause`s, 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.

### Labels, comparison, and wiping

```ts
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")) // true
const 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.

### Secrets that arrive through a schema

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.

```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](https://effect.website/docs/v4/data-types/redacted) (its headings say `unsafeWipe` and `getEquivalence`; the actual names are `Redacted.wipeUnsafe` and `Redacted.makeEquivalence`), [Effect Data Types](https://effect.website/docs/v4/schema/effect-data-types) (Schema; see its Redacted section, which does not mention that `RedactedFromValue` spells the option `disallowEncode`).

## Redactable

`effect/Redactable` — stable

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

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

# Errors, Option & Result

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/01_effect/04_errors) cover tagged errors, `catchTag`/`catchTags`, and reason-based errors.

> **Official guides:** [Expected Errors](https://effect.website/docs/v4/error-management/expected-errors), [Two Types of Errors](https://effect.website/docs/v4/error-management/two-error-types). These track Effect's `main` branch rather than this edition's audited release, so where they differ, this page and the tagged source win.

![Diagram: an Exit is a Success or a Failure carrying a Cause; a Cause holds Fail, Die, and Interrupt reasons, and each is handled by different combinators](./diagrams/cause-classification.svg)

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

## Designing the error model

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:

| Failure | Detected by | What the caller can do | Channel | Retryable | Translated by | Logged by |
| --- | --- | --- | --- | --- | --- | --- |
| no row for the employee id | repository (the query succeeded with zero rows) | answer 404, or skip the employee | `E`: `EmployeeNotFound` | no | repository, into a domain error | HTTP edge, at info level |
| proposed salary above the band | domain validation | request an exception, or reject | `E`: `BandViolation` | no | nobody; it is already domain language | nobody; it is expected |
| HRIS answers 503 or times out | HRIS adapter | retry with backoff, then degrade | `E`: `HrisUnavailable { retryable }` | yes, bounded | adapter wraps the driver error once | retry boundary (attempts), owner (terminal outcome) |
| a decoded row violates a guaranteed constraint | repository decode | nothing | defect | no | nobody | process edge through `ErrorReporter` |
| the request was aborted | runtime | nothing | interruption | never | never | not logged as a fault |

Rules that fall out of the worksheet:

- **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](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks) 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](./deep-dives/failure-retry-fallback-and-interruption.md) follows one operation through these decisions, including retry, timeout, and fallback.

## Effect error handling

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](./foundations/core-runtime-execution.md#3-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. |
| `Effect.tapError` / `tapErrorTag` / `tapCause` / `tapDefect` | 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:

```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 })
    )
  })
)
```

### Selective recovery beyond one tag

```ts
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.

### Transforming the error channel

```ts
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.

### Folding both channels at a boundary

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.

```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`.
- To make the fold exhaustive over a large union, delegate to a matcher from [Classifying an error union](#classifying-an-error-union).

### Accumulating errors instead of failing fast

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

```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 |
| Every problem at once, or else every value | `Effect.validate(items, f, { concurrency?, discard? })` | `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).

### Fallback values and ignoring failures

```ts
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`](./foundations/core-runtime-execution.md#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.

### Recovery and mixed causes

A [`Cause`](./foundations/fibers-scopes-runtimes.md#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 **first** `Fail` 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.

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

The failure deep dive covers reason inspection and the `Effect.sandbox` route: [Inspect the full Cause without flattening it](./deep-dives/failure-retry-fallback-and-interruption.md#inspect-the-full-cause-without-flattening-it).

Official guides: [Error Channel Operations](https://effect.website/docs/v4/error-management/error-channel-operations), [Matching](https://effect.website/docs/v4/error-management/matching), [Error Accumulation](https://effect.website/docs/v4/error-management/error-accumulation), [Fallback](https://effect.website/docs/v4/error-management/fallback).

## Classifying an error union

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.

```ts
import { Effect, Match, Schema } from "effect"

class InvalidRaise extends Schema.TaggedError<InvalidRaise>()("InvalidRaise", {
  requestedPercent: Schema.Finite
}) {}

class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", {
  employeeId: Schema.String
}) {}

class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", {
  status: Schema.Int
}) {}

type RaiseFailure = InvalidRaise | EmployeeNotFound | HrisUnavailable
type Policy = "reject-input" | "report-missing" | "retry-later" | "page-oncall"

// Field-sensitive policy. Adding a variant to RaiseFailure breaks compilation here.
const policyFor = Match.type<RaiseFailure>().pipe(
  Match.tag("InvalidRaise", (): Policy => "reject-input"),
  Match.tag("EmployeeNotFound", (): Policy => "report-missing"),
  Match.tag("HrisUnavailable", ({ status }): Policy => (status >= 500 ? "retry-later" : "page-oncall")),
  Match.exhaustive
)

// Table form: one handler per tag, checked for completeness.
const statusFor = Match.type<RaiseFailure>().pipe(
  Match.tagsExhaustive({
    InvalidRaise: () => 422,
    EmployeeNotFound: () => 404,
    HrisUnavailable: () => 503
  })
)

// Plain data works too: `satisfies` rejects a missing or misspelled tag.
const retryable = {
  InvalidRaise: false,
  EmployeeNotFound: false,
  HrisUnavailable: true
} as const satisfies Record<RaiseFailure["_tag"], boolean>

declare const approveRaise: Effect.Effect<number, RaiseFailure>

// The terminal fold delegates to the exhaustive classifiers.
const response = approveRaise.pipe(
  Effect.match({
    onFailure: (error) => ({ status: statusFor(error), policy: policyFor(error) }),
    onSuccess: (newSalary) => ({ status: 200, newSalary })
  })
)
```

- **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/schema.md#4-unions-literals-records-tuples)). `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.

The full `Match` API lives in [The Functional Toolkit](./data/functional-toolkit.md#match).

## Option

`effect/Option` — stable

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

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

### Combining optional values

```ts
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.

### Fallbacks and boundary exits

```ts
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` |
| `Option.match({ onNone, onSome })` | both branches produce a value |
| `Option.getOrThrow` / `Option.getOrThrowWith(() => error)` | 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](https://effect.website/docs/v4/data-types/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](#moving-between-option-result-and-effect)), [Effect Data Types](https://effect.website/docs/v4/schema/effect-data-types) (Schema) for nullable and optional wire shapes that decode to `Option`.

## Result

`effect/Result` — stable

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

```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_000
const 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.

### Transforming and combining Results

```ts
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.

### Moving between Option, Result, and Effect

Climb only when the semantics change: absence → absence with a reason → a reason inside a workflow.

| From → to | Function | Notes |
| --- | --- | --- |
| nullable → `Option` | `Option.fromNullishOr` (`fromNullOr`, `fromUndefinedOr`) | |
| `Option` → `Result` | `Result.fromOption(option, () => reason)` | upgrades absence into a named failure |
| `Result` → `Option` | `Result.getSuccess` / `Result.getFailure` | deliberately discards the other side |
| `Option` → `Effect` | `Effect.fromOption(option, () => error)` | 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` |

```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](./reference/choosing-effect-primitives.md#option-vs-result-vs-effect).

Official guide: [Result](https://effect.website/docs/v4/data-types/result) (the same caveat applies to its claim that a `Result` can be yielded inside `Effect.gen`).

## Filter

`effect/Filter` — stable

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.

```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_000

const 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](#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.

## Data

`effect/Data` — stable

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`](./data/functional-toolkit.md#equal) 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.

```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 reference

const 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:

```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 typed

class 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 equality
const 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).

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

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

Official guides: [Data](https://effect.website/docs/v4/data-types/data), [Yieldable Errors](https://effect.website/docs/v4/error-management/yieldable-errors).

## ErrorReporter

`effect/ErrorReporter` — unstable

A pluggable sink for reporting `Cause`s — 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.

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

## PlatformError

`effect/PlatformError` — unstable

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

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

## The three failure buckets

> **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](./deep-dives/testing-an-effect-application.md#assert-typed-failures-as-data). For symptoms and fixes, see [Typed failure versus defect and interruption](./troubleshooting/troubleshooting-and-anti-patterns.md#typed-failure-versus-defect-and-interruption).

# Concurrency & Coordination

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](./foundations/fibers-scopes-runtimes.md#fiber); stream-level buffering and backpressure live in [Streaming & Channels](./concurrency/streaming-channels.md#stream). This page owns what happens *between* fibers: who waits, who is told "no", and what is lost.

## Semaphore

`effect/Semaphore` — stable

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.

```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:

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

Official guide: [Semaphore](https://effect.website/docs/v4/concurrency/semaphore).

## PartitionedSemaphore

`effect/PartitionedSemaphore` — unstable

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.

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

## Queue

`effect/Queue` — stable

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.

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

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

### Put queue roles in function signatures

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

```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
})
```

### Make loss observable

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

```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) => void

const 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](./concurrency/streaming-channels.md#stream) 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](./deep-dives/structured-concurrency-through-a-bounded-worker.md).
- **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](./tooling/persistence.md#persistedqueue) or an outbox table.

```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](https://effect.website/docs/v4/concurrency/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](https://effect.website/docs/v4/stream/creating) drives the same `offerUnsafe` / `endUnsafe` / `failCauseUnsafe` API.

## PubSub

`effect/PubSub` — stable

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.

```ts
import { Context, Effect, Layer, PubSub, Stream } from "effect"

// Domain event for the annual merit cycle
type 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 service
export 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 approved
const 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
  )
})
```

### Delivery semantics: Queue or PubSub

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 and the publish result

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](#make-loss-observable), 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`.

### Reading a subscription directly

`Stream.fromPubSub` is the default consumer. Tests, batch readers, and load-shedding code sometimes need the lower-level protocol: open a scoped `PubSub.Subscription` **first**, 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`.

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

### Proving a subscription did not leak

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.

```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](https://effect.website/docs/v4/concurrency/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).

## Pool

`effect/Pool` — stable

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`. |
| `Pool.makeWithTTL({ acquire, min, max, timeToLive })` | 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`. |

```ts
import { Context, Duration, Effect, Layer, Pool, Scope } from "effect"

// A thin wrapper around a live HRIS HTTP session
interface 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 pool
export 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`.

### TTL is not a health check

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

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

```ts
import { Effect, Pool } from "effect"

declare const openSession: Effect.Effect<{ readonly id: string }>

const program = Effect.scoped(
  Effect.gen(function*() {
    const pool = yield* Pool.make({ acquire: openSession, size: 4 })
    const { idle, used, pending } = yield* Pool.stats(pool)
    yield* Effect.log(`hris sessions idle=${idle} used=${used} waiting=${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.

## RcRef

`effect/RcRef` — stable

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.

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

## RcMap

`effect/RcMap` — stable

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.

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

## ScopedRef

`effect/ScopedRef` — stable

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

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

# Software Transactional Memory

> **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 *outermost* `Effect.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`.

## The mental model

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](./concurrency/state-mutable-references.md#ref); anything that must survive a restart or be visible to another process is a database transaction — see [SQL](./interfaces/sql.md) and the [transactional write with outbox recipe](./recipes/transactional-write-with-outbox.md).

### The canonical example: draw down a shared merit budget

```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

```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 }
})
```

### Inspecting transaction attempts

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.

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

## TxRef

`effect/TxRef` — stable

The atom of STM: a single mutable cell whose reads and writes participate in a transaction. Every other `Tx*` structure is one or more `TxRef`s 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.

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

## TxChunk

`effect/TxChunk` — unstable

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.

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

## TxHashMap

`effect/TxHashMap` — stable

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.

```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).

## TxHashSet

`effect/TxHashSet` — stable

Transactional set of unique values with `add`, `remove`, `has`, `isEmpty`/`isNonEmpty`, and set algebra: `union`, `intersection`, `difference`, `isSubset`.

**Mental model.** Transactional analog of `HashSet`. Use for shared membership state that is concurrently mutated.

```ts
import { Effect, TxHashSet } from "effect"

const program = Effect.gen(function*() {
  // Employees whose raise has already been recommended this cycle.
  const recommended = yield* TxHashSet.make("E-1042", "E-2087")

  yield* Effect.tx(TxHashSet.add(recommended, "E-3119"))

  console.log(yield* TxHashSet.has(recommended, "E-3119")) // true
  console.log(yield* TxHashSet.size(recommended))          // 3
})
```

**Reach for it when** you track a concurrently-mutated set of unique things and want atomic add/remove plus set operations.

## TxQueue

`effect/TxQueue` — stable

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](./concurrency/concurrency-coordination.md#queue).

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

## TxPubSub

`effect/TxPubSub` — stable

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.

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

## TxSemaphore

`effect/TxSemaphore` — stable

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.

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

## TxReentrantLock

`effect/TxReentrantLock` — stable

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.

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

## TxDeferred

`effect/TxDeferred` — stable

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.

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

## TxPriorityQueue

`effect/TxPriorityQueue` — stable

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.

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

## TxSubscriptionRef

`effect/TxSubscriptionRef` — stable

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.

```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

```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 &rarr; `TxRef`; keyed state &rarr; `TxHashMap`; membership &rarr; `TxHashSet`; ordered buffer &rarr; `TxChunk`; work queue with blocking/backpressure &rarr; `TxQueue` (priority ordering? `TxPriorityQueue`); broadcast &rarr; `TxPubSub`; observable value &rarr; `TxSubscriptionRef`; one-shot handoff &rarr; `TxDeferred`; concurrency cap &rarr; `TxSemaphore`; explicit reader/writer control &rarr; `TxReentrantLock`. They all compose under a single `Effect.tx`, so you can mix them in one atomic step.

# State & Mutable References

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](https://effect.website/docs/v4/state-management/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.

## Ref

`effect/Ref` — stable

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.

Key APIs: make, get, set, update, updateAndGet, modify, getAndSet, getAndUpdate, updateSome, modifySome, makeUnsafe, getUnsafe

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

```ts
import { Effect, Ref } from "effect"

// Track remaining merit budget across concurrent raise recommendations
const 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 approved
const 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 `===`.

### One transition, one call

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

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

### Sharing one Ref through a service

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.

```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](./foundations/services-context-layers.md#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).

## SynchronizedRef

`effect/SynchronizedRef` — stable

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.

```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> | null

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

Official guide: [SynchronizedRef](https://effect.website/docs/v4/state-management/synchronizedref).

## SubscriptionRef

`effect/SubscriptionRef` — stable

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.

```ts
import { Deferred, Effect, Fiber, Stream, SubscriptionRef } from "effect"

// Live headcount ref: write on every hire/departure, stream to dashboards
const 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.

### Keep the ref private, expose a Stream

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

```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](./concurrency/software-transactional-memory.md#txsubscriptionref); for fan-out of *events* rather than state, use [PubSub](./concurrency/concurrency-coordination.md#pubsub).

Official guide: [SubscriptionRef](https://effect.website/docs/v4/state-management/subscriptionref).

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

## MutableRef

`effect/MutableRef` — stable

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.

```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 fiber
const 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.

## MutableList

`effect/MutableList` — stable

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

```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-write
const 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.

## MutableHashMap

`effect/MutableHashMap` — stable

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]>`.

Key operations: `empty`, `make`, `fromIterable`, `get` (returns `Option`), `set`, `has`, `remove`, `modify`, `modifyAt`, `forEach`, `keys`, `values`, `size`, `isEmpty`, `clear`.

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

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

## MutableHashSet

`effect/MutableHashSet` — stable

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

```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](./data/data-structures.md#hashset) instead: every change produces a new value, so nobody observes a half-built set.

Official guide: [HashSet](https://effect.website/docs/v4/data-types/hash-set) (documents the immutable and mutable variants side by side).

## Choosing the right state tool

| Module | Updates | Effect API | Reactive stream | Best for |
| --- | --- | --- | --- | --- |
| `Ref` | Pure, synchronous | Yes | No | Shared merit budget pool, counters, flags |
| `SynchronizedRef` | Pure or effectful, serialised | Yes | No | 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.

# Streaming & Channels

`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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/03_stream) cover creation, transformation, consumption, and NDJSON encoding.
>
> **Official guides:** [Introduction to Streams](https://effect.website/docs/v4/stream/introduction), [Sink introduction](https://effect.website/docs/v4/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.

![Diagram: pull sources produce on demand; push sources feed a buffer with a capacity and overflow strategy; operators sit between sources and the sink, which pulls each element](./diagrams/stream-backpressure.svg)

_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

`effect/Stream` — stable

`Stream<A, E, R>` is a lazy, pull-based, possibly-infinite sequence of `A`s 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.

### 1. Creating streams

| Source type | Constructor |
|---|---|
| In-memory data | `fromIterable` / `fromArray` / `make`; `fromArrays` emits one chunk per array |
| One effect, one constant, one failure | `fromEffect` / `succeed` / `fail` (also `failCause`, `die`, `empty`, `never`) |
| Effect that returns a collection | `fromIterableEffect` — "call the repository, then stream the rows" |
| Effect that returns a stream | `unwrap` — also the way to [own a resource](#6-owning-resources-inside-a-stream) |
| Repeat one effect, or a whole stream | `fromEffectRepeat` / `forever` / `repeat(schedule)` |
| Effectful, scheduled polling | `fromEffectSchedule` |
| Cursor-based API pagination | `paginate` |
| Async iterator | `fromAsyncIterable` |
| DOM event / callback | `fromEventListener` / `callback` |
| Concurrency primitives | `fromQueue` / `fromPubSub` |
| Web `ReadableStream` | `fromReadableStream` |
| Node.js `Readable` | `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.

```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](./concurrency/concurrency-coordination.md#queue).

**`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](./foundations/fibers-scopes-runtimes.md#pull) for the `Done` signal).

```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](https://effect.website/docs/v4/stream/creating) (its callback example passes no buffer options, and its "void" heading is not an API — use `Stream.succeed(undefined)`).

### 2. Transforming streams

| Need | Operators | Semantics that decide the choice |
|---|---|---|
| Per element, pure | `map` / `as` / `filter` / `filterMap` | `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. |
| Stop early | `take` / `takeWhile` / `takeUntil` / `takeRight` / `haltWhen` / `interruptWhen` | `takeWhile` stops *before* the first failing element; `takeUntil` *includes* 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. |
| Batch | `grouped(n)` / `groupedWithin(n, duration)` / `rechunk(n)` | `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. |
| Rate control | `throttle` / `debounce(duration)` / `schedule(schedule)` | `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 `merge`d in as a background side-stream. `intersperse` inserts a separator between elements. |

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

```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](https://effect.website/docs/v4/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`).

### 3. Running streams

| Runner | Behavior |
|---|---|
| `runCollect` | 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`. |

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

```ts
import { Effect, Stream } from "effect"

declare const employeeIds: Stream.Stream<string> // live HRIS feed: never ends on its own
declare 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:stream` `Readable`, maps its errors into the typed channel, and closes it when done by default; see [Platform & Runtime Hosts](./interfaces/platform-runtime-hosts.md).

Official guide: [Consuming Streams](https://effect.website/docs/v4/stream/consuming-streams).

### 4. Combining and splitting streams

| Goal | Operator | Termination and ordering |
|---|---|---|
| One after the other | `concat` / `flatten` (stream of streams) | The right side does not start until the left ends. |
| Both at once | `merge(that, { haltStrategy })` / `mergeAll({ concurrency, bufferSize })` | 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. |

```ts
import { Effect, Filter, Stream } from "effect"

interface RaiseRequest {
  readonly employeeId: string
  readonly percent: number
}

declare const requests: Stream.Stream<RaiseRequest> // finite: one merit cycle
declare 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`](./concurrency/concurrency-coordination.md#pubsub) directly.

### 5. Handling stream failures

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. |
| `onError` / `tapError` / `tapErrorTag` / `tapCause` / `tapDefect` | — | 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. |

```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](./deep-dives/streaming-ingestion-without-accidental-buffering.md)). **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`](./concurrency/scheduling-time.md#schedule) material.

Official guide: [Error handling in streams](https://effect.website/docs/v4/stream/error-handling) (its "timeoutFail", "timeoutFailCause", and "timeoutTo" headings are stale names; the code under them uses `Stream.timeoutOrElse`).

### 6. Owning resources inside a stream

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

```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](./deep-dives/streaming-ingestion-without-accidental-buffering.md) has the three tests.

Official guide: [Resourceful streams](https://effect.website/docs/v4/stream/resourceful-streams).

### 7. Where buffering hides

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](./concurrency/concurrency-coordination.md#queue) |
| `Stream.buffer({ capacity })` | up to `capacity` **elements**, 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 `capacity` **chunks** | 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 |
| `takeRight(n)`, `debounce`, `zipLatest` | the last `n` / the latest value | — | inherently bounded |
| `runCollect`, `Sink.collect()`, `mkString`, `mkUint8Array` | everything | — | only on sources you know are small; otherwise fold, `take`, or a bounded `Sink` |
| Framing decoders (`splitLines`, `Ndjson`, `Sse`, `SchemaBinary`) | one incomplete line, event, or frame | `Ndjson` and `splitLines`: no limit; `Sse`: 10 MiB; `SchemaBinary`: unset | `maxEventSize`, `maxFrameSize`, or `Stream.limitBytes` upstream |
| Source chunk size | one pulled chunk | `fromIterable`: 4096 elements; `FileSystem.stream`: 64 KiB | the source's `chunkSize` option |

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

The end-to-end version of this inventory, with a memory equation and tests, is [Streaming Ingestion Without Accidental Buffering](./deep-dives/streaming-ingestion-without-accidental-buffering.md).

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

`effect/Sink` — stable

`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`).

| Group | Sinks | Notes |
|---|---|---|
| Consume everything | `collect()`, `count`, `sum`, `last()`, `drain`, `reduce`, `reduceArray`, `forEach`, `forEachArray`, `timed` | `forEachArray` runs once per *pulled chunk*, whatever size that is. `timed` drains and returns the elapsed `Duration`. |
| Stop early (bounded) | `head()`, `take(n)`, `takeWhile`, `takeUntil`, `find`, `every`, `some`, `fold`, `foldUntil`, `reduceWhile`, `forEachWhile` | 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. |
| No input needed | `succeed`, `fail`, `die`, `never` | Finish (or not) without pulling. |
| Adapt | `map` / `mapEffect` (result), `mapInput` / `mapInputEffect` / `mapInputArray` (input), `mapError`, `mapEnd`, `ignoreLeftover`, `flatMap`, `orElse` | `mapInput` is what makes a generic sink reusable across element types. |

```ts
import { Effect, Sink, Stream } from "effect"

interface MeritRecommendation {
  readonly employeeId: string
  readonly currentSalary: number
  readonly recommendedSalary: number
}

// Built-in folds run with Stream.run.
const recCount = Stream.make(
  { employeeId: "e1", currentSalary: 100_000, recommendedSalary: 105_000 },
  { employeeId: "e2", currentSalary: 120_000, recommendedSalary: 126_000 }
).pipe(Stream.run(Sink.count)) // Effect<number> = 2

const firstRec = Stream.make(
  { employeeId: "e1", currentSalary: 100_000, recommendedSalary: 105_000 }
).pipe(Stream.run(Sink.head<MeritRecommendation>())) // Effect<Option<MeritRecommendation>>

// A custom Sink: compute the arithmetic mean merit percentage in one pass.
// Sink.reduceArray folds whole pulled arrays into state — efficient batch-at-a-time.
const averageIncreasePct = Sink.reduceArray<
  { totalPct: number; n: number },
  MeritRecommendation
>(
  () => ({ totalPct: 0, n: 0 }),
  (acc, batch) => {
    let { totalPct, n } = acc
    for (const r of batch) {
      totalPct += (r.recommendedSalary - r.currentSalary) / r.currentSalary
      n += 1
    }
    return { totalPct, n }
  }
).pipe(Sink.map(({ totalPct, n }) => (n === 0 ? 0 : (totalPct / n) * 100)))

// Run: average merit increase percentage across all recommendations.
const avgIncrease = Stream.make(
  { employeeId: "e1", currentSalary: 100_000, recommendedSalary: 105_000 },
  { employeeId: "e2", currentSalary: 120_000, recommendedSalary: 126_000 }
).pipe(Stream.run(averageIncreasePct)) // Effect<number> ≈ 5.0

// Sinks can do effects — forEach turns a per-element effect into a Sink.
const auditLog = Sink.forEach((r: MeritRecommendation) =>
  Effect.logInfo(`merit rec: ${r.employeeId} -> ${r.recommendedSalary}`)
)
const _audit = Stream.make(
  { employeeId: "e1", currentSalary: 100_000, recommendedSalary: 105_000 }
).pipe(Stream.run(auditLog))
```

### Adapting, leftovers, and repeatable batching

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

```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](#7-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](https://effect.website/docs/v4/sink/creating) (its HashSet/HashMap and "foldWeighted" headings are stale; the code folds with `Sink.reduce`, `Sink.reduceWhile`, and `Sink.fold`), [Sink operations](https://effect.website/docs/v4/sink/operations), [Leftovers](https://effect.website/docs/v4/sink/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.

## Channel

`effect/Channel` — stable

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

```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 = void

type 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`.

## ChannelSchema

`effect/ChannelSchema` — unstable

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.

```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

`effect/Take` — stable

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

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

## Ndjson

`effect/encoding/Ndjson` — unstable

Newline-delimited JSON codecs as channels. `Ndjson.decodeString()` splits on newlines and `JSON.parse`s 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.

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

## Sse

`effect/encoding/Sse` — unstable

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 `Event`s 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.

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

```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`](./interfaces/http-api.md#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.

## Csv

`effect/encoding/Csv` — unstable

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

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

## JsonArray

`effect/encoding/JsonArray` — unstable

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.parse`d; 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 `[]`.

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

## Xml

`effect/encoding/Xml` — experimental

Streaming XML 1.0 over text (`decodeString` / `encodeString`) or UTF-8 bytes (`decode` / `encode`). Decoders emit `Xml.Event`s (`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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { Stream } from "effect"
import { Xml } from "effect/encoding"

const feed = `<feed><entry id="1"><title>Q1 &amp; Q2</title></entry><entry id="2"><title>Q3</title></entry></feed>`

const entries = Stream.make(feed).pipe(
  Stream.pipeThroughChannel(Xml.decodeString()),
  Stream.pipeThroughChannel(Xml.elements(["feed", "entry"])),
  Stream.runCollect
)
// [{ name: "entry", attributes: { id: "1" }, children: [{ name: "title", attributes: {}, children: ["Q1 & Q2"] }] }, ...]
```

The decoder never reads external resources and never expands entities declared in a DOCTYPE — a reference to one fails with an `Unsupported` `XmlError` — 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.

## SchemaBinary

`effect/encoding/SchemaBinary` — unstable

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.

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

```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

`effect/encoding/Tar` — unstable

`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 `Unsupported` `TarError`. `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.

```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 `SizeMismatch` `TarError`, so a streamed entry's size must be known up front. Other `TarError` kinds are `InvalidHeader`, `Truncated`, `Unsupported`, and `BodyConsumed`.

## Zip

`effect/encoding/Zip` — experimental

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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { 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.

## Ini

`effect/encoding/Ini` — unstable

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.

```ts
import { Ini } from "effect/encoding"

const config = Ini.parse(`
enabled=true
region[]=eu-west-1
region[]=eu-south-2

[database.pool]
size=10
`)
// { enabled: true, region: ["eu-west-1", "eu-south-2"],
//   database: { pool: { size: "10" } } }
```

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.

## Toml

`effect/encoding/Toml` — unstable

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`](./data/functional-toolkit.md#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 `Date`s; 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.

```ts
import { Effect, Result } from "effect"
import { Toml } from "effect/encoding"

const parsed = Toml.parse(`
title = "Merit service"
ports = [8000, 8001]
[database]
enabled = true
credentials = { 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.

## Yaml

`effect/encoding/Yaml` — unstable

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.

```ts
import { Yaml } from "effect/encoding"

const config = Yaml.parse(`
name: merit-service
enabled: true
ports: [3000, 3001]
database:
  host: localhost
  roles: [reader, writer]
`)
```

```ts
import { Yaml } from "effect/encoding"

// Quote any value that contains ": " — unquoted, this line throws SyntaxError.
const reviewStep = Yaml.parse(`
step: calibration
description: "Use when: a manager disputes a merit rating"
`)
```

```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: 1
production:
  <<: *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.

## Json5

`effect/encoding/Json5` — unstable

A dependency-free [JSON5](https://spec.json5.org/) parser for hand-edited configuration. `Json5.parse(text)` returns `Result<unknown, EncodingError>`, failing with an [`EncodingError`](./data/functional-toolkit.md#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.

```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))
```

## Jsonc

`effect/encoding/Jsonc` — unstable

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.

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

# Scheduling & Time

_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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/06_schedule) and [DateTime](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/07_datetime) examples.

> **Official guides:** [Using schedules](https://effect.website/docs/v4/scheduling/using-schedules) introduces `Effect.repeat`, `Effect.schedule`, and `Effect.retry`; [Choosing and combining schedules](https://effect.website/docs/v4/scheduling/choosing-and-combining-schedules) walks through the constructors, limiters, and combinators; the [Schedule cookbook](https://effect.website/docs/v4/scheduling/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.

## Schedule

`effect/Schedule` — stable

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

### Primitive constructors

```ts
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.

### Composing schedules

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

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

Official guide: [Choosing and combining schedules](https://effect.website/docs/v4/scheduling/choosing-and-combining-schedules) (`upTo`, `while`, `modifyDelay`, `jittered`, `tap`, `max`, `min`, and `concat`).

### Filtering on the input

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.

```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:

```ts
import { Duration, Effect, Schedule } from "effect"

interface ProviderError {
  readonly status: 429 | 500 | 503
  readonly retryAfter: Duration.Duration | undefined
}

const providerRetry = Schedule.exponential("1 second").pipe(
  Schedule.setInputType<ProviderError>(),
  Schedule.modifyDelay(({ input, duration }) =>
    Effect.succeed(
      Duration.min(
        input.retryAfter === undefined
          ? duration
          : Duration.max(duration, input.retryAfter),
        Duration.minutes(1)
      )
    )
  ),
  Schedule.upTo({ times: 6 }),
  Schedule.while(({ input }) => input.status === 429 || input.status >= 500)
)
```

`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](#shorthand-options-for-retry-and-repeat) is shorter than `setInputType` plus `while`.

Official guide: [Retrying](https://effect.website/docs/v4/error-management/retrying).

### Polling with repeat and passthrough

`Effect.repeat` repeats on success and stops on failure. Combined with `Schedule.passthrough`, poll for a terminal state and get the final value back.

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

```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
      }))
    )
)
```

Official guide: [Using schedules](https://effect.website/docs/v4/scheduling/using-schedules).

### Shorthand options for retry and repeat

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

```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`).

### Retry policy checklist

A retry policy is a specification, so write it down before composing combinators, then [test its shape](#testing-a-policy).

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

### Scheduled repeat via Schedule.cron

`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](#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.

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

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

### Inspecting a schedule

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.

```ts
import { Duration, Effect, Pull, Schedule } from "effect"

const policy = Schedule.min([
  Schedule.exponential("250 millis"),
  Schedule.spaced("2 seconds")
]).pipe(Schedule.upTo({ times: 5 }))

const delays = Effect.gen(function*() {
  const step = yield* Schedule.toStep(policy)
  const millis: Array<number> = []

  const loop: Effect.Effect<void> = step(0, undefined).pipe( // caller supplies `now` and the input
    Effect.flatMap(([, delay]) => {
      millis.push(Duration.toMillis(delay))
      return loop
    }),
    Pull.catchDone(() => Effect.void)
  )

  yield* loop
  return millis // [250, 500, 1000, 2000, 2000]
})
```

Keep `Schedule.jittered` out of such a trace, or pin it with `Random.withSeed`; jitter draws from the `Random` service.

### Testing a policy

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

The complete harness is in [Recipe: Typed Retry with TestClock](./recipes/retry-with-test-clock.md); [TestClock](./tooling/testing-dev-tooling.md#testclock) covers the fork–adjust–join mechanics.

### Quick reference

| Combinator | Semantics |
| --- | --- |
| `recurs(n)` | Stop after n additional recurrences |
| `spaced(d)` | Fixed gap after each completion |
| `fixed(d)` | Cadence aligned to this schedule's first step; skip missed ticks |
| `windowed(d)` | Sleep to the next elapsed-time window boundary |
| `duration(d)` | Recur exactly once after `d` |
| `once` | Recur immediately once, with no delay; outputs `void` |
| `exponential(base)` | Exponential delay, 2× factor by default |
| `fibonacci(one)` | Fibonacci delay growth: `one`, `one`, `2·one`, `3·one`, `5·one`, … |
| `during(d)` | Stop after this much elapsed time; adds no delay |
| `forever` | 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.

## Duration

`effect/Duration` — stable

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

```ts
import { Duration } from "effect"

// Construction — pick the unit that matches your domain
const 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"

// Arithmetic
const totalReview = Duration.sum(Duration.weeks(1), Duration.days(2))   // 9 days
const doubled     = Duration.times(Duration.hours(2), 2)                // 4 h
const 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)   // false
Duration.between(Duration.days(300), {
  minimum: Duration.days(180),
  maximum: Duration.days(365)
})  // true — 300d is within the range

// Conversion
Duration.toMillis(Duration.days(1))       // 86_400_000
Duration.toSeconds(Duration.minutes(15)) // 900

// Human-readable formatting — useful in review-deadline notifications
Duration.format(Duration.sum(Duration.days(30), Duration.hours(4)))  // "30d 4h"

// ISO 8601 durations for wire formats that require them
Duration.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.

### Parsing untrusted durations and interop edges

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

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

See [Configuration & Secrets](./foundations/configuration-secrets.md) for loading the rest of the startup configuration.

Official guide: [Duration](https://effect.website/docs/v4/data-types/duration).

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

## DateTime

`effect/DateTime` — stable

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

### Computing dates and deadlines

```ts
import { DateTime, Effect } from "effect"

// EquityGrant domain type
interface EquityGrant {
  readonly employeeId: string
  readonly shares: number
  readonly grantDate: DateTime.Utc
}

// One-year cliff + monthly vesting over 48 months (standard 4-yr schedule).
// Returns the number of whole shares vested as of `asOf`.
function vestedShares(grant: EquityGrant, asOf: DateTime.Utc): number {
  const cliffEnd = grant.grantDate.pipe(DateTime.add({ months: 12 }))

  // Before the cliff: no shares vested
  if (DateTime.isLessThan(asOf, cliffEnd)) return 0

  // Count completed calendar months. A duration/30.44 approximation can
  // under-vest at the exact cliff because calendar months have varying lengths.
  const grantParts = DateTime.toParts(grant.grantDate)
  const asOfParts = DateTime.toParts(asOf)
  let monthsVested = (asOfParts.year - grantParts.year) * 12 + asOfParts.month - grantParts.month
  if (asOfParts.day < grantParts.day) monthsVested -= 1
  const fraction = Math.min(monthsVested / 48, 1)
  return Math.floor(grant.shares * fraction)
}

const checkVesting = Effect.gen(function*() {
  // Clock-driven "now" — safe in tests via TestClock
  const today: DateTime.Utc = yield* DateTime.now

  const grant: EquityGrant = {
    employeeId: "emp-101",
    shares: 4800,
    grantDate: DateTime.makeUnsafe("2023-01-15T00:00:00Z")
  }

  const vested = vestedShares(grant, today)
  yield* Effect.log(`Vested shares as of ${DateTime.formatIsoDate(today)}: ${vested}`)

  // Review-cycle deadline: 90 days from today
  const reviewDeadline = today.pipe(DateTime.add({ days: 90 }))
  yield* Effect.log(`Q3 merit review deadline: ${DateTime.formatIso(reviewDeadline)}`)
})
```

### Parsing safely

```ts
import { DateTime, Option } from "effect"

// make() returns Option.Option<DateTime.Utc> — never throws
const 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`](#constructing-zoned-values-from-wall-clock-input). `DateTime.fromDateUnsafe` throws on an invalid `Date`.

### Time zones (IANA)

```ts
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:

| Constructor | Accepts | Result |
| --- | --- | --- |
| `DateTime.zoneFromString(text)` | `"+05:30"` or `"Asia/Kolkata"` | `Option<TimeZone>` |
| `DateTime.zoneMakeNamed(id)` | IANA id | `Option<TimeZone.Named>` |
| `DateTime.zoneMakeNamedEffect(id)` | IANA id | Effect failing with `IllegalArgumentError` |
| `DateTime.zoneMakeNamedUnsafe(id)` | IANA id you control | Throws on an unknown id |
| `DateTime.zoneMakeOffset(millis)` / `DateTime.zoneMakeLocal()` | Offset in ms / the host zone | `TimeZone` |

```ts
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.

### Constructing zoned values from wall-clock input

`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:

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

### Calendar math and truncation

```ts
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 date
const 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 accrual
const 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 reminders
const 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.

### Providing the current zone via a Layer

```ts
import { DateTime, Layer } from "effect"

// Named IANA zone — HQ time for the compensation team
const 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 process
const local     = DateTime.layerCurrentZoneLocal

// An already-validated TimeZone value
const 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.

```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)
  )
```

### Formatting

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](https://effect.website/docs/v4/data-types/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.

## Cron

`effect/Cron` — stable

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

```ts
import { Cron, Result, DateTime } from "effect"

// parse() returns Result<Cron, CronParseError> — never throws
const 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 ET
const fires = Cron.match(quarterlyMerit, checkpoint)  // true

// Next payroll run after a given instant
const 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 runs
const 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.

### Repeated local times when clocks fall back

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.

```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.000Z
Cron.next(later, "2026-10-24T12:00:00Z")   // 2026-10-25T01:30:00.000Z
Cron.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.

### Building a Cron from structured fields

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.

```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.000Z
Cron.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.

### Driving a scheduled job with Schedule.cron

```ts
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 night

declare 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](./systems/cluster-sharding.md#clustercron) or a [Workflow](./systems/workflows-durable-execution.md). The schedule's output is a `Duration` (the computed wait), and an invalid expression fails the schedule with `Cron.CronParseError`.

Official guide: [Scheduling work with cron](https://effect.website/docs/v4/scheduling/cron).

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

## Random

`effect/Random` — stable

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

```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 }
})
```

### Deterministic testing

```ts
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`.

### Jitter without coupling to Math.random

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

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

# Data Structures

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](https://effect.website/docs/v4/data-types/chunk) (its `unsafeFromArray` heading is a stale name; use `Chunk.fromArrayUnsafe`), [HashSet](https://effect.website/docs/v4/data-types/hash-set), [Equal](https://effect.website/docs/v4/trait/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.

## Array

`effect/Array` — stable

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.

```ts
import { Array, Order, Result, Option, pipe } from "effect"

// --- domain types ---
type Employee = {
  readonly id: string
  readonly name: string
  readonly department: string
  readonly level: number
  readonly baseSalary: number
}

const employees: Employee[] = [
  { id: "e1", name: "Alice",   department: "Engineering", level: 4, baseSalary: 140_000 },
  { id: "e2", name: "Bob",     department: "Design",      level: 3, baseSalary: 110_000 },
  { id: "e3", name: "Carol",   department: "Engineering", level: 5, baseSalary: 165_000 },
  { id: "e4", name: "Dave",    department: "Design",      level: 2, baseSalary:  90_000 },
  { id: "e5", name: "Eve",     department: "Engineering", level: 3, baseSalary: 125_000 },
]

// --- building ---
// makeBy(n, f) — note: n is the first arg, f is second
const levels = Array.makeBy(6, (i) => i + 1)  // [1, 2, 3, 4, 5, 6]

// --- grouping by department ---
const byDept = Array.groupBy(employees, (e) => e.department)
// { Engineering: [Alice, Carol, Eve], Design: [Bob, Dave] } — values are NonEmptyArray

// --- sorting with multiple Orders ---
// Use Order.Number and Order.String (capitalised) for primitive orderings
const sorted = pipe(
  employees,
  Array.sortBy(
    Order.mapInput(Order.Number, (e: Employee) => e.level),
    Order.mapInput(Order.String, (e: Employee) => e.name)
  )
)
// [Dave(l2), Bob(l3), Eve(l3), Alice(l4), Carol(l5)]

// --- partition: split employees by whether salary is in-band ---
// CompBand: level -> { min, max }
const bands: Record<number, { min: number; max: number }> = {
  2: { min:  80_000, max: 100_000 },
  3: { min: 100_000, max: 140_000 },
  4: { min: 130_000, max: 160_000 },
  5: { min: 155_000, max: 200_000 },
}
// partition returns [passes, fails] — matches, then non-matches
const [inBand, outOfBand] = Array.partition(employees, (e) => {
  const band = bands[e.level]
  return band && e.baseSalary >= band.min && e.baseSalary <= band.max
    ? Result.succeed(e)
    : Result.fail({ employee: e, band })
})

// --- deduplication ---
const deptList = Array.dedupe(employees.map((e) => e.department))
// ["Engineering", "Design"]  — keeps first occurrence

// --- head/tail safely ---
const head: Option.Option<Employee> = Array.head(employees)
const tailOpt = Array.tail(employees)  // Option.some(rest)
```

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.

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

## Chunk

`effect/Chunk` — stable

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.

```ts
import { Chunk, pipe } from "effect"

// Accumulate employee IDs without copying the whole prefix on every append
let 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 copying
const engIds  = Chunk.make("e1", "e3", "e5")
const dsgIds  = Chunk.make("e2", "e4")
const allIds  = Chunk.appendAll(engIds, dsgIds)  // tree join; no element-by-element copy
console.log(Chunk.size(allIds))                   // 5

// Standard combinators work the same as Array
const 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 4
import { 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 |
| In | `Chunk.fromArrayUnsafe(xs)` / `fromNonEmptyArrayUnsafe(xs)` | 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](#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](https://effect.website/docs/v4/data-types/chunk) (it says `fromIterable` copies its input; that is only true for non-array iterables).

## HashMap

`effect/HashMap` — stable

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.

```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 allocations
let 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 instance
console.log(HashMap.get(allocations, alice2))  // Option.some(8000)

// Build a department → merit budget map
const meritBudgets: HashMap.HashMap<string, number> = HashMap.make(
  ["Engineering",  250_000],
  ["Design",       120_000],
  ["Product",       80_000]
)

// Map: apply a 5% uplift to every department budget
const uplifted = pipe(
  meritBudgets,
  HashMap.map((budget) => Math.round(budget * 1.05))
)

// Filter to departments with budget > $100k
const largeBudgets = pipe(
  uplifted,
  HashMap.filter((budget) => budget > 100_000)
)
// HashMap { Engineering: 262500, Design: 126000 }

// Fold into a total merit pool
const 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](./data/functional-toolkit.md#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.

## HashSet

`effect/HashSet` — stable

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

```ts
import { HashSet } from "effect"

// Native Set compares references; HashSet compares structure
const nativeSize = new Set([{ id: "e1" }, { id: "e1" }]).size             // 2
const hashSetSize = HashSet.size(HashSet.make({ id: "e1" }, { id: "e1" })) // 1

// An incidental field defeats dedupe — hidden own fields also count
const withNoise = HashSet.make(
  { id: "e1", requestId: "r-1" },
  { id: "e1", requestId: "r-2" }
)
const noisySize = HashSet.size(withNoise) // 2
```

```ts
import { HashSet, Data, pipe } from "effect"

// Track which employees are included in the current merit cycle
class 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 cycle
const 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-op
const deduped = pipe(cycleA, HashSet.add(new EmployeeRef({ id: "e1" })))
console.log(HashSet.size(deduped))  // still 3

// Iterate and collect IDs
const 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](./concurrency/state-mutable-references.md#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`.

Official guides: [HashSet](https://effect.website/docs/v4/data-types/hash-set), [Equal](https://effect.website/docs/v4/trait/equal).

## Trie

`effect/Trie` — stable

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.

```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 name
console.log(Trie.get(nameTrie, "alice johnson"))  // Option.some("e1")

// All names that start with what the user has typed so far
const suggestions = Arr.fromIterable(Trie.keysWithPrefix(nameTrie, "alice"))
// ["alice johnson", "alice kim"]  (alphabetical)

// All entries under "car" — useful for typeahead with result IDs
const 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 query
const 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 IDs
const 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"]
```

Key APIs: `map`, `filter`, `filterMap`, `reduce`, `forEach`, `modify`, `insert`, `remove`, `insertMany`, `removeMany`.

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.

## Graph

`effect/Graph` — unstable

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 => ...)`.

```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 evaluation
const 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-first
const 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 relationships
console.log(Graph.isAcyclic(orgGraph))  // true

// Export to Mermaid for HR dashboard visualisation
const 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 **throw** `Graph.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.

### Witnesses, reductions, and matchings

```ts
import { Array as Arr, Effect, Equal, Graph, Option } from "effect"

// Payroll-run steps; an edge means "must finish before"
const steps = Graph.directed<string, void>((g) => {
  const lock  = Graph.addNode(g, "lock-timesheets") // 0
  const gross = Graph.addNode(g, "compute-gross")   // 1
  const tax   = Graph.addNode(g, "compute-tax")     // 2
  const net   = Graph.addNode(g, "compute-net")     // 3
  Graph.addEdge(g, lock,  gross, undefined) // edge 0
  Graph.addEdge(g, gross, tax,   undefined) // edge 1
  Graph.addEdge(g, tax,   net,   undefined) // edge 2
  Graph.addEdge(g, gross, net,   undefined) // edge 3 — implied by 1 + 2
  Graph.addEdge(g, lock,  net,   undefined) // edge 4 — implied by 0 + 1 + 2
})

// Reachability without building a path
const netNeedsLock = Graph.hasPath(steps, 0, 3)                                  // true
const upstreamOfNet = Graph.hasPath(steps, 3, 0, { direction: "incoming" })      // true
const fanIn = Graph.inDegree(steps, 3)                                           // 3

// Keep only the edges that carry information; surviving edges keep their indexes
const minimal = Graph.transitiveReduction(steps)
const keptEdges = Graph.toSnapshot(minimal).edges.map((edge) => edge.index)      // [0, 1, 2]

// Every loop-free route, lazily — bound it
const routes = Arr.fromIterable(Graph.simplePaths(steps, { source: 0, target: 3, limit: 10 }))
// 3 routes; routes[0] = { path: [0, 1, 2, 3], edges: [0, 1, 2], distance: 3, costs: [...] }

// A cycle comes back as a witness you can print
const broken = Graph.mutate(steps, (g) => {
  Graph.addEdge(g, 3, 0, undefined) // edge 5: compute-net -> lock-timesheets
})
const witness = Graph.findCycle(broken)
// Option.some({ path: [0, 1, 2, 3, 0], edges: [0, 1, 2, 5] })
const describeCycle = Option.map(witness, ({ path }) =>
  path.map((index) => Option.getOrElse(Graph.getNode(broken, index), () => "?")).join(" -> ")
)

// Snapshots round-trip with identical indexes
const restored = Graph.fromSnapshot(Graph.toSnapshot(steps))
const sameGraph = Equal.equals(restored, steps) // true

// Calibration: pair each reviewer with one employee they are allowed to review
const eligibility = Graph.undirected<string, void>((g) => {
  const ana = Graph.addNode(g, "reviewer:ana") // 0
  const ben = Graph.addNode(g, "reviewer:ben") // 1
  const e1  = Graph.addNode(g, "employee:e1")  // 2
  const e2  = Graph.addNode(g, "employee:e2")  // 3
  Graph.addEdge(g, ana, e1, undefined)
  Graph.addEdge(g, ana, e2, undefined)
  Graph.addEdge(g, ben, e1, undefined)
})
const pairs = Graph.maximumBipartiteMatching(eligibility)
// [{ left: 0, right: 3, edge: 1 }, { left: 1, right: 2, edge: 2 }] — everyone is covered

// GraphError is thrown, so give it a typed channel at the Effect boundary
const reduceSafely = (graph: Graph.Graph<string, void, "directed">) =>
  Effect.try({
    try: () => Graph.transitiveReduction(graph),
    catch: (error) =>
      error instanceof Graph.GraphError ? error : new Graph.GraphError({ message: String(error) })
  })
const rejected = reduceSafely(broken) // fails with GraphError: "Cannot transitively reduce cyclic graph"
```

Use when modeling relationships — hierarchies, approval chains, dependency graphs, or any domain where connectivity is the core question.

## HashRing

`effect/HashRing` — unstable

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.

```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 weight
const ring = HashRing.make<PayrollWorker>()
HashRing.addMany(ring, [w1, w2, w3])

// Route any employee ID to the responsible payroll worker
const owner1 = HashRing.get(ring, "employee:e1")  // PayrollWorker | undefined
const owner2 = HashRing.get(ring, "employee:e42") // PayrollWorker | undefined

// Give w1 twice the load — it handles more employees
HashRing.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.

## Record

`effect/Record` — stable

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.

```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 headcounts
const 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 $100k
const largeDepts = Record.filter(budgets, (b) => b > 100_000)
// { Engineering: 250000, Design: 120000 }

// Collect to a summary array for a report
const 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 possible
const 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.

## Tuple

`effect/Tuple` — stable

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.

```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 code
const 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 orderings
const 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 transforms
const 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.

## Struct

`effect/Struct` — stable

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.

```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 UI
const publicProfile = Struct.pick(alice, ["id", "name", "level"])
// { id: "e1", name: "Alice", level: 4 }

// Omit salary for a non-confidential export
const nonConfidential = Struct.omit(alice, ["baseSalary"])
// { id: "e1", name: "Alice", departmentId: "d-eng", level: 4 }

// Evolve specific fields — apply a merit increase and a promotion
const 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.

## Iterable

`effect/Iterable` — stable

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.

```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 it
const 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 step
const 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 scenarios
const levels  = [3, 4, 5]
const ratings = ["exceeds", "meets", "below"] as const
const scenarios = Arr.fromIterable(Iterable.cartesian(levels, ratings))
// [[3,"exceeds"],[3,"meets"],[3,"below"],[4,"exceeds"],...]
```

Key APIs: makeBy / range / replicate / repeat / forever, map / flatMap / filter / filterMap, take / takeWhile / drop, zip / zipWith / intersperse, groupBy / group / groupWith, unfold / cartesian / cartesianWith, dedupeAdjacent / dedupeAdjacentWith, getSomes / getSuccesses / getFailures, head / isEmpty / size / forEach / reduce

`Iterable.groupBy` shares `Array.groupBy`'s typing: a literal-union key selector yields a record whose known keys are optional (see [Array](#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.

## NonEmptyIterable

`effect/NonEmptyIterable` — stable

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

```ts
import { NonEmptyIterable, Chunk } from "effect"

// A confirmed non-empty list of employees in a merit cycle
// NonEmptyChunk satisfies NonEmptyIterable
const cycle: Chunk.NonEmptyChunk<string> = Chunk.make("e1", "e2", "e3")

// Safely extract the first employee and the rest — no Option needed
const [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 cycle
function 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.

# The Functional Toolkit

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](https://effect.website/docs/v4/code-style/pattern-matching), [Branded Types](https://effect.website/docs/v4/code-style/branded-types), [Equal](https://effect.website/docs/v4/trait/equal), [Hash](https://effect.website/docs/v4/trait/hash), [Equivalence](https://effect.website/docs/v4/behaviour/equivalence), [Order](https://effect.website/docs/v4/behaviour/order), [BigDecimal](https://effect.website/docs/v4/data-types/bigdecimal), [Dual APIs](https://effect.website/docs/v4/code-style/dual); 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.

## Match

`effect/Match` — stable

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.

```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) => number
const 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.05
meritMultiplier({ _tag: "Meets" })                       // 0.02
```

**One-shot matching.** Use `Match.value` when you have a value in hand:

```ts
import { Match } from "effect"

type PerformanceRating =
  | { _tag: "Exceeds"; percentileRank: number }
  | { _tag: "Meets" }
  | { _tag: "Below"; pipPlan: string }

const reviewNote = (rating: PerformanceRating) =>
  Match.value(rating).pipe(
    Match.tag("Exceeds", () => "Eligible for accelerated promotion"),
    Match.tag("Meets",   () => "Eligible for standard merit increase"),
    Match.tag("Below",   ({ pipPlan }) => `On PIP: ${pipPlan}`),
    Match.exhaustive
  )

reviewNote({ _tag: "Below", pipPlan: "Q3-improvement" })
```

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

```ts
import { Match, pipe } from "effect"

const classifyRaise = pipe(
  Match.type<unknown>(),
  Match.when(Match.string,  (s) => `Named plan: ${s}`),
  Match.when(Match.number,  (n) => `Fixed amount: $${n}`),
  Match.when({ _tag: "Exceeds" }, () => "High performer — top-of-band eligible"),
  Match.orElse(() => "No raise recommendation")
)
```

**Advanced arms.**

Key APIs: `Match.tag`, `Match.tags`, `Match.tagsExhaustive`, `Match.tagStartsWith`, `Match.when`, `Match.whenOr`, `Match.whenAnd`, `Match.not`, `Match.discriminator`, `Match.discriminators`, `Match.discriminatorsExhaustive`, `Match.instanceOf`, `Match.is`

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.

```ts
import { Match } from "effect"

type ReviewStatus = "draft" | "submitted" | "calibrated" | "final"

const isEditable = Match.type<ReviewStatus>().pipe(
  Match.literals({ draft: () => true, submitted: () => true }),
  Match.orElse(() => false)
)

const statusLabel = Match.type<ReviewStatus>().pipe(
  Match.literalsExhaustive({
    draft: () => "Draft",
    submitted: () => "Awaiting calibration",
    calibrated: () => "Calibrated",
    final: () => "Final"
  })
)

isEditable("calibrated") // false
statusLabel("submitted") // "Awaiting calibration"
```

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

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

### Closing a matcher

| Finalizer | Result when nothing matched | Use when |
| --- | --- | --- |
| `Match.exhaustive` | Compile error while cases remain | 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 |

```ts
import { Match } from "effect"

type Reviewer = { readonly role: "admin" | "analyst" | "viewer"; readonly level: number }

// Partial matcher: predicates nest inside object patterns, `option` closes it
const 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 here
type 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](./foundations/errors-option-result.md#effect-error-handling).

Use when exhaustively pattern-matching unions — discriminated unions, workflow state machines, error types — and you want the compiler to enforce coverage.

Official guide: [Pattern Matching](https://effect.website/docs/v4/code-style/pattern-matching).

## Order

`effect/Order` — stable

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

```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 field
const byLevel = Order.mapInput(Order.Number, (e: { level: number }) => e.level)

// Combine: primary sort by level, secondary sort by baseSalary within the same level
const 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 directly
const 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 comparator
const byBand = Order.Struct({
  level: Order.Number,
  label: Order.String,
})
```

**Combinators at a glance:**

Key APIs: Order.make, Order.mapInput, Order.combine, Order.combineAll, Order.flip, Order.Tuple, Order.Struct, Order.min, Order.max, Order.clamp, Order.isBetween, Order.isLessThan, Order.isGreaterThan, Order.isLessThanOrEqualTo, Order.isGreaterThanOrEqualTo

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

```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 inclusive
Order.max(Order.Number)(120_000, 95_000)        // 120_000
Order.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.

Official guide: [Order](https://effect.website/docs/v4/behaviour/order).

## Equal

`effect/Equal` — stable

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`):

```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 id
Equal.equals(emp1, emp3) // false — different id
```

### Equality pitfalls and opt-outs

- **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, `ArrayBuffer`s, and `SharedArrayBuffer`s compare and hash by their bytes; an `ArrayBuffer` never equals a `SharedArrayBuffer`, and a detached buffer is equal only to itself. Use [`Bytes.Equivalence`](#bytes) when you only need a byte comparison.
- **Mutable cells are not identity-keyed.** A [`Ref`](./concurrency/state-mutable-references.md#ref) or [`MutableRef`](./concurrency/state-mutable-references.md#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.
- **Native collections ignore `Equal`.** `new Set([{ id: "e1" }, { id: "e1" }]).size` is `2`; only Effect's hash collections ([HashMap](./data/data-structures.md#hashmap), [HashSet](./data/data-structures.md#hashset)) dedupe structurally.
- **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.

```ts
import { Equal } from "effect"

const recommendation = { employeeId: "emp-001", bps: 150 }

Equal.equals(recommendation, { employeeId: "emp-001", bps: 150 }) // true — structural by default
Equal.equals(NaN, NaN)                                            // true

// An incidental field makes "the same" record different
Equal.equals(
  { employeeId: "emp-001", requestId: "r-1" },
  { employeeId: "emp-001", requestId: "r-2" }
) // false

// Identity semantics on demand; the original object is untouched
const byIdentity = Equal.byReference(recommendation)
Equal.equals(byIdentity, { employeeId: "emp-001", bps: 150 }) // false
Equal.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`.

Official guide: [Equal](https://effect.website/docs/v4/trait/equal).

## Hash

`effect/Hash` — stable

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:

```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 available
Hash.string("analyst@example.com")
Hash.number(3)
Hash.array(["L3", "Engineering", "NYC"])
Hash.structure({ departmentId: "eng", level: 3 })   // structureKeys over all own keys
const 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`.

Official guide: [Hash](https://effect.website/docs/v4/trait/hash).

## Equivalence

`effect/Equivalence` — stable

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:

```ts
import { Equivalence } from "effect"

// Primitive equivalences (Capitalized exports)
Equivalence.String   // case-sensitive exact match
Equivalence.Number   // NaN-aware
Equivalence.Boolean
Equivalence.Date     // by getTime()

// Struct equivalence: compare comp bands by level and salary midpoint
const 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 only
const eqById = Equivalence.mapInput(
  Equivalence.String,
  (emp: { id: string }) => emp.id
)
```

Key APIs: Equivalence.make, Equivalence.strictEqual, Equivalence.String / Number / Boolean / BigInt / Date, Equivalence.mapInput, Equivalence.combine, Equivalence.combineAll, Equivalence.Struct, Equivalence.Tuple, Equivalence.Array, Equivalence.Record

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

Official guides: [Equivalence](https://effect.website/docs/v4/behaviour/equivalence), [Schema-derived equivalence](https://effect.website/docs/v4/schema/equivalence).

## Ordering

`effect/Ordering` — stable

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.

```ts
import { Ordering } from "effect"

// Combine two sub-results: primary ordering wins, fall back to secondary on tie
const combined: Ordering.Ordering = firstResult !== 0 ? firstResult : secondResult
Ordering.reverse(-1)  // 1
Ordering.match(combined, { onLessThan: () => "lower band", onEqual: () => "same band", onGreaterThan: () => "higher band" })
```

## Combiner

`effect/Combiner` — stable

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 `A`s together. Carries no identity element — that is what `Reducer` adds. Note: `Combiner.intercalate` is curried — provide the separator first, then the base combiner.

```ts
import { Combiner, Number, String } from "effect"

// Sum two department merit budgets
const 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 budgets
const MinBudget = Combiner.min(Number.Order)
const MaxBudget = Combiner.max(Number.Order)

MinBudget.combine(120_000, 95_000)  // 95_000
MaxBudget.combine(120_000, 95_000)  // 120_000

// always keep the first / last value
const First = Combiner.first<string>()
const Last  = Combiner.last<string>()

// Intercalate: insert a separator between department codes
// Note: intercalate is curried — separator first, then combiner
const 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.

## Reducer

`effect/Reducer` — stable

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

```ts
import { Reducer, Number } from "effect"

// Custom reducer for summing merit budgets
const BudgetSum = Reducer.make<number>((a, b) => a + b, 0)

// Sum department merit budgets — returns 0 for an empty org
const departments = [120_000, 95_000, 80_000, 150_000]
const totalBudget = departments.reduce(
  (acc, n) => Number.ReducerSum.combine(acc, n),
  Number.ReducerSum.initialValue
)
// => 445_000

BudgetSum.combine(120_000, 95_000)  // 215_000
BudgetSum.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`.

## Brand

`effect/Brand` — stable

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

```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 integer
type 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 cap
type 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">`.

```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](./data/schema.md#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](https://effect.website/docs/v4/code-style/branded-types) (its illustrative `Brand` declaration uses a symbol key; brand keys are strings), [Schema branded types](https://effect.website/docs/v4/schema/advanced-usage).

## Optic

`effect/Optic` — stable

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.

```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 field
const 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_000
annualBase.replace(130_000, plan)               // new plan with base.annual = 130_000

// modify returns a function — apply it to the data
const 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 grant
const 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:

```ts
import { Optic, Option, Result, Schema } from "effect"

// Focus into Option — e.g. an optional managerId
const 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 positive
const positiveSalary = Optic.id<number>().compose(
  Optic.fromChecks(Schema.isGreaterThan(0))
)
```

**Traversals** focus on all elements of a collection at once using `.forEach`:

```ts
import { Optic, Schema } from "effect"

type OrgChart = { readonly departments: ReadonlyArray<{ readonly headcount: number }> }

// Traversal over all department headcounts greater than 0
const positiveHeadcounts = Optic.id<OrgChart>()
  .key("departments")
  .forEach((dept) => dept.key("headcount").check(Schema.isGreaterThan(0)))

// Apply a function to every matching element
const 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.

```ts
import { Optic, pipe } from "effect"

type CompensationPlan = {
  readonly employeeId: string
  readonly base: { readonly annual: number; readonly currency: string }
  readonly bonus?: number
}

const plan: CompensationPlan = {
  employeeId: "emp-001",
  base: { annual: 120_000, currency: "USD" },
  bonus: 5_000
}

const annualBase = Optic.id<CompensationPlan>().key("base").key("annual")
const bonus = Optic.id<CompensationPlan>().optionalKey("bonus")

Optic.get(plan, annualBase) // 120_000

// Data-last form composes in a pipeline; writing `undefined` removes the optional key
const nextCycle = pipe(
  plan,
  Optic.modify(annualBase, (salary) => Math.round(salary * 1.04)),
  Optic.replace(bonus, undefined)
)
// { employeeId: "emp-001", base: { annual: 124800, currency: "USD" } }
```

Use when updating deeply nested immutable data without boilerplate spread chains, or composing readers and writers for the same path.

## Predicate

`effect/Predicate` — stable

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:

```ts
import { Predicate } from "effect"

// Primitives
Predicate.isString("hello")    // true
Predicate.isNumber(42)         // true
Predicate.isNullish(null)      // true
Predicate.isNullish(undefined) // true
Predicate.isNotUndefined(0)    // true
Predicate.isTagged("Exceeds")({ _tag: "Exceeds", percentileRank: 95 })  // true

// Merit eligibility: employee must have a rating that is not "Below" and a level >= 2
const isMeritEligible = Predicate.and(
  Predicate.isTagged("Exceeds") as Predicate.Predicate<{ _tag: string; level: number }>,
  (e: { _tag: string; level: number }) => e.level >= 2
)

// Combinators
const isStringOrNumber  = Predicate.or(Predicate.isString, Predicate.isNumber)
const isNotNull         = Predicate.not(Predicate.isNull)

// Struct predicate: every field must pass — validate a RaiseRecommendation shape
const isRaiseRecommendation = Predicate.Struct({
  employeeId: Predicate.isString,
  amount:     Predicate.isNumber,
})

// Compose refinements: non-empty department code
const isNonEmptyString = Predicate.compose(
  Predicate.isString,
  (s: string): s is string => s.length > 0
)

// hasProperty type-safe property check
Predicate.hasProperty({ level: 3 }, "level")  // true

// Logical shortcuts
Predicate.every([Predicate.isString, (s: string) => s.length > 3])
Predicate.some([Predicate.isNull, Predicate.isUndefined])
```

Key APIs: isString, isNumber, isBoolean, isBigInt, isSymbol, isUndefined, isNull, isNullish, isObject, isFunction, isIterable, isDate, isError, isTagged, hasProperty, isTupleOf, and, or, not, xor, implies, compose

Use for runtime type narrowing, building eligibility predicates, or passing guards to `Array.filter`.

## BigDecimal

`effect/BigDecimal` — stable

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.

```ts
import { BigDecimal, pipe } from "effect"

// ── Merit increase calculation ────────────────────────────────────────────────
// Base salary $120,000.00 × 4% merit raise
const 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 object
BigDecimal.round(newSalary, { scale: 0, mode: "half-from-zero" })
// => BigDecimal representing 124800

// ── Equity grant value ────────────────────────────────────────────────────────
// 5,000 RSUs at current price $48.75 each
const 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
) // true

BigDecimal.equals(
  BigDecimal.fromStringUnsafe("124800.00"),
  BigDecimal.fromStringUnsafe("124800.000")
) // true — comparison ignores scale, so trailing zeros do not matter

// Safe division returns Option
const perShare = BigDecimal.divide(
  BigDecimal.fromStringUnsafe("243750"),
  BigDecimal.fromStringUnsafe("5000")
) // Option<BigDecimal> → Option.some(48.75)
```

**Rounding modes** are lowercase kebab strings: `"ceil"`, `"floor"`, `"to-zero"`, `"from-zero"`, `"half-ceil"`, `"half-floor"`, `"half-to-zero"`, `"half-from-zero"` (default), `"half-even"` (banker's), `"half-odd"`. Use `BigDecimal.round(value, { scale, mode })`.

**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 `format` **never 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"`).

```ts
import { BigDecimal, Option } from "effect"

const gross = BigDecimal.make(12_345n, 2)                        // 123.45, exactly
const parsed = BigDecimal.fromString("12,5")                     // Option.none() — untrusted text
const product = BigDecimal.multiply(gross, BigDecimal.make(40n, 1))
// 123.45 × 4.0: value 493800n, scale 3

const normalized = BigDecimal.normalize(product)                 // value 4938n, scale 1
const label = BigDecimal.format(product)                         // "493.8" — not "493.80"

const sameNumber = BigDecimal.equals(BigDecimal.make(105n, 2), BigDecimal.make(1050n, 3)) // true
const parsedOrZero = Option.getOrElse(parsed, () => BigDecimal.make(0n, 0))
```

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

Key APIs: make / fromString / fromStringUnsafe / fromBigInt / fromNumber / fromNumberUnsafe, sum / subtract / multiply / divide / divideUnsafe / remainder / remainderUnsafe, negate / abs / sign, round / truncate / ceil / floor / scale / normalize, min / max / clamp / between, isLessThan / isLessThanOrEqualTo / isGreaterThan / isGreaterThanOrEqualTo, isZero / isPositive / isNegative / isInteger, equals / Order / Equivalence, format / toExponential / toNumberUnsafe

`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](https://effect.website/docs/v4/data-types/bigdecimal) (its `unsafeFromString` / `unsafeFromNumber` headings are stale names; use `fromStringUnsafe` / `fromNumberUnsafe` or the safe `fromNumber`).

## Rational

`effect/Rational` — unstable

An exact fraction: a `bigint` `numerator` and a positive `bigint` `denominator`, always reduced to lowest terms (zero is `0/1`). Where [BigDecimal](#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.

```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.6667
const roundedDown = Rational.toBigDecimal(Rational.makeUnsafe(2n, 3n), { scale: 4, mode: "floor" }) // 0.6666
Rational.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](./data/schema-tooling.md#schemarepresentation) containing `Schema.Rational` needs `SchemaRepresentation.RationalReviver` passed to `fromRepresentation`.

Key APIs: make / makeUnsafe / fromBigInt / fromBigDecimal / fromNumber / fromNumberUnsafe / fromString / fromStringUnsafe, sum / sumAll / subtract / multiply / multiplyAll / divide / divideUnsafe / pow / powUnsafe, negate / abs / sign, equals / Order / Equivalence, isLessThan / isLessThanOrEqualTo / isGreaterThan / isGreaterThanOrEqualTo / between / clamp / min / max, isZero / isPositive / isNegative / isInteger, format / toBigDecimal / toNumberUnsafe

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

## ByteSize

`effect/ByteSize` — unstable

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 — `FileSystem` `File.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.

```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: string
ByteSize.fromString(quotaFromAdminForm) // Option<ByteSize>
ByteSize.fromString("1.5 KiB")          // Option.some(1536n) — fractions allowed
ByteSize.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 discarded
const 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)                  // true
ByteSize.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.

## Differ

`effect/Differ` — stable

An interface for patch-based change tracking. A `Differ<T, Patch>` computes the difference between two `T`s 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:

```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_000
BudgetDiffer.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.

## TextDiff

`effect/TextDiff` — experimental

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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { TextDiff } from "effect"

const before = "level: 3\nband: B\n"
const after = "level: 4\nband: B\n"

const edits = TextDiff.lines(before, after)
// [{ _tag: "Delete", items: ["level: 3\n"] }, { _tag: "Insert", items: ["level: 4\n"] }, { _tag: "Equal", items: ["band: B\n"] }]

TextDiff.unified(edits, { fromFile: "before.yaml", toFile: "after.yaml" })
// "--- before.yaml\n+++ after.yaml\n@@ -1,2 +1,2 @@\n-level: 3\n+level: 4\n band: B\n"

TextDiff.applyText(before, edits)                  // Result.succeed(after)
TextDiff.applyText(after, TextDiff.invert(edits))  // Result.succeed(before)
```

> **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](#differ).

## SemVer

`effect/SemVer` — unstable

Immutable [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) 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.

```ts
import { Result, SemVer } from "effect"

const current = SemVer.parseUnsafe("1.4.2-rc.1+build.7")
SemVer.isPrerelease(current)              // true
SemVer.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.

## SemVerRange

`effect/SemVerRange` — unstable

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.

```ts
import { Option, SemVer, SemVerRange } from "effect"

const supported = SemVerRange.parseUnsafe("^1.4.0")

SemVerRange.matches(supported, "1.9.3")      // true
SemVerRange.matches(supported, "2.0.0")      // false
SemVerRange.matches(supported, "1.5.0-rc.1") // false — pre-releases need opting in

SemVerRange.maxSatisfying(supported, ["1.4.0", "1.6.1", "2.0.0", "1.7.0-rc.1"]).pipe(
  Option.map(SemVer.format)
) // Option.some("1.6.1")
```

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.

## Newtype

`effect/Newtype` — unstable

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:

```ts
import { Newtype, Optic, Equivalence, Order } from "effect"

// Distinguish salary dollars from equity dollars at the type level
interface SalaryUSD extends Newtype.Newtype<"SalaryUSD", number> {}
const salaryIso = Newtype.makeIso<SalaryUSD>()

const base: SalaryUSD = salaryIso.set(120_000)   // 120_000 branded as SalaryUSD
salaryIso.get(base)                               // 120_000 (the plain number)

// Lift Order and Equivalence for the underlying number
const 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.

## Function

`effect/Function` — stable

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.

```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 dollar
const 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 / constant
F.identity(42)           // 42
F.constant(true)()       // true
F.constNull()            // null
F.constUndefined()       // undefined

// flip: swap the first two arguments of a function
const sub = (a: number) => (b: number) => a - b
F.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 it
const 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`.

```ts
import { Function as F, pipe } from "effect"

// `dual(2, ...)`: two arguments means data-first, one argument returns the pipeable form
const 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_800
pipe(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](https://effect.website/docs/v4/getting-started/building-pipelines) (it states that `Option` and `Result` can be yielded inside `Effect.gen`; they cannot — convert with `Effect.fromOption` / `Effect.fromResult`), [Dual APIs](https://effect.website/docs/v4/code-style/dual).

## Number

`effect/Number` — stable

Pipeable arithmetic, comparisons, and ready-made `Reducer`s 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`.

```ts
import { Number as N, pipe } from "effect"

pipe(3, N.increment)          // 4
pipe(-1, N.sign)              // -1
N.sumAll([80_000, 95_000, 120_000])   // 295_000
N.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
```

## String

`effect/String` — stable

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.

```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 kept

S.camelCase("merit_cycle")      // "meritCycle"
S.pascalCase("comp_band")       // "CompBand"
S.configCase("Payroll API URL") // "PAYROLL_API_URL"
// data-last: searchString first, then self
S.indexOf("emp")("hris-emp-001")  // Option.some(5)
```

## Boolean

`effect/Boolean` — stable

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

```ts
import { Boolean as B, pipe } from "effect"

const isPromotionEligible = true
pipe(isPromotionEligible, B.not)  // false
B.match(isPromotionEligible, {
  onTrue:  () => "schedule promotion review",
  onFalse: () => "standard merit only"
})
B.every([true, true, false])       // false  — all departments approved?
B.ReducerAnd.combine(true, false)  // false
```

## BigInt

`effect/BigInt` — stable

Arithmetic and comparison for native `bigint`. Mirrors the `Number` API — pipeable `sum`, `multiply`, `subtract`, `divide`, `remainder`, `abs`, `sign`, `clamp`, `between`. Additional math: `BigInt.gcd`, `BigInt.lcm`, `BigInt.sqrt`/`sqrtUnsafe`. Safe conversions: `BigInt.toNumber` → `Option`, `BigInt.fromString` → `Option`, `BigInt.fromNumber` → `Option`. Ready-made reducers: `BigInt.ReducerSum`, `BigInt.ReducerMultiply`; combiners: `BigInt.CombinerMax`, `BigInt.CombinerMin`.

```ts
import { BigInt as BI } from "effect"

// Share counts — large integers, safe as bigint
const totalGranted  = 50_000n
const totalVested   = 32_500n
const unvested      = BI.subtract(totalGranted, totalVested)  // 17_500n

BI.gcd(12n, 8n)               // 4n
BI.sqrt(10_000n)               // Option.some(100n)
BI.toNumber(totalGranted)      // Option.some(50000)
```

## Pipeable

`effect/Pipeable` — stable

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.

```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)
```

## Symbol

`effect/Symbol` — stable

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.

## RegExp

`effect/RegExp` — stable

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.

```ts
import { RegExp as RE } from "effect"

// Safely search for an employee ID that might contain regex metacharacters
const empId = "emp.001+special"
const pattern = new RE.RegExp(`^${RE.escape(empId)}$`)
// pattern: /^emp\.001\+special$/
```

## UndefinedOr

`effect/UndefinedOr` — stable

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

```ts
import { UndefinedOr } from "effect"

// An employee's manager may or may not be set
const managerId: string | undefined = employee.managerId

UndefinedOr.map(managerId, (id) => `mgr:${id}`)   // string | undefined
UndefinedOr.getOrThrow(managerId)                   // string or throws
UndefinedOr.match(managerId, {
  onDefined:   (id) => `Reports to ${id}`,
  onUndefined: ()   => "No manager assigned (top-level)"
})
```

## Bytes

`effect/Bytes` — unstable

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.

```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])) // true

const 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](./interfaces/cryptography.md).

## Base64

`effect/encoding/Base64` — stable

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.

```ts
import { Result } from "effect"
import { Base64 } from "effect/encoding"

// Encode an employee token payload for transmission
const encoded = Base64.encode("emp-001:merit-2025")  // base64 string
const 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>
```

## Base64Url

`effect/encoding/Base64Url` — stable

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

```ts
import { Base64Url } from "effect/encoding"

const token = Base64Url.encode(new Uint8Array([0xfb, 0xff, 0xbf]))  // "-_-_"
const back = Base64Url.decode(token)                                 // Result<Uint8Array, EncodingError>

Base64Url.encodePadded("fo") // "Zm8="
Base64Url.decode("Zg=")      // Result.fail(EncodingError) — partially padded
```

## Hex

`effect/encoding/Hex` — stable

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`](./interfaces/cryptography.md#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.

```ts
import { Hex } from "effect/encoding"

// Hex encoding for audit-log checksums
Hex.encode(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))  // "deadbeef"
Hex.decode("deadbeef")                                 // Result<Uint8Array, EncodingError>

const correlationId = Hex.random(16)  // e.g. "d515b35eeabef8b9"
const traceLikeId = Hex.random(32)    // 32 lowercase hex characters
```

## EncodingError

`effect/encoding/EncodingError` — stable

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"`](./concurrency/streaming-channels.md#json5), …), 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`](./foundations/errors-option-result.md#result) combinators rather than with `Effect.catch`.

```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"
}
```

## Inspectable

`effect/Inspectable` — stable

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

```ts
import { Inspectable, Formatter } from "effect"

class CompBand extends Inspectable.Class {
  readonly level: number
  readonly min: number
  readonly mid: number
  readonly max: number

  constructor(level: number, min: number, mid: number, max: number) {
    super()
    this.level = level
    this.min = min
    this.mid = mid
    this.max = max
  }

  override toJSON() {
    return { _tag: "CompBand", level: this.level, min: this.min, mid: this.mid, max: this.max }
  }
  override toString(): string {
    return Formatter.format(this.toJSON())
  }
}

console.log(new CompBand(3, 90_000, 120_000, 150_000))
// { _tag: 'CompBand', level: 3, min: 90000, mid: 120000, max: 150000 }

String(new CompBand(3, 90_000, 120_000, 150_000))
// '{"_tag":"CompBand","level":3,"min":90000,"mid":120000,"max":150000}'
```

## Types

`effect/Types` — stable

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.

## Utils

`effect/Utils` — stable

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.

```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.gen

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

## Unify

`effect/Unify` — stable

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.

## HKT

`effect/HKT` — stable

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

# Schema

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](./data/schema-in-depth.md) continues with annotations, serialization, recursion, parse options, optional fields, and effectful schemas; [Schema Tooling & Internals](./data/schema-tooling.md) covers the AST, compilers, issues, JSON Schema, and `TestSchema`.

> **Official companion:** Effect's release-matched [comprehensive Schema guide](https://github.com/Effect-TS/effect/blob/effect%404.1.4/packages/effect/SCHEMA.md) goes substantially deeper into codecs, constraints, transformations, serialization, generated tooling, integrations, and migration.
>
> **Official guides:** [Introduction to Effect Schema](https://effect.website/docs/v4/schema/introduction) (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.

## Schema

`effect/Schema` — stable

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.

```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](./data/schema-in-depth.md#9-effectful-schemas-and-services): 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](./data/schema-in-depth.md#5-parse-options-are-boundary-policy).

Official guide: [Getting Started](https://effect.website/docs/v4/schema/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.

```ts
import { Schema } from "effect"

const schema = Schema.FiniteFromString
type 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.

Official guide: [Schema Projections](https://effect.website/docs/v4/schema/projections).

### 3. Structs, the workhorse

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

```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.Type

const 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](./data/schema-in-depth.md#6-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`](./data/data-structures.md#struct) module supplies those functions.

```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 absent
const LevelChange = Employee.mapFields(Struct.mapPick(["level"], Schema.optionalKey)) // only `level` optional
const 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:** `mapFields` **drops 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.

### 4. Unions, literals, records, tuples

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

```ts
import { Schema } from "effect"

const PerformanceRating = Schema.Literals(["exceeds", "meets", "below"])
const GrantKind = Schema.Union([Schema.Literal("RSU"), Schema.Literal("ISO")])
// merit budget per department: { readonly [departmentId: string]: BigDecimal }
const MeritBudgets = Schema.Record(Schema.String, Schema.BigDecimal)
// a comp-band row: readonly [level, salaryMid]
const BandRow = Schema.Tuple([
  Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })),
  Schema.BigDecimalFromString
])

Schema.decodeUnknownSync(PerformanceRating)("exceeds")   // "exceeds"
Schema.decodeUnknownSync(BandRow)([5, "190000"])         // [5, BigDecimal]
```

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`:

```ts
import { Schema } from "effect"

const CompAction = Schema.TaggedUnion({
  Raise:     { amount: Schema.BigDecimal },
  Promotion: {
    fromLevel: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })),
    toLevel: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 }))
  },
  Bonus:     { amount: Schema.BigDecimal, reason: Schema.String }
})

const describe = CompAction.match({ _tag: "Promotion", fromLevel: 4, toLevel: 5 }, {
  Raise:     (r) => `raise of ${r.amount}`,
  Promotion: (p) => `promote ${p.fromLevel} -> ${p.toLevel}`,
  Bonus:     (b) => `bonus: ${b.reason}`
})
```

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

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

```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](https://effect.website/docs/v4/schema/basic-usage) (its "Transforming Keys" passage is stale: records accept transformed key schemas).

### 5. Refinements — `check` and `refine`

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

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

| Carrier | Checks |
| --- | --- |
| String | `isMinLength(n)`, `isMaxLength(n)`, `isBetweenLength(min, max)`, `isMinCodePoints(n)`, `isMaxCodePoints(n)`, `isBetweenCodePoints(min, max)`, `isNonEmpty()`, `isPattern(regExp)`, `isStartingWith`, `isEndingWith`, `isIncluding`, `isTrimmed`, `isLowercased`, `isUppercased`, `isCapitalized`, `isUncapitalized`, `isUUID(version?)`, `isGUID`, `isULID`, `isBase64`, `isBase64Url`, `isAscii()` (ASCII characters only) |
| Number | `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) |
| Map / Set, object | `isMinSize`, `isMaxSize`, `isBetweenSize`; `isMinProperties`, `isMaxProperties`, `isBetweenProperties`, `isPropertyNames(keySchema)` |
| `Date`, `bigint`, `BigDecimal` | 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.

```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](#6-transformations-decodeto-getters)). 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`](./data/schema-tooling.md#schemagetter)), 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.

Official guide: [Filters](https://effect.website/docs/v4/schema/filters).

### 6. Transformations — `decodeTo` + getters

Transformations are written with `decodeTo(target, transformation)`, where the transformation is a `SchemaTransformation` (two-way) or a pair of one-way `SchemaGetter`s.

```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")    // 4000
Schema.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`.

```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](./data/schema-in-depth.md#8-custom-error-messages)).

```ts
import { Schema } from "effect"

const PageRequest = Schema.Struct({ page: Schema.Int, size: Schema.Int })

// string -(URI-decode)-> string -(JSON.parse + validate)-> PageRequest
const PageFromQueryValue = Schema.StringFromUriComponent.pipe(
  Schema.decodeTo(Schema.fromJsonString(PageRequest))
)

Schema.decodeUnknownSync(PageFromQueryValue)("%7B%22page%22%3A1%2C%22size%22%3A20%7D")
// { page: 1, size: 20 }
```

Getters that call services or do asynchronous work are covered in [Effectful schemas and services](./data/schema-in-depth.md#9-effectful-schemas-and-services).

Official guide: [Schema Transformations](https://effect.website/docs/v4/schema/transformations) (it still spells `transformEffect` as `transformOrFail`, and it predates `SchemaGetter.forbiddenEncoding` — this page and the edition's tagged source win).

### 7. Branded schemas

`brand` narrows the type nominally (no runtime check). `fromBrand` additionally wires in a `Brand.Constructor`'s checks.

```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`](./data/functional-toolkit.md#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`.

```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
```

Official guide: [Branded Types](https://effect.website/docs/v4/code-style/branded-types).

### 8. Default values

`withConstructorDefault` fills a field when building a value with `Schema.make`/`new`. `withDecodingDefault` / `withDecodingDefaultKey` fill a missing field during decoding. Defaults are `Effect`s and may be effectful (generated id, clock-derived timestamp).

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

```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 survives

const 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](https://effect.website/docs/v4/schema/advanced-usage) (decoding defaults and the missing / `undefined` / `null` tables), [Default Constructors](https://effect.website/docs/v4/schema/default-constructors) (nested, lazy, and class-level constructor defaults).

### 9. Classes and tagged errors

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

```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`).

```ts
import { Equal, Schema } from "effect"

class CompBand extends Schema.Class<CompBand>("comp/CompBand")(
  Schema.Struct({ min: Schema.Finite, max: Schema.Finite }).check(
    Schema.makeFilter(({ min, max }) => min <= max || "min must not exceed max")
  ),
  { title: "Compensation band" }
) {
  get spread() {
    return this.max - this.min
  }
}

class LevelBand extends CompBand.extend<LevelBand>("comp/LevelBand")({
  level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 }))
}) {}

const decoded = Schema.decodeUnknownSync(LevelBand)({ min: 150_000, max: 210_000, level: 5 })
decoded instanceof LevelBand // true: plain object -> instance
decoded.spread               // 60000: inherited getter
Schema.encodeSync(LevelBand)(decoded) // { min: 150000, max: 210000, level: 5 }
Equal.equals(decoded, new LevelBand({ min: 150_000, max: 210_000, level: 5 })) // true
// new LevelBand({ min: 2, max: 1, level: 5 }) throws: the inherited cross-field check runs
```

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

| Before committing to a class, test | Why |
| --- | --- |
| `new` / `make` with invalid input | constructors throw `Error("Schema validation failed")` with the issue in `cause` ([section 4 of Schema in Depth](./data/schema-in-depth.md#4-construction-and-deliberate-fallbacks)) |
| 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](https://effect.website/docs/v4/schema/classes) (its sample output for a failing `new` shows formatted issue text; construction throws the generic message described in [section 4 of Schema in Depth](./data/schema-in-depth.md#4-construction-and-deliberate-fallbacks)).

# Schema in Depth

This page continues the [Schema](./data/schema.md) 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](./data/schema-tooling.md).

## 1. Annotations and derivations

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

```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](#5-parse-options-are-boundary-policy)).

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

```ts
import { Schema } from "effect"

declare module "effect/Schema" {
  namespace Annotations {
    interface Annotations {
      readonly containsPii?: boolean | undefined
    }
  }
}

const NationalId = Schema.String.annotate({ containsPii: true })

const containsPii = (schema: Schema.Top): boolean =>
  Schema.resolveAnnotations(schema)?.["containsPii"] === true
```

**Derivation rules worth knowing.**

| Derivation | Rule | Customize with |
| --- | --- | --- |
| `Schema.toEquivalence` | 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`](./data/schema-tooling.md#schemaissue) and from the general [`Formatter`](./operations/observability.md#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](./data/schema.md#5-refinements-check-and-refine)); a declaration supplies a generatable stand-in with a `toCodecArbitrary` annotation | see [Arbitrary](./tooling/testing-dev-tooling.md#arbitrary) (unstable) |
| `Schema.toStandardSchemaV1` | see [StandardSchema](./data/schema-tooling.md#standardschema) | `leafHook`, `checkHook`, `parseOptions` |

```ts
import { Schema } from "effect"

const Employee = Schema.Struct({ id: Schema.Int, displayName: Schema.String })

// Identity-style equality: a renamed employee is still the same entity.
const sameEmployee = Schema.toEquivalence(
  Employee.pipe(Schema.overrideToEquivalence(() => (a, b) => a.id === b.id))
)
sameEmployee({ id: 1, displayName: "Ada" }, { id: 1, displayName: "Ada L." }) // true

// Audit-log formatter that masks every string leaf.
const auditLine = Schema.toFormatter(Employee, {
  onBefore: (ast) => (ast._tag === "String" ? () => "<masked>" : undefined)
})
auditLine({ id: 1, displayName: "Ada" }) // { "id": 1, "displayName": <masked> }
```

Official guides: [Schema Annotations](https://effect.website/docs/v4/schema/annotations) (its `parseOptions` annotation row and its claim that `concurrency` reaches union members are obsolete), [Schema to Equivalence](https://effect.website/docs/v4/schema/equivalence), [Schema to Formatter](https://effect.website/docs/v4/schema/formatter).

## 2. Serialization codecs

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.

```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](#7-effect-data-types-at-the-boundary).

## 3. Recursive and custom schemas

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.

```ts
import { Schema } from "effect"

interface OrgNode {
  readonly employeeId: string
  readonly reports: ReadonlyArray<OrgNode>
}

const OrgNode: Schema.Codec<OrgNode> = Schema.Struct({
  employeeId: Schema.String,
  reports: Schema.Array(
    Schema.suspend((): Schema.Codec<OrgNode> => OrgNode)
  )
})

const Url = Schema.declare(
  (value): value is URL => value instanceof URL,
  { expected: "URL" }
)
```

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

```ts
import { Schema } from "effect"

const fields = { name: Schema.String, openedAt: Schema.DateFromString }

interface Department extends Schema.Struct.Type<typeof fields> {
  readonly children: ReadonlyArray<Department>
}
interface DepartmentEncoded extends Schema.Struct.Encoded<typeof fields> {
  readonly children: ReadonlyArray<DepartmentEncoded>
}

const Department = Schema.Struct({
  ...fields,
  children: Schema.Array(
    Schema.suspend((): Schema.Codec<Department, DepartmentEncoded> => Department)
  )
})
```

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

```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](https://effect.website/docs/v4/schema/advanced-usage) (mutual recursion, declarations with type parameters), [Class APIs](https://effect.website/docs/v4/schema/classes) (recursive classes).

## 4. Construction and deliberate fallbacks

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

```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](https://effect.website/docs/v4/schema/default-constructors) (it types `makeEffect` as failing with `SchemaError` and prints formatted text for a throwing `make`; use the behavior in the table above).

## 5. Parse options are boundary policy

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](#4-construction-and-deliberate-fallbacks)) |

```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](./data/schema-tooling.md#jsonschema).** 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](./data/schema.md#4-unions-literals-records-tuples)). There is no `onExcessProperty: "preserve"` option, because it would let unvalidated values cross the boundary.
- **Options apply to the whole operation.** A `parseOptions` *annotation* 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.

## 6. Optional fields, null, and Option

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 }` |
| `Schema.OptionFromNullOr(S)` | fails | fails | `None` | `Option<A>` | `null` |
| `Schema.OptionFromUndefinedOr(S)` | fails | `None` | fails | `Option<A>` | `undefined` |
| `Schema.OptionFromNullishOr(S)` | fails | `None` | `None` | `Option<A>` | `undefined`, or `{ onNoneEncoding: null }` |

```ts
import { Schema } from "effect"

const Employee = Schema.Struct({
  name: Schema.String,
  nickname: Schema.OptionFromOptionalKey(Schema.String),       // wire: key may be absent
  managerId: Schema.OptionFromNullOr(Schema.FiniteFromString), // wire: numeric string or null (a nullable column)
  phone: Schema.OptionFromOptionalNullOr(Schema.String)        // wire: absent | undefined | null
})

Schema.decodeUnknownSync(Employee)({ name: "Ada", managerId: null })
// { name: "Ada", nickname: Option.none(), managerId: Option.none(), phone: Option.none() }
```

- **`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](#7-effect-data-types-at-the-boundary) 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](./data/schema-tooling.md#schemagetter).

Official guide: [Advanced Usage](https://effect.website/docs/v4/schema/advanced-usage).

## 7. Effect data types at the boundary

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

```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
```

| Schema | Canonical JSON form (`toCodecJson`) |
| --- | --- |
| `Schema.Option(A)` | `{ _tag: "None" }` or `{ _tag: "Some", value }` |
| `Schema.Result(A, E)` | `{ _tag: "Success", success }` or `{ _tag: "Failure", failure }` |
| `Schema.Exit(A, E, D)` | `{ _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`](./concurrency/scheduling-time.md#duration); 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.

**Other boundary schemas in `effect/Schema`.**

| Area | Schemas | Notes |
| --- | --- | --- |
| Secrets | `Schema.Redacted(S, { label?, disallowJsonEncode? })`, `Schema.RedactedFromValue(S, { label?, disallowEncode? })` | 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 |
| Sizes | `Schema.ByteSize`, `ByteSizeFromString`, `ByteSizeFromBigInt`, `ByteSizeFromNumber` | the string form requires a unit (`"5 MiB"`) and encodes the exact count as `"5242880 bytes"`; see [ByteSize](./data/functional-toolkit.md#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](./data/functional-toolkit.md#rational) |
| Graphs | `Schema.Graph("directed" \| "undirected", node, edge)` | immutable [Graph](./data/data-structures.md#graph) values; derive `toCodecJson` for a `{ type, nodes, edges }` snapshot |
| Network (unstable) | `Schema.IpAddressFromString`, `Ipv4AddressFromString`, `Ipv6AddressFromString`, `IpNetworkFromString`, `InetAddressFromString`, `MacAddressFromString` | text to `effect/net` values; malformed text fails with a specific message |
| Versions (unstable) | `Schema.SemVer`, `Schema.SemVerFromString`, `Schema.SemVerRange`, `Schema.SemVerRangeFromString` | strict SemVer 2.0.0 and npm-style ranges; see [SemVer](./data/functional-toolkit.md#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](./interfaces/cryptography.md) |
| HTTP (unstable) | `Schema.UrlParams`, `Schema.Headers`, `Schema.Cookies`, `Schema.RecordFromUrlParams`, `Schema.RecordFromCookies`, `Schema.JsonFromUrlParamsField(field)`, `Schema.DateTimeUtcFromHttpDate`, `Schema.RetryAfterFromString` | live in `effect/Schema`, not the HTTP modules; usage lives with [UrlParams](./interfaces/http-server.md#urlparams) |

Official guide: [Effect Data Types](https://effect.website/docs/v4/schema/effect-data-types).

## 8. Custom error messages

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 |

```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](./data/schema-tooling.md#schemaissue) suit wording that belongs to one UI.

Official guide: [Error Messages](https://effect.website/docs/v4/schema/error-messages).

## 9. Effectful schemas and services

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](./data/schema.md#1-decoding-and-encoding-pick-your-result-style)).

```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 EmployeeDirectory

const 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` |
| Validate without changing the value | `SchemaGetter.checkEffect` inside `Schema.decode({ ... })` ([SchemaGetter](./data/schema-tooling.md#schemagetter)) |
| A default or fallback that needs a service | an effectful default ([section 8 of Schema](./data/schema.md#8-default-values)) or `Schema.catchDecodingWithContext` |
| Run children in parallel | the `concurrency` parse option ([section 5](#5-parse-options-are-boundary-policy)) |

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

# Schema Tooling & Internals

The modules behind [Schema](./data/schema.md): 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.

## SchemaAST

`effect/SchemaAST` — stable

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.

```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.ast
console.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](#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.

## SchemaParser

`effect/SchemaParser` — stable

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.

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

```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 union

const input: unknown = "meets"
Schema.asserts(Rating, input) // throws if not a rating; otherwise narrows
input.toUpperCase()
```

Parsers look up each exact AST in a shared decoder registry. By default that entry is the interpreter; [SchemaJITCompiler](#schemajitcompiler) and [SchemaAOTCompiler](#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`.

## SchemaCompiler

`effect/schema/SchemaCompiler` — unstable

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.

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

## SchemaJITCompiler

`effect/schema/SchemaJITCompiler` — unstable

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.

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

## SchemaAOTCompiler

`effect/schema/SchemaAOTCompiler` — unstable

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 **direct** `Schema` 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.

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

## SchemaGetter

`effect/SchemaGetter` — stable

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

```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)
```

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

```ts
import { Effect, Schema, SchemaGetter } from "effect"

declare const isCodeTaken: (code: string) => Effect.Effect<boolean>

const FreeCostCenterCode = Schema.NonEmptyString.pipe(
  Schema.decode({
    decode: SchemaGetter.checkEffect((code: string) =>
      Effect.map(isCodeTaken(code), (taken) => (taken ? "cost-center code is already used" : undefined))
    ),
    encode: SchemaGetter.passthrough()
  })
)
```

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

## SchemaTransformation

`effect/SchemaTransformation` — stable

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.

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

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

## SchemaRepresentation

`effect/SchemaRepresentation` — stable

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.

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

## SchemaIssue

`effect/SchemaIssue` — stable

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.

```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](./data/schema-in-depth.md#8-custom-error-messages).

```ts
import { Result, Schema, SchemaIssue } from "effect"

const RaiseRequest = Schema.Struct({ employeeId: Schema.String, percent: Schema.Finite })

const toFieldErrors = SchemaIssue.makeFormatterStandardSchemaV1({
  leafHook: (issue) =>
    issue._tag === "MissingKey" ? "errors.required" : SchemaIssue.defaultLeafHook(issue)
})

const result = Schema.decodeUnknownResult(RaiseRequest)({}, { errors: "all" })
if (Result.isFailure(result)) {
  console.log(toFieldErrors(result.failure.issue).issues)
  // [ { path: ["employeeId"], message: "errors.required" },
  //   { path: ["percent"],    message: "errors.required" } ]
}
```

Official guide: [Error Formatters](https://effect.website/docs/v4/schema/error-formatters).

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

## Schema.SchemaError

`effect/Schema` — stable

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.

```ts
import { Result, Schema, SchemaIssue, SchemaParser } from "effect"

const Employee = Schema.Struct({ id: Schema.String, level: Schema.Int })

// High-level Schema adapters wrap the issue.
const decoded = Schema.decodeUnknownResult(Employee)({ id: 1 })
if (Result.isFailure(decoded) && Schema.isSchemaError(decoded.failure)) {
  console.log(decoded.failure.message)
  console.log(SchemaIssue.makeFormatterDefault()(decoded.failure.issue))
}

// Low-level SchemaParser adapters expose SchemaIssue.Issue directly.
const raw = SchemaParser.decodeUnknownResult(Employee)({ id: 1 })
if (Result.isFailure(raw)) {
  console.log(raw.failure._tag)
}
```

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

## JsonSchema

`effect/JsonSchema` — stable

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.

```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](./interfaces/http-api.md).)

- **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](./data/schema.md#5-refinements-check-and-refine)); `{ 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`.

```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 cycle

const 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`](./interfaces/http-api.md#openapi). 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](https://effect.website/docs/v4/schema/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.

## StandardSchema

`effect/StandardSchema` — stable

The **type definitions** of the [Standard Schema](https://standardschema.dev) 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.

```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`](#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.

Official guide: [Schema to Standard Schema](https://effect.website/docs/v4/schema/standard-schema).

**Reach for it when** a third-party library asks for a Standard Schema and you want your Effect schema to remain the single source of truth.

## JsonPatch

`effect/JsonPatch` — stable

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](./data/functional-toolkit.md#textdiff).

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

## JsonPointer

`effect/JsonPointer` — stable

The RFC 6901 conversions underlying `JsonPatch` paths and JSON Schema `$ref`s. `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.

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

## Model

`effect/schema/Model` — unstable

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`).

```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 defaults
Employee.update  // update schema
Employee.json    // outward JSON API shape — no baseSalary
Employee.jsonCreate
Employee.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.

## VariantSchema

`effect/schema/VariantSchema` — unstable

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.

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

## Testing schemas with TestSchema

`effect/testing/TestSchema` — unstable

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.

```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](./data/schema-in-depth.md#5-parse-options-are-boundary-policy)).

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](./deep-dives/schema-from-external-input-to-domain-and-back.md#test-the-contract-in-both-directions).

Official guide: [Schema to Arbitrary](https://effect.website/docs/v4/schema/arbitrary).

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

# Observability

_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](./operations/telemetry-export.md).

> **Official examples:** Effect's release-matched [`ai-docs` observability examples](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/08_observability) cover production logging and OTLP tracing.

## Designing signals

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.

### Which signal answers which question

| Signal | Answers | Does not answer |
| --- | --- | --- |
| Log (`Effect.log*`) | 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](#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](./operations/telemetry-export.md#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.

The lifetime side of this — startup order, drain, and shutdown deadlines — is covered in [Owning lifetimes: startup, readiness, and shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md), and the observability review items live in [Review checklists](./reference/review-checklists.md).

## Logger

`effect/Logger` — stable

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.

### The built-in loggers

- **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.
- **formatSimple** — Compact quoted `key=value` text; level names are uppercase (`INFO`, `WARN`, `ERROR`).
- **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](https://effect.website/docs/v4/platform/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).

### Installing and swapping loggers

```ts
import { Config, Effect, Layer, Logger, References } from "effect"
import { NodeFileSystem } from "@effect/platform-node"

// Logger.layer REPLACES the active logger set. The default set is
// { Logger.defaultLogger, Logger.tracerLogger }, so list tracerLogger again
// to keep log calls attached to the active span as span events.
export const JsonLoggerLayer = Logger.layer([Logger.consoleJson, Logger.tracerLogger])

// Raise the minimum level — Debug/Info calls become no-ops below "Warn".
export const WarnLevelLayer = Layer.succeed(References.MinimumLogLevel, "Warn")

// File logger added NEXT TO the loggers already installed (mergeWithExisting).
// Logger.toFile is dual — first arg is the string-producing logger, second is the path.
export const FileLoggerLayer = Logger.layer(
  [Logger.toFile(Logger.formatLogFmt, "/var/log/comp-service.log", { batchWindow: "250 millis" })],
  { mergeWithExisting: true }
).pipe(Layer.provide(NodeFileSystem.layer))

// Batched remote logger — flush a whole batch at once.
// Logger.batched is dual: (logger, options) or curried. It requires Scope.
export const RemoteLoggerLayer = Logger.layer(
  [
    Logger.batched(Logger.formatStructured, {
      window: "2 seconds",
      flush: Effect.fn(function*(batch) {
        // send batch to your log aggregator here
        yield* Effect.log(`flushing ${batch.length} entries`)
      })
    })
  ],
  { mergeWithExisting: true }
)

// Pick logger based on NODE_ENV.
export const AppLoggerLayer = Layer.unwrap(
  Effect.gen(function*() {
    const env = yield* Config.String("NODE_ENV").pipe(Config.withDefault("development"))
    return env === "production"
      ? JsonLoggerLayer.pipe(Layer.provideMerge(WarnLevelLayer))
      : Logger.layer([Logger.consolePretty(), Logger.tracerLogger])
  })
)
```

`Logger.layer(loggers, { mergeWithExisting })` decides between replacing and extending the set, and the choice has visible consequences:

| Call | Resulting logger set | Consequence |
| --- | --- | --- |
| `Logger.layer([Logger.consoleJson])` | JSON only | The default text output is gone **and log calls stop becoming span events**, because `tracerLogger` was replaced too |
| `Logger.layer([Logger.consoleJson, Logger.tracerLogger])` | JSON + span events | A format swap that keeps log-to-span correlation |
| `Logger.layer([sink], { mergeWithExisting: true })` | Existing set + `sink` | 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.

### Logging practice

| Level | Use for |
| --- | --- |
| `Debug` / `Trace` | Diagnosis; dropped by the default `Info` minimum |
| `Info` | 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

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

```ts
import { Effect } from "effect"

export const runPayrollExport = (payrollRunId: string) =>
  Effect.scoped(
    Effect.gen(function*() {
      yield* Effect.logInfo("export requested") // no payrollRunId yet
      yield* Effect.annotateLogsScoped({ payrollRunId })
      yield* Effect.logInfo("export started") // carries payrollRunId
      yield* Effect.logInfo("export finished") // carries payrollRunId
    })
  ) // annotation removed when the scope closes
```

### Keeping secrets masked in log payloads

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

```ts
import { Effect, Redacted } from "effect"

export const rotatePayrollToken = (employeeId: string, token: Redacted.Redacted<string>) =>
  Effect.logInfo("payroll token rotated", { employeeId, token }).pipe(
    Effect.annotateLogs({ service: "comp-service", apiKey: token })
  )
// Logger.consoleJson prints, among its other fields:
//   "message": ["payroll token rotated", { "employeeId": "E-1", "token": "<redacted>" }]
//   "annotations": { "service": "comp-service", "apiKey": "<redacted>" }
```

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

See [Redacted](./foundations/configuration-secrets.md#redacted) for construction and [`Config.Redacted`](./foundations/configuration-secrets.md#config) for loading secrets already wrapped.

### Custom loggers — redacting PII

```ts
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](#privacy-allow-list-fields-before-they-are-buffered)) 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](https://effect.website/docs/v4/observability/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

`effect/LogLevel` — stable

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

```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}`)
})
```

### Scoping and configuring the minimum level

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.

```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](./foundations/services-context-layers.md#references).

**Reach for it when** adjusting log verbosity for a specific scope, comparing levels programmatically, or setting a global minimum via config.

## Console

`effect/Console` — stable

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

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

## Formatter

`effect/Formatter` — stable

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.

```ts
import { Formatter } from "effect"

// Pretty-print a merit recommendation object (handles BigInt salaries, nested objects)
const rec = { employeeId: "E-001", newSalary: 145_000n, meritPct: 0.05 }
console.log(Formatter.format(rec))
// => '{ employeeId: "E-001", newSalary: 145000n, meritPct: 0.05 }'

// formatJson safely preserves bigint's printed identity as a JSON string.
console.log(Formatter.formatJson({ baseSalary: 130_000n, grantDate: "2025-01-15" }))
// => '{"baseSalary":"130000n","grantDate":"2025-01-15"}'
```

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

## Tracer

`effect/Tracer` — stable

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](./foundations/fibers-scopes-runtimes.md#fiberset) 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

```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](#cardinality-names-and-attribute-sets-are-bounded)). Span attributes are still exported data, so the [privacy allow-list](#privacy-allow-list-fields-before-they-are-buffered) applies to them too.

### What ends up on a span

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 | `Logger.tracerLogger` — only while it is in the logger set (see [Installing and swapping loggers](#installing-and-swapping-loggers)) |
| 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 and correlation rules

- **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](./operations/caching-batching.md#requestresolver).
- **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](./interfaces/http-server.md#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.

### Effect.fn traces automatically

```ts
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
  }
)
```

### Span links — fan-in across approval steps

```ts
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](https://effect.website/docs/v4/observability/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).

## Metric

`effect/Metric` — stable

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.

### The five metric types

| Type | Input | Use for |
| --- | --- | --- |
| `Metric.counter` | `number \| bigint` | 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, `update` *sets* the level and `modify` *adds* 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.

```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)
)
```

### Tracking effects with metrics

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

```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 reason
const 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>
```

### Gauges that follow a lifetime

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

```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

```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](#cardinality-names-and-attribute-sets-are-bounded)).

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.

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

### Runtime metrics

```ts
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.

Official guide: [Metrics](https://effect.website/docs/v4/observability/metrics).

# Telemetry Export

Getting logs, spans, and metrics out of the process. Instrumentation stays in business code ([Observability](./operations/observability.md)); 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.

## Choosing and owning an export path

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.

### One export path per signal

| Path | Choose it when | Know before you ship |
| --- | --- | --- |
| Direct OTLP — [`Otlp`](#otlp) / `OtlpTracer` / `OtlpLogger` / `OtlpMetrics` | You want a small, dependency-free stack that posts straight to a collector | Unstable module. Retry and shutdown flush are best effort, not delivery (see [OtlpExporter](#otlpexporter)) |
| OpenTelemetry SDK bridge — [`NodeSdk` / `WebSdk`](#otelnodesdk) | A platform team owns span processors, vendor exporters, samplers, or auto-instrumentation | Keep OpenTelemetry package versions aligned, and register auto-instrumentation before importing the modules it patches |
| Prometheus pull — [`PrometheusMetrics`](#prometheusmetrics) | Infrastructure already scrapes `/metrics` | 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.

### Layer order and shutdown

Build the root so that telemetry exists before anything that logs, traces, or forks:

1. Transport and resource prerequisites (`FetchHttpClient.layer`, `OtlpSerialization`, resource attributes).
2. Tracer, logger, and metric export Layers.
3. 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.

### Sampling has one owner per path

| Path | Who decides whether a span is recorded |
| --- | --- |
| Core tracer | `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.

### Verifying telemetry

Work up this ladder; each rung catches what the previous one cannot:

1. **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.
2. **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.
3. **Real exporter or scrape integration.** Decode the OTLP body or parse the Prometheus exposition; asserting that "an HTTP call happened" proves nothing about content.
4. **Propagation across real HTTP and queue boundaries**, including malformed headers and unsampled parents.
5. **Outage behavior**: a `429`, a slow collector, an exporter in its disabled window — the application keeps serving.
6. **Shutdown of the built artifact** with the collector absent and slow: the process exits within its deadline.
7. **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:

```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" } }
    ])
  }))
```

## Otlp

`effect/observability/Otlp` — unstable

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

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

## OtlpLogger

`effect/observability/OtlpLogger` — unstable

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.

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

## OtlpMetrics

`effect/observability/OtlpMetrics` — unstable

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.

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

## OtlpTracer

`effect/observability/OtlpTracer` — unstable

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](./operations/observability.md#what-ends-up-on-a-span)).

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

## OtlpExporter

`effect/observability/OtlpExporter` — unstable

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.

## OtlpResource

`effect/observability/OtlpResource` — unstable

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.

## OtlpSerialization

`effect/observability/OtlpSerialization` — unstable

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.

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

## OtlpProxy

`effect/observability/OtlpProxy` — unstable

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

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

## PrometheusMetrics

`effect/observability/PrometheusMetrics` — unstable

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.

```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](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded) 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.

## DevTools

`effect/devtools/DevTools` — unstable

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.

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

## DevToolsClient

`effect/devtools/DevToolsClient` — unstable

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

## DevToolsServer

`effect/devtools/DevToolsServer` — unstable

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.

## DevToolsSchema

`effect/devtools/DevToolsSchema` — unstable

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.

## OtelNodeSdk

`@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.

```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: () => Configuration
const 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](#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`.

## OtelWebSdk

`@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.

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

## OtelTracer

`@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).

## OtelMetrics

`@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.

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

## OtelLogger

`@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 `LogRecordProcessor`s.

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.

## OtelResource

`@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.

```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 & Batching

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/05_batching) builds a batched `RequestResolver`.

> **Official guides:** [Batching](https://effect.website/docs/v4/batching) (it enables batching with `Effect.forEach(..., { batching: true })`, an option `Effect.forEach` does not have — see [RequestResolver](#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.

## Which problem do you have?

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 | [`Effect.cached` / `cachedWithTTL`](#caching-a-single-effect) | A keyed cache is machinery you do not need |
| **Repeat lookup** — the same key again inside a freshness window | Lookup count ≈ request count; the same keys recur | [`Cache`](#cache): key, capacity, TTL | Batching shrinks one burst; it remembers nothing afterwards |
| **Cold stampede** — many callers, same key, nothing warm yet | A burst of identical lookups at startup or right after expiry | Already solved by `Cache.get`: concurrent misses for one key share a single lookup. No promise map or lock needed | — |
| **N+1** — many *different* keys at once that the backend could answer together | Lookups scale with rows; every backend call carries one id | [`RequestResolver`](#requestresolver) + `Effect.request` | A cache cannot help: remembering `L4` does nothing for `L5` and `L6` |
| **Entries own resources** — a connection per tenant shard | Handles leak or linger after eviction | [`ScopedCache`](#scopedcache) | `Cache` drops the value without releasing it |
| **Results must survive a restart** | Cold start repeats work another instance already did | `RequestResolver.persisted` or [PersistedCache](./tooling/persistence.md#persistedcache) | In-memory caches die with the process |

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

For the neighboring choices (`Resource`, `Pool`, `Semaphore`) see [Cache vs ScopedCache vs Resource vs RequestResolver](./reference/choosing-effect-primitives.md#cache-vs-scopedcache-vs-resource-vs-requestresolver).

## Caching a single Effect

`effect/Effect` — stable

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

```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.Input` **or** `(exit) => Duration.Input` | Expiry, read from the `Clock` — `TestClock.adjust` controls it in tests |
| `Effect.cachedInvalidateWithTTL(e, ttl)` | For `ttl`, a `Duration.Input` **or** `(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`](#cache) as soon as there is a key**, and for [`Resource`](./foundations/services-context-layers.md#resource) when the value needs scheduled refresh or owns a resource.

Official guide: [Caching Effects](https://effect.website/docs/v4/caching/caching-effects) (its "once" heading is not an API name; the code under it uses `Effect.cached`).

## Cache

`effect/Cache` — stable

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](#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.

```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])
})
```

### Keys are logical values

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

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

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

### Key API surface

| Function | What it does |
| --- | --- |
| `Cache.make({ lookup, capacity, timeToLive? })` | Create a cache. `timeToLive` is a `Duration.Input` string or millis; omitted means entries never expire. |
| `Cache.makeWith(lookup, { capacity, timeToLive: (exit, key) => Duration })` | 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.

### Failure and freshness policy

**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`:

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

### Testing a cache deterministically

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.

```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](./tooling/testing-dev-tooling.md#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](https://effect.website/docs/v4/caching/cache) (it shows `timeToLive` as a required option; the API makes it optional and defaults to no expiry).

## ScopedCache

`effect/ScopedCache` — stable

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

```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](#keys-are-logical-values) and [failure TTL](#failure-and-freshness-policy) 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.

## Request

`effect/Request` — stable

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)`.

```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 object
const req = new GetEmployeeById({ id: 42 })
console.log(req.id) // 42

// Type utilities
type EmployeeSuccess = Request.Success<GetEmployeeById> // Employee
type EmployeeError   = Request.Error<GetEmployeeById>   // EmployeeNotFound
```

Key APIs: Request.Class, Request.TaggedClass, Request.tagged, Request.of, Request.complete, Request.succeed, Request.fail, Request.Success, Request.Error, Request.Services, Request.Result

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.

## RequestResolver

`effect/RequestResolver` — stable

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](#resolver-combinators)) 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 |
| `Effect.forEach(ids, get, { concurrency: "unbounded" })` | `[1, 2, 3]` |

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

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

### Resolver obligations

A resolver is a small protocol, and part of it is enforced at runtime:

1. **Settle every entry you receive, exactly once** — with `entry.completeUnsafe(exit)` or the [`Request.*` helpers](#request). 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.
2. **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.
3. **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).
4. **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`](#resolver-combinators) collapse equal requests before they reach the resolver.
5. **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.

```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 })
  })
})
```

### Resolver combinators

| Combinator | Effect |
| --- | --- |
| `RequestResolver.make(runAll)` | 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. |
| `RequestResolver.fromEffectTagged<Req>()({ Tag: (entries) => … })` | 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. |
| `RequestResolver.withCache({ capacity, strategy? })` | 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. |
| `RequestResolver.asCache({ capacity, timeToLive? })` | 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](#failure-and-freshness-policy) applies — or `invalidate` / `refresh`. |
| `RequestResolver.persisted({ storeId, timeToLive?, staleWhileRevalidate? })` | 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`](#primarykey)) — a resolver without one of them receives every entry, duplicates included. The same [key normalization](#keys-are-logical-values) 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)`.

### Testing a resolver

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](#resolver-obligations): one backend call, distinct ids, results in caller order, every entry settled.

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

## PrimaryKey

`effect/PrimaryKey` — stable

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.

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

# HTTP Client

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.

> **Official example:** Effect's release-matched [`ai-docs` HttpClient example](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/50_http-client) builds a typed client service.

## HttpClient

`effect/http/HttpClient` — unstable

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

```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](#retries-time-budgets-and-cancellation). |
| `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 `HttpApiClient` `baseUrl`, 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](#response-lifetimes-and-withscope). |
| `withCircuitBreaker` | Stop calling an origin that keeps failing; see [below](#circuit-breaking). 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.

### Retries, time budgets, and cancellation

`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 *before* `retryTransient` 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 *before* `timeout` (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`](#response-lifetimes-and-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](./recipes/request-cancellation-through-a-host.md).
- **`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.

```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
})
```

### Response lifetimes and `withScope`

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

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

### Circuit breaking

`HttpClient.withCircuitBreaker({ breaker, key?, classify? })` guards each request with a [`CircuitBreaker`](./tooling/persistence.md#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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { Effect } from "effect"
import { HttpClient } from "effect/http"
import { CircuitBreaker } from "effect/persistence"

export const guardedClient = Effect.gen(function*() {
  const breaker = yield* CircuitBreaker.make({
    tripPolicy: CircuitBreaker.consecutive(5),
    openDuration: "30 seconds"
  })
  return (yield* HttpClient.HttpClient).pipe(HttpClient.withCircuitBreaker({ breaker }))
})
```

### User-controlled destinations

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.

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

## FetchHttpClient

`effect/http/FetchHttpClient` — unstable

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

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

## HttpClientRequest

`effect/http/HttpClientRequest` — unstable

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.

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

### Request compression and native connections

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

```ts
import { HttpClientRequest } from "effect/http"

export const compressed = HttpClientRequest.post("https://api.example.com/import").pipe(
  HttpClientRequest.bodyText("employee_id,salary\n".repeat(200)),
  HttpClientRequest.compressBody("gzip")
)
```

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.

## HttpClientResponse

`effect/http/HttpClientResponse` — unstable

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](./interfaces/http-server.md#url-credentials-and-query-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`.

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

## HttpClientError

`effect/http/HttpClientError` — unstable

Tagged error family on the client's error channel. Each carries the request (and often the response) for context:

Key APIs: TransportError, EncodeError, InvalidUrlError, StatusCodeError, DecodeError, EmptyBodyError

```ts
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`](./interfaces/http-server.md#url-credentials-and-query-redaction) 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.

### Three failure classes

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.

# HTTP Server

**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](./interfaces/http-api.md); this layer is right for webhooks, health checks, file exports, and anything without a schema contract.

## FindMyWay

`effect/http/FindMyWay` — unstable

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.

```ts
import { FindMyWay } from "effect/http"

const router = FindMyWay.make<string>({ ignoreTrailingSlash: true })
router.on("GET", "/employees/:id", "getEmployee")

const match = router.find("GET", "/employees/e-42?include=manager")
// { handler: "getEmployee", params: { id: "e-42" },
//   searchParams: { include: "manager" } }
```

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.

## HttpEffect

`effect/http/HttpEffect` — unstable

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.

```ts
import { Effect } from "effect"
import { HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/http"

const app = Effect.gen(function*() {
  const request = yield* HttpServerRequest.HttpServerRequest
  return HttpServerResponse.text(`${request.method} ${request.url}`)
})

export const handler = HttpEffect.toWebHandler(app)
```

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.

## HttpIncomingMessage

`effect/http/HttpIncomingMessage` — unstable

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.

## HttpPlatform

`effect/http/HttpPlatform` — unstable

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.

```ts
import { HttpMiddleware } from "effect/http"

const compressLargeResponses = HttpMiddleware.compression({
  algorithms: ["br", "gzip"],
  minSize: 2_048
})
```

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

## HttpStaticServer

`effect/http/HttpStaticServer` — unstable

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.

```ts
import { HttpStaticServer } from "effect/http"

const Assets = HttpStaticServer.layer({
  root: "./public",
  prefix: "/assets",
  cacheControl: "public, max-age=3600"
})
```

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.

## HttpTraceContext

`effect/http/HttpTraceContext` — unstable

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.

## MultipartParser

`effect/http/MultipartParser` — unstable

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.

## HttpRouter

`effect/http/HttpRouter` — unstable

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 *new* `HttpRouter` rather than reusing one the app provides itself — a route registered via `Layer.provide(HttpRouter.layer)` *inside* `appLayer` 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.

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

## HttpServer

`effect/http/HttpServer` — unstable

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`](./interfaces/platform-runtime-hosts.md#netaddress) — 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.

### Request work stays in the request fiber

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](#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.

```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](./recipes/request-cancellation-through-a-host.md).

### 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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md) and the [graceful entrypoint recipe](./recipes/graceful-entrypoint-and-shutdown.md).

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

## HttpServerRequest

`effect/http/HttpServerRequest` — unstable

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.

```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`](#edge-policy-checklist) 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.

## HttpServerResponse

`effect/http/HttpServerResponse` — unstable

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.

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

## HttpMiddleware

`effect/http/HttpMiddleware` — unstable

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 `IpNetwork`s 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.

```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`](./interfaces/http-api.md#httpapi) 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).

### Decompressing incoming bodies

`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](#httpplatform).

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

```ts
import { HttpRouter } from "effect/http"

export const Cors = HttpRouter.cors({
  allowedOrigins: ["https://hr.acme.example", "https://admin.acme.example"],
  allowedMethods: ["GET", "POST"],
  allowedHeaders: ["authorization", "content-type"],
  credentials: true,
  maxAge: 600
})
```

### Edge policy checklist

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 `BodyTooLarge` `RequestParseError` 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](#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](#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](./deep-dives/testing-an-effect-application.md).

**Reach for it when** you need cross-cutting behavior — auth, timing, request IDs, CORS — without repeating it per handler.

## HttpBody

`effect/http/HttpBody` — unstable

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.

## Headers

`effect/http/Headers` — unstable

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.

```ts
import { Headers } from "effect/http"

const headers = Headers.set(
  Headers.fromInput({ "content-type": "application/json" }),
  "authorization",
  "Bearer hris-service-token"
)
// Redact sensitive names before logging.
const safeForLogs = Headers.redact(headers, ["authorization"])
```

`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:

```ts
import { Layer } from "effect"
import { Headers } from "effect/http"

export const RedactedHeaders = Layer.succeed(Headers.CurrentRedactedNames)([
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-hris-signature",
  /^x-internal-/
])
```

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

## Cookies

`effect/http/Cookies` — unstable

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`](./interfaces/http-client.md#httpclient) 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.

## HttpMethod

`effect/http/HttpMethod` — unstable

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

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

## Url

`effect/http/Url` — unstable

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.

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

## UrlParams

`effect/http/UrlParams` — unstable

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.

### URL credentials and query redaction

`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](#headers).

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

## Multipart

`effect/http/Multipart` — unstable

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.Reference`s tunable per route; only `MaxFieldSize` has a finite default (see the [edge policy checklist](#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.

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

## HttpServerError

`effect/http/HttpServerError` — unstable

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.

## HttpServerRespondable

`effect/http/HttpServerRespondable` — unstable

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

`effect/http/Etag` — unstable

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.

## Template

`effect/http/Template` — unstable

Effectful tagged-template literal for building HTML (or any string) where interpolations can themselves be Effects, `Option`s, 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.

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

## HttpStatus

`effect/http/HttpStatus` — unstable

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

```ts
import { HttpStatus } from "effect/http"

const conflict = HttpStatus.fromLiteral("Conflict")               // 409
const 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

`effect/http/Mime` — unstable

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.

```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 on
Mime.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.

# HttpApi

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/51_http-server) connects a schema-first contract, handlers, middleware, serving, and a generated client.

![Diagram: an HttpApi request passes middleware and decoding, then the handler; invalid input is a 400, declared errors use their declared status, defects and encoding failures are 500s, and a disconnect interrupts the request fiber](./diagrams/httpapi-request-lifecycle.svg)

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

## HttpApiEndpoint

`effect/http-api/HttpApiEndpoint` — unstable

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

```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](#openapi) and [HttpMiddleware](./interfaces/http-server.md#httpmiddleware).

```ts
import { Schema } from "effect"
import { HttpApiEndpoint } from "effect/http-api"

// Search comp bands with a structured filter in the body: QUERY /comp-bands/search
const 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](#httpapitest) shows how to prove it. Schema mechanics (checks, brands, transformations) live in [Schema](./data/schema.md#schema).

**Reach for it when** describing a single route's typed inputs and outputs — the atom every HttpApi is built from.

## HttpApiGroup

`effect/http-api/HttpApiGroup` — unstable

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()`).

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

## HttpApi

`effect/http-api/HttpApi` — unstable

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.

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

```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:

```ts
import { Schema } from "effect"
import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"

const RaiseInput = Schema.Struct({ amount: Schema.Finite, effectiveDate: Schema.String })

export class RaisesApi2 extends HttpApi.make("raises").add(
  HttpApiGroup.make("raises").add(
    HttpApiEndpoint.post("propose", "/raises", { payload: RaiseInput })
  )
)
  .annotate(HttpApi.ParseOptions, { onExcessProperty: "error" })
  .annotate(HttpApi.HeadersParseOptions, {}) {}
```

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

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

## HttpApiSchema

`effect/http-api/HttpApiSchema` — unstable

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.

```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](./interfaces/http-server.md#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.

### Streaming request payloads

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.

```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 })
})
```

### Upgrades

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

## HttpApiError

`effect/http-api/HttpApiError` — unstable

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

```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 (RFC 9457)

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 `400` `BadRequestProblem` (with per-field `errors` only when `includeDetails: true`) and response encoding failures as a `500` `InternalServerErrorProblem`, and declares both in OpenAPI and the client.

```ts
import { Effect, Layer, Schema } from "effect"
import {
  HttpApi,
  HttpApiBuilder,
  HttpApiEndpoint,
  HttpApiError,
  HttpApiGroup,
  HttpApiMiddleware,
  HttpApiSchema
} from "effect/http-api"

class BudgetExceeded extends HttpApiError.Problem<BudgetExceeded>()("BudgetExceeded", {
  type: "https://comp.acme.internal/problems/budget-exceeded",
  status: 409,
  title: "The raise exceeds the remaining merit budget."
}, {
  remaining: Schema.Number
}) {}

const Raises = HttpApiGroup.make("raises").add(
  HttpApiEndpoint.post("approve", "/raises/:id/approve", {
    params: { id: Schema.String },
    success: Schema.Struct({ approved: Schema.Boolean }),
    error: [BudgetExceeded, HttpApiError.NotFound.pipe(HttpApiSchema.asProblem({ title: "Raise not found" }))]
  })
)

const Api = HttpApi.make("comp").add(Raises).middleware(HttpApiMiddleware.ProblemDetails)

const RaisesLive = HttpApiBuilder.group(Api, "raises", (handlers) =>
  handlers.handle("approve", () => Effect.fail(new BudgetExceeded({ remaining: 1200 })))
)

export const ApiLive = HttpApiBuilder.layer(Api).pipe(
  Layer.provide(RaisesLive),
  Layer.provide(HttpApiMiddleware.layerProblemDetails())
)
```

### Status mapping is part of the contract

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](#problem-details-rfc-9457) 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](./interfaces/sql.md#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](#httpapibuilder) 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`](./foundations/errors-option-result.md#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`:

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

## ProblemDetails

`effect/http/ProblemDetails` — unstable

The RFC 9457 value layer underneath HttpApi's [problem support](#problem-details-rfc-9457), 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).

```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."
  })))
```

## HttpApiSecurity

`effect/http-api/HttpApiSecurity` — unstable

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.

## HttpApiMiddleware

`effect/http-api/HttpApiMiddleware` — unstable

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.

```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 `provideService`s the context:

```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 })
        )
      })
    })
  })
)
```

### Authentication is not authorization

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

```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](#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.

## HttpApiBuilder

`effect/http-api/HttpApiBuilder` — unstable

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.

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

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

```ts
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"
import { Layer } from "effect"
import { HttpRouter } from "effect/http"
import { HttpApiBuilder, HttpApiScalar } from "effect/http-api"
import { createServer } from "node:http"

const ApiRoutes = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
  Layer.provide([CompApiHandlers, SystemApiHandlers])
)
const DocsRoute = HttpApiScalar.layer(Api, { path: "/docs" })

const ServerLayer = HttpRouter.serve(Layer.mergeAll(ApiRoutes, DocsRoute)).pipe(
  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))
)

Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)
```

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

### Handlers are lazy adapters

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](./interfaces/http-server.md#request-work-stays-in-the-request-fiber) 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.
- **Translate errors at this edge, exhaustively** ([status mapping](#status-mapping-is-part-of-the-contract)), and authorize before acting ([authentication is not authorization](#authentication-is-not-authorization)).

**Reach for it when** implementing the server for an `HttpApi` — this is the only place handlers live.

## HttpApiClient

`effect/http-api/HttpApiClient` — unstable

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.

```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`](#httpapi) 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](#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

`effect/http-api/OpenApi` — unstable

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.

```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`](./data/schema-tooling.md#jsonschema) 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`](#httpapi) `{ onExcessProperty: "error" }`.
- **`QUERY` operations sit under an extension.** OpenAPI 3.1 has no `query` field, so `fromApi` emits an [`HttpApiEndpoint.query`](#httpapiendpoint) 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](https://effect.website/docs/v4/schema/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.

## HttpApiSwagger

`effect/http-api/HttpApiSwagger` — unstable

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.

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

## HttpApiScalar

`effect/http-api/HttpApiScalar` — unstable

Same idea as Swagger, rendered with [Scalar's](https://github.com/scalar/scalar) 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.

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

## HttpApiTest

`effect/http-api/HttpApiTest` — unstable

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.

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

### What each test ring proves

| Ring | Drive it with | Proves | Does not prove |
| --- | --- | --- | --- |
| 1. Compile | `tsc` over the API, the complete handler Layers, the derived client, and the root Layer | the contract, handlers, and wiring agree | any runtime behavior |
| 2. Document | targeted assertions on `OpenApi.fromApi(Api)` | published paths, parameters, security, media types, and statuses | that the server behaves that way |
| 3. In process | `HttpApiTest.groups` | codecs, routing, middleware, status mapping, typed errors | malformed input (the typed client cannot send it), sockets, disconnects |
| 4. Raw wire | `HttpRouter.toWebHandler` with a hand-built `Request`, or a real listener on port `0` | malformed JSON, wrong `Content-Type`, bad headers, invalid params, streaming, disconnect, listener release | that the deployed artifact starts |
| 5. Artifact | 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:

```ts
import { assert, it } from "@effect/vitest"
import { Context, Effect, Layer, Ref, Schema } from "effect"
import { HttpRouter, HttpServer } from "effect/http"
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"

const EmployeeId = Schema.String.check(Schema.isPattern(/^E-\d{4}$/)).pipe(Schema.brand("EmployeeId"))
const CompRecord = Schema.Struct({ employeeId: EmployeeId, baseSalary: Schema.Finite })

class Api extends HttpApi.make("comp-api").add(
  HttpApiGroup.make("comp").add(
    HttpApiEndpoint.get("getComp", "/employees/:id/comp", {
      params: { id: EmployeeId }, // the rule lives on the contract
      success: CompRecord
    })
  )
) {}

class CompRepository extends Context.Service<CompRepository, {
  readonly find: (id: typeof EmployeeId.Type) => Effect.Effect<typeof CompRecord.Type>
}>()("comp/CompRepository") {}

const CompHandlers = HttpApiBuilder.group(
  Api,
  "comp",
  Effect.fn(function*(handlers) {
    const repository = yield* CompRepository
    return handlers.handle("getComp", ({ params }) => repository.find(params.id))
  })
)

it.effect("an invalid id never reaches the repository", () =>
  Effect.gen(function*() {
    const calls = yield* Ref.make(0)
    const CountingRepository = Layer.succeed(CompRepository)({
      find: (employeeId) =>
        Ref.update(calls, (n) => n + 1).pipe(Effect.as({ employeeId, baseSalary: 180_000 }))
    })
    const Routes = HttpApiBuilder.layer(Api).pipe(
      Layer.provide(CompHandlers),
      Layer.provide(CountingRepository),
      Layer.provide(HttpServer.layerServices)
    )
    // The typed client would reject "nope" while encoding, so speak raw HTTP instead.
    const { dispose, handler } = HttpRouter.toWebHandler(Routes, { disableLogger: true })
    yield* Effect.addFinalizer(() => Effect.promise(dispose))

    const invalid = yield* Effect.promise(() => handler(new Request("http://localhost/employees/nope/comp")))
    assert.strictEqual(invalid.status, 400)
    assert.strictEqual(yield* Ref.get(calls), 0) // validation happened before the handler

    const valid = yield* Effect.promise(() => handler(new Request("http://localhost/employees/E-0042/comp")))
    assert.strictEqual(valid.status, 200)
    assert.strictEqual(yield* Ref.get(calls), 1)
  }))
```

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.

# GraphQL

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](./interfaces/http-api.md) for an Effect-owned HTTP contract, and [RPC](./interfaces/rpc.md) for an Effect-to-Effect procedure protocol.

## GraphQL

`effect/graphql/GraphQL` — experimental

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

```ts
// This example deliberately uses the experimental GraphQL client family.
// @effect-diagnostics experimentalApiUsage:off
import { Effect, Layer, Schema } from "effect"
import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
import { FetchHttpClient } from "effect/http"

const Viewer = GraphQL.query("Viewer", {
  document: "query Viewer { viewer { login } }",
  result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
})

export const viewer = Effect.gen(function*() {
  const client = yield* GraphQLClient.make(GraphQLGroup.make(Viewer))
  return yield* client.Viewer()
}).pipe(
  Effect.provide(
    GraphQLProtocol.layerHttp({ url: "https://api.example.com/graphql" }).pipe(
      Layer.provide(FetchHttpClient.layer)
    )
  )
)
```

**Reach for it when** defining a typed operation by hand or inspecting generated operation types.

## GraphQLGroup

`effect/graphql/GraphQLGroup` — experimental

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

## GraphQLClient

`effect/graphql/GraphQLClient` — experimental

`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](#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.

## GraphQLClientError

`effect/graphql/GraphQLClientError` — experimental

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.

## GraphQLMiddleware

`effect/graphql/GraphQLMiddleware` — experimental

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.

## GraphQLProtocol

`effect/graphql/GraphQLProtocol` — experimental

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

## GraphQLResolver

`effect/graphql/GraphQLResolver` — experimental

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

## GraphQL generator

`@effect/graphql-generator/Config` — experimental

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

```ts
// The generator configuration API is intentionally experimental too.
// @effect-diagnostics experimentalApiUsage:off
import { 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.

Pinned implementation and examples: [GraphQL source](https://github.com/Effect-TS/effect/tree/effect%404.1.4/packages/effect/src/graphql), [client tests](https://github.com/Effect-TS/effect/tree/effect%404.1.4/packages/effect/test/graphql), and [generator](https://github.com/Effect-TS/effect/tree/effect%404.1.4/packages/tools/graphql-generator).

# RPC

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.

## Rpc

`effect/rpc/Rpc` — unstable

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.

```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](./interfaces/http-api.md#status-mapping-is-part-of-the-contract), 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](#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.

## RpcGroup

`effect/rpc/RpcGroup` — unstable

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.

```ts
import { BigDecimal, Context, Effect, Schema } from "effect"
import { Rpc, RpcGroup } from "effect/rpc"

class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", {
  employeeId: Schema.String
}) {}

class BudgetExceeded extends Schema.TaggedError<BudgetExceeded>()("BudgetExceeded", {
  employeeId: Schema.String,
  requested: Schema.BigDecimal
}) {}

class Compensation extends Schema.Class<Compensation>("Compensation")({
  employeeId: Schema.String,
  level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })),
  baseSalary: Schema.BigDecimal
}) {}

// 1. The contract — three procedures in one group.
export class CompRpc extends RpcGroup.make(
  Rpc.make("GetComp", {
    payload: { employeeId: Schema.String },
    success: Compensation,
    error: EmployeeNotFound
  }),
  Rpc.make("ProposeRaise", {
    payload: { employeeId: Schema.String, amount: Schema.BigDecimal },
    success: Compensation,
    error: Schema.Union([EmployeeNotFound, BudgetExceeded])
  }),
  Rpc.make("ApproveGrant", {
    payload: { employeeId: Schema.String, shares: Schema.Natural },
    success: Schema.Void
  })
) {}

// A service the handlers depend on, like any other Effect service.
class CompService extends Context.Service<CompService>()("app/CompService", {
  make: Effect.succeed({
    find: (employeeId: string) =>
      employeeId === "E-1"
        ? Effect.succeed(new Compensation({ employeeId, level: 4, baseSalary: BigDecimal.fromBigInt(180000n) }))
        : Effect.fail(new EmployeeNotFound({ employeeId })),
    raise: (employeeId: string, amount: BigDecimal.BigDecimal) =>
      Effect.succeed(new Compensation({ employeeId, level: 4, baseSalary: BigDecimal.sum(BigDecimal.fromBigInt(180000n), amount) })),
    grant: (_employeeId: string, _shares: number) => Effect.void
  })
}) {}

// 2. The implementation — exhaustively typed against the group.
export const CompLive = CompRpc.toLayer(
  Effect.gen(function*() {
    const comp = yield* CompService
    return {
      GetComp: ({ employeeId }) => comp.find(employeeId),            // Effect<Compensation, EmployeeNotFound>
      ProposeRaise: ({ employeeId, amount }) => comp.raise(employeeId, amount),
      ApproveGrant: ({ employeeId, shares }) => comp.grant(employeeId, shares) // Effect<void>
    }
  })
)
```

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)`.

### Evolving a contract

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`](#rpctest) cannot see these failures.
- Schema-level techniques for tolerant evolution (optional keys, decoding defaults, unions of versions) are in [Schema](./data/schema.md#schema).

**Reach for it when** you want a single typed surface the server implements and the client mirrors.

## RpcServer

`effect/rpc/RpcServer` — unstable

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.

```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](./deep-dives/exposing-an-effect-application-over-mcp.md)), `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`](./interfaces/http-server.md#httprouter) 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 |

### Operational defaults

`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](./operations/caching-batching.md)). A capacity plan names a finite value for each of: body and frame bytes (`maxFrameSize`, `maxBufferSize`, and [`MaxBodySize`](./interfaces/http-server.md#edge-policy-checklist) 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](./interfaces/sql.md#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.

## RpcClient

`effect/rpc/RpcClient` — unstable

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

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

### Retried mutations need a ledger

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.

```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 transaction boundary and the post-commit side of this pattern are covered by [SQL transactions](./interfaces/sql.md#transactions) and the [transactional write with outbox recipe](./recipes/transactional-write-with-outbox.md).

**Reach for it when** you are the caller and want a typed client derived from the group.

## RpcClientError

`effect/rpc/RpcClientError` — unstable

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](#retried-mutations-need-a-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:`.

```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}`)
  )
)
```

### Keep six failure categories distinguishable

| Category | Where it shows up on the client | Treat it as |
| --- | --- | --- |
| Declared operation or middleware failure | typed error, `Effect.catchTag` | a business outcome |
| Stream element or terminal failure | the `Stream`'s error channel | a business outcome, mid-stream |
| Request or response schema incompatibility | a **defect** carrying the formatted schema issue (server could not decode the payload or encode the reply), or a decode failure on the client | version skew — a deployment problem, never a domain failure |
| Envelope, framing, or serializer failure | `RpcClientError` with `reason._tag === "RpcClientDefect"` | a protocol bug or a mismatched serializer |
| Transport failure | `RpcClientError` whose `reason` is an HTTP client, socket, or worker error | outcome unknown — see [retried mutations](#retried-mutations-need-a-ledger) |
| Handler defect or interruption | a defect, or interruption of the calling fiber | 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.

## RpcMiddleware

`effect/rpc/RpcMiddleware` — unstable

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

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

```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:

1. **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.
2. **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.
3. **Provide** a decoded principal through `provides` — never the raw token.
4. **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.

```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](./interfaces/http-server.md#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.

## RpcSchema

`effect/rpc/RpcSchema` — unstable

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.

```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](./systems/workflows-durable-execution.md), 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.

## RpcSerialization

`effect/rpc/RpcSerialization` — unstable

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](./concurrency/streaming-channels.md#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).

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

## OpenRpc

`effect/rpc/OpenRpc` — unstable

Publishes an RPC group as an [OpenRPC](https://spec.open-rpc.org/) 1.3.2 document, the JSON-RPC counterpart of [`OpenApi.fromApi`](./interfaces/http-api.md#openapi). `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.

```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 inherits

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

## RpcMessage

`effect/rpc/RpcMessage` — unstable

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.

Key APIs: Request, Ack, Interrupt, Eof, Ping, ResponseChunk, ResponseExit, RequestId

**Reach for it when** implementing a bespoke `Protocol` or reasoning about acks, interrupts, and stream framing at the wire level.

## RpcWorker

`effect/rpc/RpcWorker` — unstable

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.

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

## RpcTest

`effect/rpc/RpcTest` — unstable

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.

```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](./interfaces/http-server.md#own-the-listener-acquire-late-bind-port-0-prove-release)), 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.

## Utils

`effect/rpc/Utils` — unstable

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

# SQL

> **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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/40_sql) defines a `Model.Class`, runs migrations, and exposes a derived repository through a service.

## Where SQL belongs in an application

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

| Layer | Owns | Does not own |
| --- | --- | --- |
| Transport ([HttpApi](./interfaces/http-api.md), [RPC](./interfaces/rpc.md)) | Decoding input, encoding output, mapping domain errors to statuses | SQL, transactions |
| Use case | The transaction boundary (`sql.withTransaction` around the smallest atomic unit), domain rules | Statement text |
| Domain repository (a `Context.Service`) | A domain-named capability, row decoding, [one stable storage error](#normalizing-errors-at-a-repository-boundary) | Connections — its Layer receives `SqlClient` once |
| Driver Layer | Pool, dialect, connection lifetime | Anything domain-shaped |

Generated repositories ([`SqlModel`](#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

`effect/sql/SqlClient` — unstable

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

### The star: parameterized tagged-template queries

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

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

```ts
import { SqlClient } from "effect/sql"

// SqlClient is part of the unstable effect/sql module.
declare const sql: SqlClient.SqlClient
declare const requestedSort: string // untrusted: a query-string value

const sortColumns: Record<string, string> = { name: "name", hired: "hired_at", level: "level" }
const column = sortColumns[requestedSort] ?? "name" // unknown input falls back, it is never quoted through
const 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.

### Helpers you'll use daily

```ts
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.

```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).

### Fragments compose

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.

```ts
import { SqlClient } from "effect/sql"

declare const sql: SqlClient.SqlClient
declare const activeOnly: boolean

const filter = activeOnly ? sql`where terminated_at is null` : sql``
const page = sql`select * from employees ${filter} order by id limit 20`
```

### Transactions

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

```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](#statement) (`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 *outside* `withTransaction`. |
| **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. |

```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 *same* `SqlClient` 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](#external-effects-after-commit-outbox).
- **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 **outermost** `sql.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.

```ts
import { Effect } from "effect"
import { SqlClient } from "effect/sql"

export const closeCycle = (cycleId: number) =>
  Effect.gen(function*() {
    const sql = yield* SqlClient.SqlClient
    return yield* sql.withTransaction(
      Effect.gen(function*() {
        yield* sql`update merit_cycles set closed = true where id = ${cycleId}`
        yield* sql.afterCommit(Effect.logInfo("merit cycle closed"))
      })
    ).pipe(Effect.provideService(SqlClient.BeginTransaction, "BEGIN ISOLATION LEVEL SERIALIZABLE"))
  })
```

Under `SERIALIZABLE`, conflicting transactions abort with `SerializationError`, so pair the isolation level with a bounded retry of the whole unit:

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

### External effects after commit (outbox)

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

```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](./recipes/transactional-write-with-outbox.md). When the queue itself can live in the same database, [PersistedQueue](./tooling/persistence.md#persistedqueue) with its SQL store is a ready-made outbox with retry schedules and dead-lettering; [the durability ladder](./deep-dives/durability-and-distribution-ladder.md) covers workflows and cluster delivery.

### Statement variants & dialect switches

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.

**Reach for it when** you talk to a database at all.

## Statement

`effect/sql/Statement` — unstable

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`](#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. |

```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.unsafe` *is* 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

`effect/sql/SqlSchema` — unstable

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

```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

`effect/sql/SqlResolver` — unstable

`SqlResolver` builds schema-aware `RequestResolver`s 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.

```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](https://effect.website/docs/v4/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](./operations/caching-batching.md#requestresolver).

## SqlStream

`effect/sql/SqlStream` — unstable

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

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

## SqlError

`effect/sql/SqlError` — unstable

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.

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

### Normalizing errors at a repository boundary

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

```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](./interfaces/http-api.md); the [outbox recipe](./recipes/transactional-write-with-outbox.md) 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.

## SqlConnection

`effect/sql/SqlConnection` — unstable

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.

```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](#the-driver-packages) below).

**Reach for it when** implementing a new driver, or needing a pinned raw connection for operations the statement API does not model.

## Migrator

`effect/sql/Migrator` — unstable

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.

```ts
// migrations/0003_create_equity_grants.ts
import { 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)
    )
  `
})
```

```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 **one** `sql.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.

### Operating migrations

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

## MigratorFileSystem

`effect/sql/MigratorFileSystem` — unstable

The directory loader for [Migrator](#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`.

## SqlModel

`effect/sql/SqlModel` — unstable

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.

```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 variants
class 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 context
const 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 `RequestResolver`s (`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.

## Operating SQL in production

### Pools, reservations, and streaming

- **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](./concurrency/concurrency-coordination.md#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.

### Logging and telemetry safety

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.

### Verification levels

| Test | Replace | Proves | Does not prove |
| --- | --- | --- | --- |
| Use case | The **domain repository** Layer (not a partial fake `SqlClient`) | Domain rules, error mapping, orchestration | Any SQL, any atomicity — an identity `withTransaction` fake commits nothing and rolls back nothing |
| Repository contract suite | Nothing: a real database after real migrations, per supported driver | Decoding, cardinality, constraints, rollback, savepoints, date / integer / JSON / null behavior | 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.

## The driver packages

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.

```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](#native-client-behavior-codecs-json-and-listen). Session defaults, TLS mode, and rotating passwords are configured per physical connection ([Session settings at connect time](#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](#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.

### Session settings at connect time

**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 `SqlError`s. |

```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 **invalid** `Date` — `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](#session-settings-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 **scoped** `Effect` 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:

```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: number
declare 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:

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

# Platform & Runtime Hosts

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](https://effect.website/docs/v4/platform/introduction) (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.

Who owns each of these runtimes, and when it is disposed, is a separate question from which Layer implements a service: see [Choosing a host](#choosing-a-host) below and [Owning Lifetimes — Startup, Readiness, and Shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md).

## FileSystem

`effect/FileSystem` — unstable

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`) |
| Single files and links | `copyFile`, `truncate`, `link`, `symlink`, `readLink`, `realPath` |
| Metadata and permissions | `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`](./data/functional-toolkit.md#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 `number`s. 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`](./interfaces/http-server.md#httpplatform) clamps a requested range to the file's size, so `Content-Length` always matches the bytes actually sent.

```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 chunks
const 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 implementation
const 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`](#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.

```ts
import { Effect, FileSystem } from "effect"

// Every TypeScript source under ./src, skipping generated code.
export const sources = Effect.gen(function*() {
  const fs = yield* FileSystem.FileSystem
  return yield* fs.glob("**/*.{ts,tsx}", { root: "src", exclude: ["generated/**"] })
})
```

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

Official guide: [FileSystem](https://effect.website/docs/v4/platform/file-system).

### Testing without a disk

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

```ts
import { Effect, FileSystem } from "effect"

const TestFs = FileSystem.layerNoop({
  readFileString: (path) =>
    path === "./data/comp_bands.csv"
      ? Effect.succeed("level,min,mid,max\nL5,100,120,140")
      : Effect.die(`unexpected read: ${path}`)
})

const firstBand = Effect.gen(function*() {
  const fs = yield* FileSystem.FileSystem
  const csv = yield* fs.readFileString("./data/comp_bands.csv")
  return csv.split("\n")[1] // "L5,100,120,140"
}).pipe(Effect.provide(TestFs))
```

The noop service's `glob`, `lstat`, and `readDirectoryEntries` also fail with `NotFound` unless overridden.

## Glob

`effect/Glob` — experimental

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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { Glob } from "effect"

const reports = Glob.make("exports/**/*.{csv,xlsx}")

Glob.match(reports, "exports/2026/payroll.csv") // true
Glob.match(reports, "exports/.tmp/payroll.csv") // false: dot directory
Glob.match(Glob.make(Glob.escape("band[1].csv")), "band[1].csv") // true
```

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

## Path

`effect/Path` — unstable

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.

```ts
import { FileSystem, Path } from "effect"
import { Effect } from "effect"

// Build an export file path for this merit cycle's raise recommendations
const buildExportPath = Effect.fn("buildExportPath")(
  function*(cycleId: string, outputDir: string) {
    const path = yield* Path.Path
    const fs = yield* FileSystem.FileSystem

    // Ensure the output directory exists
    yield* fs.makeDirectory(outputDir, { recursive: true })

    // Compose a timestamped CSV path: <outputDir>/merit-<cycleId>-raises.csv
    const filename = `merit-${cycleId}-raises.csv`
    const fullPath = path.join(outputDir, filename)

    yield* Effect.log(`export path: ${fullPath}`)
    return fullPath
  }
)
```

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

Official guide: [Path](https://effect.website/docs/v4/platform/path).

## Terminal

`effect/Terminal` — unstable

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

```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)
```

```ts
import { Terminal } from "effect"
import { Effect } from "effect"

// Interactive CLI prompt for confirming a merit cycle run
const 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`.

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

Official guide: [Terminal](https://effect.website/docs/v4/platform/terminal).

## Stdio

`effect/Stdio` — unstable

Lower-level counterpart to `Terminal`: `process.argv` via `args`, write `Sink`s 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.

```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 stdout
const 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.

## Socket

`effect/socket/Socket` — unstable

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 `pull` **never 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`.

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

## SocketServer

`effect/socket/SocketServer` — unstable

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

```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 prefix
const 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`](#netaddress) values rather than strings.

When to use: accepting TCP or WebSocket connections — custom protocols, push event relays, or bidirectional streaming pipelines.

## NetAddress

`effect/net/NetAddress` — unstable

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 `number`s 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.

```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) // false
NetAddress.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                               // 8443
NetAddress.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).

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

## Host

`effect/net/Host` — experimental

Pure values for DNS domain names, numeric hosts (including scoped IPv6), and host/port endpoints. Checked `domainNameFromString`, `hostFromString`, and `hostPortFromString` return `Result`s 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](#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

`effect/net/Dns` — experimental

`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](#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

`effect/net/AddressResolver` — experimental

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

```ts
// Host resolution is deliberately experimental.
// @effect-diagnostics experimentalApiUsage:off
import { Effect, Layer } from "effect"
import { AddressResolver } from "effect/net"
import { NodeAddressResolver, NodeDns } from "@effect/platform-node"

export const endpoints = Effect.gen(function*() {
  const resolver = yield* AddressResolver.AddressResolver
  return yield* resolver.resolve("example.com:443", { family: "IPv4" })
}).pipe(
  Effect.provide(NodeAddressResolver.layer.pipe(Layer.provide(NodeDns.layer)))
)
```

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.

## DatagramSocket

`effect/socket/DatagramSocket` — experimental

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.

## IpNetwork

`effect/net/IpNetwork` — unstable

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.

## IpInterface

`effect/net/IpInterface` — unstable

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.

## Worker

`effect/workers/Worker` — unstable

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.

```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 count
const 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.

## WorkerRunner

`effect/workers/WorkerRunner` — unstable

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

```ts
// vesting-worker.ts — runs inside the worker thread
import { WorkerRunner } from "effect/workers"
import { NodeWorkerRunner } from "@effect/platform-node"
import { Effect } from "effect"

// Receive a grant ID, compute vested shares, reply to parent
const 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.

## WorkerError

`effect/workers/WorkerError` — unstable

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", ...)`.

## Transferable

`effect/workers/Transferable` — unstable

Transfer-list support for worker message fields. Annotate fields with `Transferable.schema`; a `Transferable.Collector` records backing `ArrayBuffer`s, `MessagePort`s, 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.

## ChildProcess

`effect/process/ChildProcess` — unstable

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.

```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 it
const signedExport = ChildProcess.make("payroll-cli", ["export", "--format=csv"]).pipe(
  ChildProcess.pipeTo(ChildProcess.make("gpg", ["--sign", "--armor"]))
)

// Override environment for a production payroll run
const 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`.

```ts
import { ChildProcess } from "effect/process"

const employee = "Ada Lovelace; rm -rf /" // stays one harmless argument
const flags = ["--format=csv", "--cycle=2026 H1"]

// payroll-cli ["export", "--format=csv", "--cycle=2026 H1", "--employee", "Ada Lovelace; rm -rf /"]
const exportOne = ChildProcess.make`payroll-cli export ${flags} --employee ${employee}`

// Options first, then the template.
const listing = ChildProcess.make({ cwd: "/app/payroll", forceKillAfter: "2 seconds" })`ls -la`
```

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`](#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.

## CommandLine

`effect/process/CommandLine` — unstable

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.

```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"
```

## ChildProcessSpawner

`effect/process/ChildProcessSpawner` — unstable

Service that executes `ChildProcess.Command` values.

Key APIs: spawner.string(cmd), spawner.lines(cmd), spawner.spawn(cmd)

`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 `Stream`s, 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](#platform-packages)).

```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 line
const 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.

## Platform packages

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](./interfaces/cryptography.md)), 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`](./interfaces/http-server.md#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.

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

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

```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](./systems/cluster-sharding.md#running-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 *persisted* `pagehide` — 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.

```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
)
```

## Choosing a host

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 |
| Foreign framework callback (Express, Hono, UI, plugin API) | 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](./operations/observability.md#logger)).
- **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.

```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)
```

Official guide: [Runtime (platform)](https://effect.website/docs/v4/platform/runtime) (it gives the exit code as only `0` or `1` and names only SIGINT; Effect also uses `130` for an unannotated interrupt and handles SIGTERM). Recipes: [a graceful Node entrypoint](./recipes/graceful-entrypoint-and-shutdown.md), [ManagedRuntime at an imperative boundary](./recipes/managed-runtime-integration.md), and [request cancellation through a host](./recipes/request-cancellation-through-a-host.md).

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

```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](./troubleshooting/troubleshooting-and-anti-patterns.md#incompatible-unstable-package-versions)).

## Browser IndexedDB

`@effect/platform-browser/IndexedDb*` — package

Five modules form a schema-aware, versioned database rather than a thin `IDBRequest` wrapper:

| Module | Responsibility |
| --- | --- |
| `IndexedDb` | `indexedDB` / `IDBKeyRange` capability service plus valid-key schemas; `layerWindow` uses browser globals. |
| `IndexedDbTable` | An object-store descriptor with a `Schema`, key path, typed index paths, auto-increment and durability metadata. Declaring an index does not create it. |
| `IndexedDbVersion` | A non-empty set of tables representing one schema version. |
| `IndexedDbDatabase` | Ordered migrations, database layer, `getQueryBuilder`, and destructive `rebuild`. |
| `IndexedDbQueryBuilder` | Schema-encoded writes and decoded reads, index/key ranges, pagination/streaming, transactions, and reactive invalidation. |

```ts
import {
  IndexedDb,
  IndexedDbDatabase,
  IndexedDbTable,
  IndexedDbVersion
} from "@effect/platform-browser"
import { Effect, Layer, Schema } from "effect"

const Todo = IndexedDbTable.make({
  name: "todo",
  schema: Schema.Struct({
    id: Schema.Int,
    title: Schema.String,
    completed: Schema.Boolean
  }),
  keyPath: "id",
  indexes: { titleIndex: "title" }
})

const V1 = IndexedDbVersion.make(Todo)

class AppDb extends IndexedDbDatabase.make(
  V1,
  Effect.fn(function*(migration) {
    yield* migration.createObjectStore("todo")
    yield* migration.createIndex("todo", "titleIndex")
  })
) {}

const program = Effect.gen(function*() {
  const db = yield* AppDb.getQueryBuilder
  yield* db.from("todo").insert({
    id: 1,
    title: "Review salary bands",
    completed: false
  })
  return yield* db.from("todo").select("titleIndex").equals("Review salary bands")
}).pipe(
  Effect.provide(
    AppDb.layer("comp-planner").pipe(Layer.provide(IndexedDb.layerWindow))
  )
)
```

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.

## Other browser capabilities

| API | What it adds |
| --- | --- |
| `Permissions.query` | 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](./interfaces/cryptography.md)) avoid reaching host globals.

# Cryptography

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`](#jose-tokens-and-keys) 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 | [`SecureRandom`](#securerandom) | `effect/Random`, which is seedable and not secure |
| A checksum, content hash, or pseudonymous lookup key | [`Digest`](#digest) | a MAC, unless a secret is involved |
| Proof that a message came from someone holding a shared secret (webhooks, signed cookies) | [`Mac`](#mac) | comparing digests with `===` |
| Encrypt data so tampering is detected | [`Aead`](#aead) | [`Cipher`](#cipher) |
| A protocol that pairs AES-CTR or AES-CBC with its own MAC | [`Cipher`](#cipher) | — |
| Turn a password or shared secret into key bytes | [`Kdf`](#kdf) | using the secret as a key directly |
| Public-key signatures (release signing, custom protocols) | [`Signature`](#signature) | hand-built JWS; use [`Jws`](#jws) |
| Issue or verify JWTs (access tokens, ID tokens, session tokens) | [`Jwt`](#jwt) | `decodeUnverified` for any authorization decision |
| Verify tokens against an identity provider's JWKS endpoint | [`Jwks.layerRemote`](#jwks) with `Jwt.verifyWithKeySet` | fetching the key set by hand per request |
| Two parties agreeing on a secret (ECDH, X25519) | [`KeyAgreement`](#keyagreement), then `Kdf` | — |
| Encrypting a key with another key | [`KeyWrap`](#keywrap) | `Aead` over exported key bytes |
| PEM, SPKI, PKCS#8, or JWK in and out | [`KeyFormat`](#keyformat) | hand-written DER parsing |

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`](#webcrypto) reference, and every family except `Digest` and `Kdf` needs `SecureRandom` for key generation, so provide `SecureRandom.layerWebCrypto` underneath.

```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))`.

```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 = 0
export 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 |
| `randomULID` | `ulid` (monotonic within a millisecond) |
| `randomIntBetween(min, max, { halfOpen })` | `intBetween(min, max, { halfOpen })` |
| `randomShuffle(xs)` | `shuffle(xs)` |
| `random`, `randomBetween`, `randomBoolean`, `randomInt`, `nextDoubleUnsafe` | 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.

## SecureRandom

`effect/crypto/SecureRandom` — unstable

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

```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 }
})
```

## Digest

`effect/crypto/Digest` — unstable

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`](#mac) with a server-side key when the input is guessable.

```ts
import { Effect } from "effect"
import { Digest } from "effect/crypto"

export const contentHash = (bytes: Uint8Array) =>
  Effect.gen(function*() {
    const digest = yield* Digest.Digest
    return yield* digest.digestHex(Digest.sha256, bytes)
  })
```

## Mac

`effect/crypto/Mac` — unstable

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.

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

## Aead

`effect/crypto/Aead` — unstable

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 `CryptoKey`s 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).

```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))
  )
```

## Cipher

`effect/crypto/Cipher` — unstable

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`](#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.

## Kdf

`effect/crypto/Kdf` — unstable

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.

```ts
import { Effect } from "effect"
import { Kdf } from "effect/crypto"

export const passwordKey = (password: string, salt: Uint8Array) =>
  Effect.gen(function*() {
    const kdf = yield* Kdf.Kdf
    const secret = new TextEncoder().encode(password.normalize("NFKC"))
    return yield* kdf.derive(Kdf.argon2id(), secret, { salt, length: 32 }).pipe(
      Effect.catchReason("CryptoError", "Unsupported", () =>
        kdf.derive(Kdf.pbkdf2Sha256, secret, { salt, length: 32 }))
    )
  })
```

## Signature

`effect/crypto/Signature` — unstable

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`](#keyformat). Ed25519 needs Chrome 137, Firefox 129, or Safari 17 in browsers.

```ts
import { Effect } from "effect"
import { KeyFormat, Signature } from "effect/crypto"

declare const publicKeyPem: string

export const verifyRelease = (artifact: Uint8Array, signature: Uint8Array) =>
  Effect.gen(function*() {
    const signatures = yield* Signature.Signature
    const publicKey = yield* KeyFormat.decodePublic(KeyFormat.pem(KeyFormat.spki), Signature.ed25519, publicKeyPem)
    return yield* signatures.verify(publicKey, signature, artifact)
  })
```

## KeyAgreement

`effect/crypto/KeyAgreement` — unstable

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`](#kdf) (HKDF) before using it as a key. X25519 needs Chrome 133, Firefox 130, or Safari 17 in browsers.

```ts
import { Effect } from "effect"
import { Aead, Kdf, KeyAgreement } from "effect/crypto"

export const sessionKey = (
  mine: KeyAgreement.PrivateKey<KeyAgreement.X25519>,
  theirs: KeyAgreement.PublicKey<KeyAgreement.X25519>,
  salt: Uint8Array
) =>
  Effect.gen(function*() {
    const agreement = yield* KeyAgreement.KeyAgreement
    const kdf = yield* Kdf.Kdf
    const shared = yield* agreement.deriveSharedSecret(mine, theirs)
    const bytes = yield* kdf.derive(Kdf.hkdfSha256, shared, {
      salt,
      info: new TextEncoder().encode("payroll-sync v1"),
      length: 32
    })
    return yield* Aead.key(Aead.xchacha20Poly1305, bytes)
  })
```

## KeyWrap

`effect/crypto/KeyWrap` — unstable

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

## KeyFormat

`effect/crypto/KeyFormat` — unstable

Plain functions, not a service, that run on the [`WebCrypto`](#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`](#jwk).

```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 }
})
```

## CryptoError

`effect/crypto/CryptoError` — unstable

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

`effect/crypto/WebCrypto` — unstable

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

## JOSE: tokens and keys

The `effect/jose` modules implement compact JSON Web Keys, Signatures, Encryption, and Tokens on the services above: HMAC runs on [`Mac`](#mac), asymmetric signatures on [`Signature`](#signature), encryption on [`Aead`](#aead) with IVs from `SecureRandom`, thumbprints on [`Digest`](#digest), and key import and export on [`KeyFormat`](#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`](#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.

## Jwk

`effect/jose/Jwk` — unstable

Imports keys and binds each to one algorithm. Imports need no services, because they run on [`KeyFormat`](#keyformat):

| Function | Input → result |
| --- | --- |
| `importPublic(jwk, algorithm)` | `PublicJwk` → `PublicKey`, for verification. Private members are rejected; decode untrusted JSON with the `Jwk.PublicJwk` schema first |
| `importPrivate(jwk, algorithm)` | `Redacted<PrivateJwk>` → `PrivateKey`, for signing; RSA keys need their CRT members |
| `importSecret(jwk, algorithm)` | `Redacted<SecretJwk>` → `SecretKey<A>` for `HS256`/`HS384`/`HS512` (at least 32, 48, or 64 bytes) or `"dir"` (exactly 32 bytes) |
| `importSpki(derOrPem, algorithm, { kid? })`, `importPkcs8(Redacted<derOrPem>, algorithm, { kid? })` | DER bytes or PEM text → `PublicKey` / `PrivateKey` |
| `exportPublic`, `exportPrivate`, `exportSpki(key, { format? })`, `exportPkcs8(key, { format? })` | 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.

```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 }
  })
```

## Jws

`effect/jose/Jws` — unstable

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`](#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`](#jwt). On Node.js and Bun, `NodeCrypto.layerMac` computes HMAC signatures synchronously on `node:crypto`.

## Jwt

`effect/jose/Jwt` — unstable

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`](#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.

```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))
)
```

## Jwe

`effect/jose/Jwe` — unstable

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`](#keyagreement), [`Kdf`](#kdf), and [`Aead`](#aead) yourself; JWE has no public-key key management in this profile.

## Jwks

`effect/jose/Jwks` — unstable

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 `kid`s 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](#jwt)), and a client wrapped with `HttpClient.followRedirects` follows them too.

## JoseError

`effect/jose/JoseError` — unstable

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.

# Reactivity & Atom

For a connected, application-oriented treatment of these modules, see [Reactivity — From Atoms to Mastery](./deep-dives/reactivity-from-atoms-to-mastery.md).

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

## Atom

`effect/reactivity/Atom` — unstable

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.

```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).

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

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

## AtomRegistry

`effect/reactivity/AtomRegistry` — unstable

The store. A `Registry` evaluates atoms, caches their current values in `Node`s, 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.

```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)   // 4
registry.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.08
cancel()

// `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.

## AtomRef

`effect/reactivity/AtomRef` — unstable

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.

```ts
import { AtomRef } from "effect/reactivity"

// A single editable raise recommendation form.
const draft = AtomRef.make({ employeeId: "emp_1042", raisePct: 4, note: "" })

const raisePct = draft.prop("raisePct") // AtomRef<number> focused on .raisePct
raisePct.set(6)                          // updates draft to { ..., raisePct: 6 }
draft.value                              // { employeeId: "emp_1042", raisePct: 6, note: "" }

const cancel = raisePct.subscribe((p) => console.log("raise ->", p))
raisePct.update((p) => p + 1)            // logs: raise -> 7
cancel()
```

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

## AsyncResult

`effect/reactivity/AsyncResult` — unstable

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.

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

## AtomHttpApi

`effect/reactivity/AtomHttpApi` — unstable

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.

```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 |
| `responseMode: "decoded-and-response"` / `"response-only"` | 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 |
| Binary stream (`HttpApiSchema.StreamUint8Array`) | a `Stream` of `Uint8Array` | `HttpClientError` in the stream's error channel |
| Header-wrapped success (`HttpApiSchema.WithHeaders`) | the value together with its decoded headers | as for an ordinary endpoint |

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

## AtomRpc

`effect/reactivity/AtomRpc` — unstable

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.

```ts
import { Schema } from "effect"
import { Rpc, RpcGroup } from "effect/rpc"
import { AtomRpc } from "effect/reactivity"

const CompRpcs = RpcGroup.make(
  Rpc.make("getVestedEquity", {
    payload: { employeeId: Schema.String },
    success: Schema.Struct({
      employeeId: Schema.String,
      vestedShares: Schema.Natural,
      grantDate: Schema.String
    })
  })
)

class CompRpcClient extends AtomRpc.Service<CompRpcClient>()("app/CompRpcClient", {
  group: CompRpcs,
  protocol: ProtocolLive // your RpcClient.Protocol transport layer
}) {}

// Query atom: AsyncResult<{ employeeId, vestedShares, grantDate }, RpcClientError | ...>.
const vested = CompRpcClient.query(
  "getVestedEquity",
  { employeeId: "emp_1042" },
  { serializationKey: "vested:1042" }
)

// Mutation atom, with key-based invalidation on success:
// const grant = CompRpcClient.mutation("recordEquityGrant")
// registry.set(grant, { payload: { employeeId: "emp_1042", shares: 1200 }, reactivityKeys: ["equity"] })
```

**Error and retention rules.**

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

## Hydration

`effect/reactivity/Hydration` — unstable

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.

```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-`Initial` `AsyncResult` 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](https://github.com/Effect-TS/effect/blob/effect%404.1.4/packages/effect/SCHEMA.md) 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.

## Reactivity

`effect/reactivity/Reactivity` — unstable

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.

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

## Framework bindings

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.

## @effect/atom-react in practice

`@effect/atom-react` — pkg

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`).

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

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

# AI & Language Models

`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`](#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](./systems/mcp.md).

> **Official companions:** The release-matched [AI examples](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/71_ai) cover language-model calls, tools, and stateful chat. The broader [AI documentation source tree](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src) and [`LLMS.md`](https://github.com/Effect-TS/effect/blob/effect%404.1.4/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`):

```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))
```

## LanguageModel

`effect/ai/LanguageModel` — unstable

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.

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

```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:

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

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

```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](#client-executed-tools) 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.

### Service types are branded

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

## Chat

`effect/ai/Chat` — unstable

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.

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

```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](#client-executed-tools) 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.

```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](./tooling/persistence.md)), 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](./tooling/persistence.md#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](#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.

## Tool

`effect/ai/Tool` — unstable

A single typed function the model can call. Bundles a name, a description (shown to the model), a `parameters` `Schema` the model fills in, and a `success` `Schema` 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.

```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"
})
```

### Failure results and their wire format

A tool call ends in one of four shapes, and the encoded form of each is a **persisted contract** once it lands in a `Chat` history or your own store.

| Outcome | `isFailure` | Value in `result` | Encoded with |
| --- | --- | --- | --- |
| Handler succeeded | `false` | the `success` type | JSON codec of the `success` schema |
| Handler failed with the declared `failure` type (`failureMode: "return"`) | `true` | the `failure` type | JSON codec of `Tool.failureResultSchema(tool)` |
| Framework or handler produced an `AiError` (`failureMode: "return"`) | `true` | `AiError.AiError` | JSON codec of `Tool.failureResultSchema(tool)` |
| Call was denied by an approval response, or never ran because the response finished incomplete | `true` | `Tool.ExecutionFailure` — `{ type: "execution-denied" \| "execution-interrupted", reason }` | JSON codec of `Tool.failureResultSchema(tool)` |

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

### Client-executed tools

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.

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

## Toolkit

`effect/ai/Toolkit` — unstable

A typed bundle of tools plus their handler implementations. `Toolkit.make(...tools)` groups any number of `Tool`s; `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`.

```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](#tool-call-resolution-concurrency-and-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`.

## Prompt

`effect/ai/Prompt` — unstable

The provider-neutral representation of conversation input: an ordered list of `Message`s (system/user/assistant), each composed of typed `Part`s (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).

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

## Response

`effect/ai/Response` — unstable

The typed vocabulary of model output. A non-streaming call returns a `GenerateTextResponse` whose `content` is an array of `Part`s; streaming yields a sequence of `StreamPart`s. 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.

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

## EmbeddingModel

`effect/ai/EmbeddingModel` — unstable

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.

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

## Decision

`effect/ai/Decision` — unstable

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`](#decisionmodel) 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.

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

## DecisionModel

`effect/ai/DecisionModel` — unstable

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.

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

## Model

`effect/ai/Model` — unstable

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](#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.

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

## Tokenizer

`effect/ai/Tokenizer` — unstable

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.

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

## IdGenerator

`effect/ai/IdGenerator` — unstable

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

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

## Telemetry

`effect/ai/Telemetry` — unstable

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.

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

## AiError

`effect/ai/AiError` — unstable

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.

```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 }))
  )
)
```

### Classifying a failure before retrying

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"` | `true` | Bounded retry. |
| `InvalidOutputError`, `StructuredOutputError`, `ToolNotFoundError`, `ToolParameterValidationError` | `true` | The model produced something unusable; a retry re-bills the whole prompt, so cap it tightly. |
| `AuthenticationError`, `QuotaExhaustedError`, `ContentPolicyError`, `InvalidRequestError`, `InvalidResponseError`, `UnsupportedSchemaError`, `InvalidToolResultError`, `ToolResultEncodingError`, `ToolConfigurationError`, `ToolkitRequiredError`, `InvalidUserInputError`, `UnknownError`, other `NetworkError` reasons | `false` | 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.

## ResponseIdTracker

`effect/ai/ResponseIdTracker` — unstable

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.

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

## AnthropicStructuredOutput

`effect/ai/AnthropicStructuredOutput` — unstable

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.

## OpenAiStructuredOutput

`effect/ai/OpenAiStructuredOutput` — unstable

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.

## WorkloadIdentity

`effect/ai/WorkloadIdentity` — unstable

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:

| Package module | Options | Exchange |
| --- | --- | --- |
| `AnthropicWorkloadIdentity` (`@effect/ai-anthropic`) | `federationRuleId`, `organizationId`, optional `serviceAccountId`, `workspaceId`, `apiUrl` | `jwt-bearer` grant at `${apiUrl}/v1/oauth/token`; adds the `oauth-2025-04-20` beta header |
| `OpenAiWorkloadIdentity` (`@effect/ai-openai`) | `identityProviderId`, `serviceAccountId`, optional `identityTokenType` (`"jwt"` or `"id_token"`), `tokenUrl` | `token-exchange` grant at `https://auth.openai.com/oauth/token` |
| `OpenRouterWorkloadIdentity` (`@effect/ai-openrouter`) | `federationPolicyId`, optional `apiUrl` | `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 `HttpClientError`s (`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.

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

## AgUiSchema

`effect/ai/AgUiSchema` — experimental

Schemas for the [Agent User Interaction (AG-UI)](https://docs.ag-ui.com) 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`.

## AgUi

`effect/ai/AgUi` — experimental

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.

## AgUiServer

`effect/ai/AgUiServer` — experimental

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](#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`](#chat) (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`.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { 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.

## Production rules for model calls

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](./deep-dives/building-a-production-ai-capability.md), 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.** | `concurrency`, `disableToolCallResolution`, `toolkit.handle`, `setNeedsApproval`. |
| Loops | **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.** | `error.isRetryable`, `error.retryAfter`, `Schedule.upTo`. |
| Structured output | **The local `Schema` decode is authoritative** even when the provider advertises strict JSON; never fall back to parsing prose. | `generateObject`, `StructuredOutputError`. |
| Dynamic and MCP tools | **Allow-list tool names, snapshot and validate their schemas locally, and re-review when a server changes them.** | `Tool.dynamic`, `Tool.getJsonSchema`, `McpClient.toolkit(client, { tools, transformTool })`. |
| Media input | **Validate MIME type, size, count, and URI scheme before a file part leaves the process**; never let a prompt trigger an implicit URL fetch. | `Prompt` file parts. |
| Telemetry | **Record model, provider, latency, finish reason, usage, and tool names; keep prompts, keys, and reasoning text out of spans and logs.** | `Telemetry`, `Model.ProviderName` / `ModelName`, `Config.Redacted`; leave `Toolkit.RecordToolArguments` off. |

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

## Provider packages

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](#workloadidentity) 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`](#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](#classifying-a-failure-before-retrying) 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.

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

# MCP Servers

`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](./systems/ai-language-models.md). For an end-to-end walkthrough, read the [MCP deep dive](./deep-dives/exposing-an-effect-application-over-mcp.md).

## McpSchema

`effect/ai/McpSchema` — unstable

The complete Model Context Protocol (MCP) wire format as Effect `Schema`s 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`.

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

## McpProtocol

`effect/ai/McpProtocol` — unstable

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.

```ts
import { McpProtocol, McpServer } from "effect/ai"

// Session-based clients negotiate 2025-11-25; stateless clients use 2026-07-28.
const StdioMcp = McpServer.layerStdio({
  name: "Comp Server",
  version: "1.0.0",
  protocols: [McpProtocol.v2025_11_25, McpProtocol.v2026_07_28]
})
```

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.

## McpServer

`effect/ai/McpServer` — unstable

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-readable `title` beside the `name` (also accepted by `registerPrompt`). Each of these is a registration Layer that requires the `McpServer` service. Merge them and pass them to the transport as its `registrations` option, so they are registered before the server reads its first request. Transports: `layerStdio` (desktop clients), `layerHttp` (mount on an `HttpRouter`; pass `allowSessionTermination: true` to enable DELETE on the session path, which ends the session and interrupts its active requests — later requests on that session id return `404`), and `layer` over a caller-provided `RpcServer.Protocol`. Every server constructor (`layer`, `layerStdio`, `layerHttp`, `run`) accepts an optional `instructions` string, returned in the initialization and discovery responses to tell a client how to use the server. Launch with `Layer.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](#request-level-dependencies-middleware-and-visibility).

```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 `LanguageModel` *and* 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 `structuredContent` **only 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 `ErrorReporter`s, so provide one when you need alerting on tool faults (see [Observability](./operations/observability.md)). 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.

### Request-scoped HTTP and typed requirements

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

```ts
import { McpProtocol, McpServer } from "effect/ai"

export const RequestScopedMcp = McpServer.layerHttpRequestScoped({
  name: "Comp Server",
  version: "1.0.0",
  path: "/mcp",
  protocols: [McpProtocol.v2026_07_28]
})
```

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 `undefined` `payload`, 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.

```ts
import { Context, Effect, Layer, Schema } from "effect"
import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"

class CurrentUser extends Context.Service<CurrentUser, {
  readonly id: string
  readonly isAdmin: boolean
}>()("acme/CurrentUser") {}

class Unauthorized extends Schema.Error<Unauthorized>("Unauthorized")({
  ...McpSchema.McpErrorBase.fields,
  _tag: Schema.tag("Unauthorized"),
  code: Schema.tag(-32001)
}) {}

declare const verify: (token: string) => Effect.Effect<CurrentUser["Service"], Unauthorized>

// Runs around every call, read, get, and completion of the registrations it is provided to.
const Auth = McpServer.middleware<{ provides: CurrentUser }>()((effect, { headers }) => {
  const token = headers["authorization"]
  return token === undefined
    ? Effect.fail(new Unauthorized({ message: "Missing credentials" }))
    : Effect.flatMap(verify(token), (user) => Effect.provideService(effect, CurrentUser, user))
})
const AdminOnly = McpServer.visibility(() => Effect.map(CurrentUser, (user) => user.isAdmin))

const ReadTools = Toolkit.make(
  Tool.make("comp_whoami", { success: Schema.String, dependencies: [CurrentUser] })
)
const AdminTools = Toolkit.make(
  Tool.make("comp_reset_cycle", { success: Schema.String, dependencies: [CurrentUser] })
)

export const Registrations = Layer.mergeAll(
  McpServer.toolkit(ReadTools).pipe(
    Layer.provide(Auth.layer),
    Layer.provide(ReadTools.toLayer({ comp_whoami: () => Effect.map(CurrentUser, (user) => user.id) }))
  ),
  McpServer.toolkit(AdminTools).pipe(
    // `Auth` runs outside the check, so the check can read CurrentUser.
    Layer.provide(AdminOnly.combine(Auth).layer),
    Layer.provide(AdminTools.toLayer({ comp_reset_cycle: () => Effect.succeed("reset") }))
  )
)
```

### Request context, client gating, and human input

- **`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](./deep-dives/exposing-an-effect-application-over-mcp.md#one-gate-for-both-eras) does:

```ts
import { Effect, Schema } from "effect"
import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"

declare const applyBandTable: (tableId: string) => Effect.Effect<void>
const Confirm = Schema.Struct({ confirm: Schema.Boolean })

const ApplyBandTable = Tool.make("comp_apply_band_table", {
  parameters: Schema.Struct({ tableId: Schema.String }),
  success: Schema.Struct({ applied: Schema.Boolean }),
  dependencies: [McpSchema.McpServerClient] // supplied per call to session clients
}).annotate(McpSchema.EnabledWhen, (client) => client.protocolVersion !== "2026-07-28")

const BandToolkit = Toolkit.make(ApplyBandTable)
export const BandHandlers = BandToolkit.toLayer({
  comp_apply_band_table: Effect.fn("comp_apply_band_table")(function*({ tableId }) {
    const message = `Apply band table ${tableId} to every open cycle?`
    const { confirm } = yield* McpServer.elicit({ message, schema: Confirm }).pipe(
      Effect.catchTag("ElicitationDeclined", () => Effect.succeed({ confirm: false }))
    )
    if (confirm) yield* applyBandTable(tableId)
    return { applied: confirm }
  })
})
```

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

```ts
import { Context, Effect, Layer, Schema } from "effect"
import { McpSchema, McpServer } from "effect/ai"

declare const lockCycle: Effect.Effect<void>
const requestedSchema = { type: "object", properties: { confirm: { type: "boolean" } }, required: ["confirm"] }
const isConfirmed = Schema.is(Schema.Struct({
  action: Schema.Literal("accept"),
  content: Schema.Struct({ confirm: Schema.Literal(true) })
}))
const text = (text: string) => new McpSchema.CallToolResult({ content: [{ type: "text", text }] })

export const LockCycle = Layer.effectDiscard(McpServer.McpServer.use((server) =>
  server.addTool({
    tool: new McpSchema.Tool({ name: "comp_lock_cycle", inputSchema: { type: "object" } }),
    annotations: Context.make(McpSchema.EnabledWhen, (client) => client.protocolVersion === "2026-07-28"),
    handle: () =>
      Effect.gen(function*() {
        const answer = (yield* McpSchema.McpRequestContext).inputResponses?.["confirm"]
        if (answer === undefined) {
          const message = "Lock FY27-merit? Managers can no longer edit proposals."
          return new McpSchema.InputRequired({
            inputRequests: { confirm: { method: "elicitation/create", params: { mode: "form", message, requestedSchema } } }
          })
        }
        if (!isConfirmed(answer)) return text("Not locked.")
        yield* lockCycle
        return text("Locked.")
      })
  })
))
```

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

### Skills

`McpServer.skill({ uri, files, annotations? })` (a registration Layer) and `McpServer.registerSkill(options)` (its Effect form) publish an [Agent Skill](https://agentskills.io/) 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.

```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-cycle
description: 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.

### Tracing

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](./deep-dives/exposing-an-effect-application-over-mcp.md).

**Reach for it when** you want capabilities usable from Claude Desktop, an IDE, or any MCP client — without writing JSON-RPC by hand.

## McpClient

`effect/ai/McpClient` — experimental

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-28` `input_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](./systems/ai-language-models.md): 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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { 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.

## McpClientError

`effect/ai/McpClientError` — experimental

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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { Effect, Schema } from "effect"
import type { McpClient, McpSchema } from "effect/ai"

const Report = Schema.Struct({ count: Schema.Number })

export const readOrDefer = (client: McpClient.McpClient, tool: McpSchema.Tool) =>
  client.callTool({ tool, arguments: { reportId: "q3" }, schema: Report }, { timeout: "2 seconds" }).pipe(
    Effect.map((report) => ({ status: "ready" as const, report })),
    Effect.catchReason("McpClientError", "TimeoutError", () => Effect.succeed({ status: "deferred" as const }))
  )
```

**Reach for it when** recovering from specific remote-MCP failures: `Effect.catchReason` / `catchReasons` select reasons, `Effect.catchTag("McpClientError", ...)` handles them all.

## McpTest

`effect/ai/McpTest` — unstable

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

```ts
import { assert, it } from "@effect/vitest"
import { Context, Effect, Layer, Schema } from "effect"
import { McpProtocol, McpServer, McpTest, Tool, Toolkit } from "effect/ai"

class CurrentUser extends Context.Service<CurrentUser, { readonly id: string }>()("acme/CurrentUser") {}

const WhoAmI = Tool.make("comp_whoami", { success: Schema.String, dependencies: [CurrentUser] })
const Tools = Toolkit.make(WhoAmI)
const AsTestUser = McpServer.middleware<{ provides: CurrentUser }>()((effect) =>
  Effect.provideService(effect, CurrentUser, { id: "test-user" })
)

const Registrations = McpServer.toolkit(Tools).pipe(
  Layer.provide(AsTestUser.layer),
  Layer.provide(Tools.toLayer({ comp_whoami: () => Effect.map(CurrentUser, (user) => user.id) }))
)

it.effect("calls a tool over the JSON-RPC wire encoding", () =>
  Effect.gen(function*() {
    const client = yield* McpTest.makeClient(Registrations, { protocols: [McpProtocol.v2025_11_25] })
    const listed = yield* client.listTools()
    assert.deepStrictEqual(listed.tools.map((tool) => tool.name), ["comp_whoami"])
    const result = yield* client.callTool({ name: "comp_whoami", arguments: {} })
    assert.deepStrictEqual(result.content, [{ type: "text", text: "test-user" }])
  }).pipe(Effect.scoped))
```

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

# Workflows & Durable Execution

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

`effect/workflow` — unstable

`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)`.

```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)`).

### Finalizers, compensation, and cancellation

Three cleanup mechanisms exist, and they answer to different owners.

| Mechanism | Runs when | Use it for |
| --- | --- | --- |
| `Workflow.addFinalizer((exit) => …)` | The **execution** reaches a terminal state (`Complete`), on whichever runner finishes it. Skipped when an owner merely abandons an attempt. | Durable, terminal-state work: publish "raise workflow finished", release a durable reservation. |
| `Workflow.withCompensation(step, undo)` | The execution terminates in failure **after** `step` 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. |

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

### Abandoned run attempts

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

`effect/workflow` — unstable

`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 `Activity` *is* 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.

```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

`effect/workflow` — unstable

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

```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](./systems/cluster-sharding.md#running-on-cloudflare-durable-objects)).

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

`effect/workflow` — unstable

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

```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 `into` *records* 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

`effect/workflow` — unstable

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

```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

`effect/workflow` — unstable

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

```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](#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](./systems/cluster-sharding.md#clusterworkflowengine). That engine also retries transient `PersistenceError`s 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](./systems/cluster-sharding.md#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

`effect/workflow` — unstable

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

```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

`effect/workflow` — unstable

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

```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 const

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

## Replay, versioning, and rollout

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. |
| `Activity` `name` | Journal key for the recorded `Exit` | Replay finds no record and **executes the activity again**. |
| `DurableClock` / `DurableDeferred` / `DurableQueue` `name` | Journal key, and part of every deferred token | Outstanding tokens and wake-ups no longer match. |
| `payload`, `success`, `error` schemas (workflow, activity, deferred, queue) | Encoded bytes in storage | 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.

## Recovery testing and operations

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.

# Cluster & Sharding

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/80_cluster) 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](#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](#transport-options).

## Entity

`effect/cluster` — unstable

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.

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

```ts
import { BigDecimal, Effect } from "effect"

const program = Effect.gen(function*() {
  const departmentFor = yield* Department.client
  const engineering = departmentFor("dept-eng")

  const remaining = yield* engineering.RecordRaise({
    employeeId: "emp-42",
    amount: BigDecimal.fromBigInt(8_000n)
  })
  yield* Effect.log(`engineering merit budget remaining: ${BigDecimal.format(remaining)}`)
})
```

> **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](#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.

## Sharding

`effect/cluster` — unstable

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.

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

### Transport options

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

```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](./interfaces/rpc.md).

### Rebalance and shutdown behavior

- **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](#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`](#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*.

### Running on Cloudflare Durable Objects

`CloudflareCluster.layer` from the experimental [`@effect/platform-cloudflare`](./interfaces/platform-runtime-hosts.md#platform-packages) 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.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { 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`](#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](./systems/workflows-durable-execution.md#durableclock)).

## Singleton

`effect/cluster` — unstable

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.

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

## Runner

`effect/cluster` — unstable

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.

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

## Runners

`effect/cluster` — unstable

The node-to-node communication service. Where `Sharding` *decides* where a message goes, `Runners` *delivers* 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](#transport-options)).

**Reach for it when** implementing a new cluster transport. Otherwise, pick a runner layer.

## MessageStorage

`effect/cluster` — unstable

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](#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.

## MessageRetention

`effect/cluster/MessageRetention` — unstable

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](#singleton) (named `effect/cluster/MessageRetention/<entity type>`) which deletes the entity type's completed requests once their final reply is older than `retention`.

```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_format` `ROW` 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](#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.

## Snowflake

`effect/cluster` — unstable

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.

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

## EntityProxy

`effect/cluster` — unstable

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.

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

## ClusterCron

`effect/cluster` — unstable

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.

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

## ShardingConfig

`effect/cluster` — unstable

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.

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

### Capacity limits and their defaults

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](#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`](#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.

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

**Addresses & identifiers**

## EntityAddress

`effect/cluster` — unstable

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

## EntityId

`effect/cluster` — unstable

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.

## EntityType

`effect/cluster` — unstable

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.

## RunnerAddress

`effect/cluster` — unstable

A `host` + `port` `Schema.Class` identifying how to reach a runner, with structural equality, hashing, and a stable primary key. `RunnerAddress.make("10.0.0.4", 34431)`.

## ShardId

`effect/cluster` — unstable

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.

## SingletonAddress

`effect/cluster` — unstable

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.

## MachineId

`effect/cluster` — unstable

A branded integer marking the machine component of a runner — the middle bits of a Snowflake. Keeps the value distinct from a plain `number` in APIs.

**Runner transports & health**

## RunnerServer

`effect/cluster` — unstable

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.

## RunnerHealth

`effect/cluster` — unstable

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

## SingleRunner

`effect/cluster` — unstable

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`).

## SocketRunner

`effect/cluster` — unstable

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

## HttpRunner

`effect/cluster` — unstable

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

## TestRunner

`effect/cluster` — unstable

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

## K8sHttpClient

`effect/cluster` — unstable

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.

## K8sTypes

`effect/cluster/K8sTypes` — unstable

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.

**Durable storage backends**

## SqlMessageStorage

`effect/cluster` — unstable

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](#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).

## SqlRunnerStorage

`effect/cluster` — unstable

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.

## RunnerStorage

`effect/cluster` — unstable

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, errors & observability**

## ClusterSchema

`effect/cluster` — unstable

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](./systems/workflows-durable-execution.md#abandoned-run-attempts). 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.

## ClusterError

`effect/cluster` — unstable

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](#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. |

## ClusterMetrics

`effect/cluster` — unstable

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.

## ShardingRegistrationEvent

`effect/cluster` — unstable

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.

**Wire protocol & message shapes**

## Envelope

`effect/cluster` — unstable

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.

## Message

`effect/cluster` — unstable

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.

## Reply

`effect/cluster` — unstable

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.

## DeliverAt

`effect/cluster` — unstable

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.

**Entity helpers & durable workflows**

## EntityProxyServer

`effect/cluster` — unstable

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.

## EntityResource

`effect/cluster` — unstable

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

## ClusterWorkflowEngine

`effect/cluster` — unstable

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](./systems/workflows-durable-execution.md#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](./systems/workflows-durable-execution.md).

# EventLog & Event Sourcing

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

`effect/eventlog` — unstable

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

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

## EventGroup

`effect/eventlog` — unstable

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.

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

## EventLog

`effect/eventlog` — unstable

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.

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

## EventRow

`effect/eventlog/EventRow` — unstable

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.

```ts
import { Effect, Schema } from "effect"
import { EventGroup, EventLog, EventRow } from "effect/eventlog"

const Proposal = EventRow.make("proposal", {
  key: "id",
  schema: Schema.Struct({ id: Schema.String, employeeId: Schema.String, increasePct: Schema.Number })
})
const Proposals = EventGroup.empty.add(Proposal)
const schema = EventLog.schema(Proposals)

const store = new Map<string, typeof Proposal.schema.Type>()

export const ProposalsLive = EventLog.group(Proposals, (handlers) =>
  handlers.handle(
    "proposal",
    EventRow.handler(Proposal, {
      set: (row) => Effect.sync(() => store.set(row.id, row)),
      patch: (id, fields) =>
        Effect.sync(() => {
          const row = store.get(id)
          if (row !== undefined) store.set(id, { ...row, ...fields })
        }),
      remove: (id) => Effect.sync(() => store.delete(id))
    })
  ))

export const adjust = Effect.fn("adjust")(function*(id: string, increasePct: number) {
  const log = yield* EventLog.EventLog
  yield* log.write({ schema, ...Proposal.patch(id, { increasePct }) })
})
```

Use `EventRow` for local-first, editable records (drafts, settings, lists) rather than hand-written last-writer-wins events.

## EventJournal

`effect/eventlog` — unstable

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.

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

## EventLogEncryption

`effect/eventlog` — unstable

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/crypto` `Aead`, `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.

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

## EventLogRemote

`effect/eventlog` — unstable

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.

```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`](#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.

## EventLogServer

`effect/eventlog` — unstable

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.

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

## EventLogServerEncrypted

`effect/eventlog` — unstable

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.

## EventLogServerUnencrypted

`effect/eventlog` — unstable

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.

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

## EventLogSessionAuth

`effect/eventlog` — unstable

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 `Hello`s 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.

## EventLogMessage

`effect/eventlog` — unstable

The wire protocol shared by clients and servers. Defines branded `StoreId`s, 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.

## SqlEventJournal

`effect/eventlog` — unstable

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.

## SqlEventLogServerEncrypted

`effect/eventlog` — unstable

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.

## SqlEventLogServerUnencrypted

`effect/eventlog` — unstable

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 `EventGroup`s, 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.

# Choosing Effect Primitives

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.

## Boundary rules before primitives

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.

| Keep explicit inside | Collapse it only at | Owning section |
| --- | --- | --- |
| Absence (`Option`) | a display or protocol edge that owns the fallback | [Fallbacks and boundary exits](./foundations/errors-option-result.md#fallbacks-and-boundary-exits) |
| Expected failure (`E`) | the terminal boundary that owns the response, with one fold | [Folding both channels at a boundary](./foundations/errors-option-result.md#folding-both-channels-at-a-boundary) |
| Untrusted representation (`unknown`) | ingress: decode once, with that boundary's parse options | [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy) |
| Requirements (`R`) | the application, module, or test edge that provides them | [Providing one value or building a graph](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph) |
| Execution (laziness) | a runner at an edge that owns the fiber | [Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) |
| Lifetime (`Scope` in `R`) | the narrowest owner that is still valid | [Write the ownership ledger first](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#write-the-ownership-ledger-first) |
| Secrets (`Redacted`) | the single call that needs the bytes | [Redacted](./foundations/configuration-secrets.md#redacted) |
| Units of time (`Duration`) | an interop edge that requires a number | [Parsing untrusted durations and interop edges](./concurrency/scheduling-time.md#parsing-untrusted-durations-and-interop-edges) |

**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](./deep-dives/adopting-effect-in-an-existing-codebase.md#decide-what-to-leave-out).

## Constructor by source convention

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 |
| A Promise that can reject | `Effect.tryPromise({ try: (signal) => ..., catch })` | the typed error `catch` returns | the thunk ignores `signal`: interruption then stops the fiber but not the I/O |
| A Promise that is not expected to reject | `Effect.promise((signal) => ...)` | a defect | the call touches a network, disk, or SDK; `Effect.promise(() => fetch(url))` moves every outage out of `E` |
| A one-shot callback API | `Effect.callback<A, E>((resume, signal) => ...)` | whatever is passed to `resume`; only the first call counts | the source emits many values; use a `Queue` or `Stream.callback` |
| Building the next effect is itself work | `Effect.suspend(() => effect)` | a defect if the thunk throws | a plain conditional inside `Effect.gen` already defers it |
| An `Option`, `Result`, or nullable value | `Effect.fromOption`, `Effect.fromResult`, `Effect.fromNullishOr` | not applicable | you expected `yield*` to accept the `Option` or `Result` directly; it does not |

Details: [Creating effects](./foundations/core-runtime-execution.md#1-creating-effects), [Cancellable adapters for promises and callbacks](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks).

## Runner by host contract

Choose the runner by the outcome contract the host needs. Reusable code — services, domain functions, libraries — never calls one.

| Runner | Returns | Failure surfaces as | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- |
| `Effect.runSync` / `runSyncExit` | `A` / `Exit<A, E>` | a `throw` / a defect holding `AsyncFiberError` at the first asynchronous boundary | the effect is known to finish synchronously | anything may suspend; the types cannot tell you |
| `Effect.runPromise` | `Promise<A>` | a rejection with the squashed cause; failure, defect, and interruption are no longer distinct | a JavaScript edge wants value-or-rejection | the host must tell cancellation from failure |
| `Effect.runPromiseExit` | `Promise<Exit<A, E>>` | always resolves | an adapter, reporter, or test must keep the three outcomes apart | — |
| `Effect.runFork` | `Fiber<A, E>`, immediately | `Fiber.await` or an observer | the caller keeps the handle and owns its lifetime | nobody will join, observe, or interrupt the fiber |
| `Effect.runCallback` | an interruptor function | the `onExit` callback | callback-style hosts | a Promise or fiber handle fits |
| Platform `runMain` | `void` | a logged error and a process exit code | the process entry point, once | inside application code |
| `ManagedRuntime` | the same family as methods | as above | a non-Effect host calls in repeatedly against one Layer graph | one runtime per request, or disposing without draining first |

The `Effect.run*` and `ManagedRuntime` runners except `runSync` / `runSyncExit` accept `{ signal }`, which turns a host abort into interruption. Platform `runMain` owns process signal handling instead. Details: [Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge), [ManagedRuntime](./foundations/fibers-scopes-runtimes.md#managedruntime), [Bridge into a host that is not Effect](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#bridge-into-a-host-that-is-not-effect).

## Option vs Result vs Effect

| Primitive | Error and requirements | Scope, lifetime, and backpressure | Durability and distribution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `Option<A>` | 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`.

Before choosing a channel at all, decide whether the outcome is a *result* or a *failure*: a correct negative answer that every caller treats as ordinary output belongs in `A`, not in `E`. Details: [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model), [Moving between Option, Result, and Effect](./foundations/errors-option-result.md#moving-between-option-result-and-effect), [Exit](./foundations/fibers-scopes-runtimes.md#exit).

Official guides: [Expected Errors](https://effect.website/docs/v4/error-management/expected-errors), [Exit](https://effect.website/docs/v4/data-types/exit).

## Recovery operator by intent

| Intent | Operator | What remains in `E` | Avoid it when |
| --- | --- | --- | --- |
| Handle one or several tagged variants | `Effect.catchTag("A")`, `catchTag(["A", "B"])`, `catchTags({ ... })` | every other variant | the policy depends on a field rather than the tag |
| Handle by predicate, refinement, or `Filter` | `Effect.catchIf`, `Effect.catchFilter` | what the selector rejects | 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](./foundations/errors-option-result.md#effect-error-handling), [Recovery and mixed causes](./foundations/errors-option-result.md#recovery-and-mixed-causes), [Classifying an error union](./foundations/errors-option-result.md#classifying-an-error-union).

## Fail fast or accumulate

| Need | Use | Outcome | Avoid it when |
| --- | --- | --- | --- |
| Stop the batch at the first problem | `Effect.all` / `Effect.forEach` (the default mode; sequential unless `concurrency` is set) | fails with the first `E`; no partial successes are returned | the caller needs every problem at once |
| Every problem at once, or else every value | `Effect.validate(items, f, { concurrency? })` | `Array<B>`, or fails with `NonEmptyArray<E>` | successes matter even when some items fail |
| Act on both sides | `Effect.partition(items, f, { concurrency? })` | never fails: `[failures, successes]` | a failure should stop the caller |
| One outcome per member, in the input's shape | `Effect.all(effects, { mode: "result" })` | a `Result` per member | a flat list of failures is enough |
| Every Schema issue of one decode | the parse option `errors: "all"` | one `SchemaError` holding every reachable issue | you would read "no issue reported" as "every rule ran" |

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 one. Details: [Accumulating errors instead of failing fast](./foundations/errors-option-result.md#accumulating-errors-instead-of-failing-fast), [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy).

## Providing dependencies by seam

| Seam | Effect on `R` | What is built, and how often | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- |
| `Effect.provideService(Service, value)` | removes exactly one identifier | nothing is built; the value already exists | a focused test fake, a script, a per-request value set by middleware | the implementation needs state, configuration, other services, or teardown |
| `Effect.provide(context)` | removes every key in the `Context` | nothing is built | several ready values travel together | the values need construction |
| `Layer.succeed(Service, value)` | removes the output | a finished value, no finalizer | a constant implementation inside a Layer graph | anything must be closed; it cannot express teardown |
| `Layer.effect(Service, constructor)` | removes the output, adds the constructor's needs (minus `Scope`) | once per memo map; the Layer build owns the scope of `acquireRelease` | state, configuration, other services, or a lifetime | — |
| One `Effect.provide(AppLive)` at the edge, or one `ManagedRuntime` | closes `R` to `never` | every Layer value once, released at shutdown | the application root | repeated next to each use: sibling `Effect.provide(PoolLive)` calls build two pools |
| `Effect.provide(layer, { local: true })` | same | a brand-new memo map: the whole provided graph is rebuilt, then released when that effect ends | deliberate isolation per tenant, test, or transaction | silencing a type error; it duplicates pools, caches, and subscriptions |
| `Layer.fresh(layer)` | same | that Layer and its dependencies are private to one branch of a build | one branch needs its own instance | as a default; sharing is the resource-safety default |
| `Effect.serviceOption(Service)` | does not add the service | — | a capability the host may or may not install | the feature is required; the compiler will not remind anyone to provide it |

Provide live implementations only at application or module edges and fakes only at test edges. Details: [Providing one value or building a graph](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph), [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt), [Resourceful services](./foundations/services-context-layers.md#resourceful-services), [Optional services](./foundations/services-context-layers.md#optional-services).

## Fork by owner

Name the owner first; the fork function follows.

| Function | Owner | Interrupted when | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- |
| `Effect.forkChild` | the current fiber | the parent ends, for any reason | the work must not outlive the code that started it | the work has to survive the function that forked it |
| `Effect.forkScoped` (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, such as an `Effect.scoped` around the fork itself |
| `Effect.forkIn(effect, scope)` | a `Scope` you were handed | that scope closes | "start it here, own it there" | the current scope is already the right owner |
| `Effect.forkDetach` | nobody | never, unless someone keeps the handle | process-lifetime work with a documented stop path | library and domain code; an unowned detached fiber is a leak |
| `FiberSet` / `FiberMap` / `FiberHandle` | a scoped supervisor | the supervisor's scope closes; `FiberMap` and `FiberHandle` also replace by key or slot | a dynamic population of fibers, keyed jobs, or "at most one running" | the population is static; `Effect.forEach` with `concurrency` is smaller |
| No fork: `Effect.all` / `forEach` / `race` | the combinator | the combinator ends | a finite batch or a race | — |

All four fork functions accept `{ startImmediately, uninterruptible }`; a forked fiber is otherwise only *scheduled* until the parent yields, so a listener forked just before a publish can miss it. Details: [Choosing a fork by its owner](./foundations/fibers-scopes-runtimes.md#choosing-a-fork-by-its-owner), [When a forked fiber starts](./foundations/fibers-scopes-runtimes.md#when-a-forked-fiber-starts), [Structured concurrency is ownership](./deep-dives/structured-concurrency-through-a-bounded-worker.md#structured-concurrency-is-ownership).

## Resource lifetime and bracket

| Shape | Lifetime unit | Who closes it | May cleanup fail in `E`? | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `Effect.acquireUseRelease(acquire, use, release)` | one `use` call | the combinator | yes | the resource lives for exactly one operation and the caller must see a failed release, such as a commit or flush | the handle must outlive `use` |
| `Effect.acquireRelease` + `Effect.scoped` | the scoped region | `Effect.scoped` | no; the finalizer's error type is `never` | several resources share one region and release in reverse order | the value escapes the region; returning it is a use-after-release bug |
| `Effect.acquireRelease` inside `Layer.effect` | the Layer's owner: application, `ManagedRuntime`, or test | the Layer build's scope | no | pools, clients, exporters, listeners | the resource is per request; providing the Layer in a handler acquires it per request |
| `Effect.ensuring` / `Effect.onExit` / `Effect.onError` | one effect | the combinator | only `onExit` | cleanup with no handle to pass: a gauge decrement, a `Deferred` completion, a flag | there is a resource; pair it with its acquisition instead |
| `Effect.addFinalizer` | the current `Scope` | whoever owns that scope | no | registering cleanup from inside a scoped constructor | nothing will discharge the `Scope` it adds to `R` |
| `Stream.unwrap` over a scoped effect, `Stream.scoped` | the stream's consumption | the stream, on completion, failure, interruption, and early stop | no | a cursor, file, or subscription read incrementally | acquiring before the stream and closing "when done" |
| `Pool.get`, `ScopedCache`, `RcRef` / `RcMap` | a borrow or a cache entry | the pool, cache, or reference count | no | bounded sharing of expensive instances | one long-lived client is enough |

Give every handle its own bracket, because a release is registered only after its acquisition succeeds. `Scope` left in `R` means nobody owns the lifetime yet. Details: [Interruption & resource safety](./foundations/core-runtime-execution.md#6-interruption-resource-safety), [When cleanup can fail](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail), [One bracket per resource](./deep-dives/anatomy-of-a-real-effect-application.md#one-bracket-per-resource), [Owning resources inside a stream](./concurrency/streaming-channels.md#6-owning-resources-inside-a-stream).

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

Each `Ref` operation is atomic; a `Ref.get` followed by a `Ref.set` is two transitions and loses updates under concurrency. Details: [One transition, one call](./concurrency/state-mutable-references.md#one-transition-one-call), [Choosing the right state tool](./concurrency/state-mutable-references.md#choosing-the-right-state-tool), [Failure rolls back; snapshots need one transaction](./concurrency/software-transactional-memory.md#failure-rolls-back-snapshots-need-one-transaction).

## Deferred vs Latch vs Queue vs PubSub

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? | wait / shed / latest | the `bounded`, `dropping`, or `sliding` constructor — see [Overload semantics at a glance](#overload-semantics-at-a-glance) |

| Primitive | Error and requirements | Scope, lifetime, and backpressure | Durability and distribution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `Deferred<A, E>` | 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. |

Details: [Delivery semantics: Queue or PubSub](./concurrency/concurrency-coordination.md#delivery-semantics-queue-or-pubsub), [Queue lifecycle: who ends it, and what a failure does](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does), [Deferred](./foundations/fibers-scopes-runtimes.md#deferred), [Latch](./foundations/fibers-scopes-runtimes.md#latch).

Official guide: [Latch](https://effect.website/docs/v4/concurrency/latch).

## Overload semantics at a glance

Decide which failure mode you want **before** picking a constructor. `dropping` and `sliding` are stated loss policies, never performance switches.

| Strategy | `Queue.offer` | `PubSub.publish` | `Stream.buffer` / `Stream.callback` | What is lost | Choose it when |
| --- | --- | --- | --- | --- | --- |
| Suspend (`Queue.bounded`, `PubSub.bounded`, `strategy: "suspend"`) | the producing fiber waits, then gets `true` | waits while any subscriber lags by a full buffer | upstream is back-pressured | nothing | every value must be processed **and** the producer is an Effect that can wait |
| Dropping | returns `false`; `offerAll` returns the rejected remainder | returns `false`; the message is dropped for every subscriber | the newest elements are discarded | the newest values | shedding load is an accepted policy and the `false` results are counted |
| Sliding | returns `true`; the eviction is **not** reported | returns `true`; only lagging subscribers miss the evicted message | the oldest elements are evicted | the oldest values | only the latest state matters: progress, presence, prices |
| Unbounded (`Queue.unbounded`, `PubSub.unbounded`, `capacity: "unbounded"`, and the **default** of `Stream.callback`) | always `true` | always `true` | nothing pushes back | nothing, until memory runs out | something else you can name already bounds the producer |

A synchronous callback cannot wait: `Queue.offerUnsafe` and `PubSub.publishUnsafe` return `false` on a full bounded buffer instead of suspending, so a bounded buffer in front of a callback producer is a loss policy whether or not it is named one. Durable delivery semantics (at-least-once, leases, outbox) are a separate ladder. Details: [Queue](./concurrency/concurrency-coordination.md#queue), [Make loss observable](./concurrency/concurrency-coordination.md#make-loss-observable), [Overflow strategies and the publish result](./concurrency/concurrency-coordination.md#overflow-strategies-and-the-publish-result), [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides), [Durability and Distribution Ladder](./deep-dives/durability-and-distribution-ladder.md).

## Per-call concurrency vs Semaphore vs Pool

| Primitive | Error and requirements | Scope, lifetime, and backpressure | Durability and distribution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `{ 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. |

Never use `concurrency: "unbounded"` merely to make a batch faster. Use it only when the input is already tightly bounded and every downstream system can accept the resulting load. Several library defaults are unbounded and need an explicit number: `RpcServer` handler concurrency, AI tool-call resolution, and `Stream.callback` buffering. Details: [Write the execution policy first](./deep-dives/structured-concurrency-through-a-bounded-worker.md#write-the-execution-policy-first), [TTL is not a health check](./concurrency/concurrency-coordination.md#ttl-is-not-a-health-check), [Operational defaults](./interfaces/rpc.md#operational-defaults), [Tool-call resolution: concurrency and manual dispatch](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch).

## Single-flight, cache, or batching

Repeated work has three different shapes, and each tool fixes exactly one. Measure first: hit ratio, lookup count per request, resolver batch size.

| Waste shape | What the measurement shows | Tool | Why the neighbors do not help |
| --- | --- | --- | --- |
| One expensive effect, no key | the same effect runs once per caller instead of once per freshness window | `Effect.cached`, `Effect.cachedWithTTL`, `Effect.cachedInvalidateWithTTL` | a keyed cache is machinery you do not need |
| Repeat lookup of the same key | lookup count ≈ request count; keys recur | `Cache` with a key, capacity, and TTL | 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?](./operations/caching-batching.md#which-problem-do-you-have), [Caching a single Effect](./operations/caching-batching.md#caching-a-single-effect), [Resolver obligations](./operations/caching-batching.md#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. |

With `Cache.make`, a cached failure lives exactly as long as a cached success; give failures their own lifetime with `Cache.makeWith`. Details: [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy), [Keys are logical values](./operations/caching-batching.md#keys-are-logical-values).

## Array, Chunk, Iterable vs Stream, Sink, Channel

| Primitive | Error and requirements | Scope, lifetime, and backpressure | Durability and distribution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `Array` / `ReadonlyArray` | Plain data; no `E` or `R`. | Eager and fully resident. JavaScript arrays are the interoperability default. | Data only. | The complete, reasonably sized collection is already in memory. | The source is unbounded or larger than the available memory. |
| `Chunk<A>` | Plain immutable collection; no `E` or `R`. | Strict, compact collection optimized for repeated functional concatenation/slicing and used at streaming boundaries. | Data only. | You need an immutable batch value or an efficient intermediate collection. | Data should be processed incrementally rather than materialized. |
| `Iterable<A>` | Lazy synchronous pull protocol; no typed failure/services in the protocol. | Consumer-driven but synchronous and generally single-pass. No async backpressure, interruption, or scoped cleanup contract. | Data only. | Values can be produced synchronously and cheaply as requested. | Production is asynchronous, fallible, resourceful, or must be interrupted safely. |
| `Stream<A, E, R>` | Typed stream failure `E` and services `R`. | High-level, lazy, chunked, interruptible pipeline. Operators express concurrency and buffering; a Sink runs it. | Ephemeral unless connected to durable input/output. | Processing zero-to-many asynchronous values without collecting them all. | A single Effect or already-materialized collection is simpler. |
| `Sink<A, In, L, E, R>` | Typed failure/services; emits a result `A` and may leave leftovers `L`. | Reusable consumer/fold attached with `Stream.run`. Can stop before the source ends and compose with other sinks. | Ephemeral unless the sink writes durably. | Consumption logic deserves a named, composable value: parsing, folding, batching, or validation. | A one-line `runCollect`/`runForEach` is sufficient. |
| `Channel<OutElem, OutErr, OutDone, InElem, InErr, InDone, R>` | 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.

Official guides: [Introduction to Streams](https://effect.website/docs/v4/stream/introduction), [Sink introduction](https://effect.website/docs/v4/sink/introduction).

## Stream buffering and batching operators

Flow-control depth, batch size, and rate are three different knobs. **Buffer capacity is not batch size.**

| Need | Operator | What it retains | Avoid it when |
| --- | --- | --- | --- |
| Decouple a fast producer from a slow consumer | `Stream.buffer({ capacity, strategy? })` | up to `capacity` elements; `"suspend"` back-pressures, `"dropping"` / `"sliding"` lose data | you wanted batches, or a cheap prefix: `buffer` runs ahead of a downstream `take` |
| Fixed-size batches from a finite source | `Stream.grouped(n)` | the batch under construction | the source is live: a partial batch waits indefinitely |
| Batches by size **or** elapsed time | `Stream.groupedWithin(n, duration)` | the batch under construction | the source is a finite file import; `grouped` is simpler |
| A custom batch boundary (weight, cost) | `Stream.aggregateWithin(sink, schedule)`, `Stream.transduce(sink)` | whatever the `Sink` accumulates | size or time already expresses it |
| Resize chunks for an array-consuming sink | `Stream.rechunk(n)` | one chunk | the consumer needs arrays as *elements*; that is `grouped` |
| Bound in-flight effectful work | `Stream.mapEffect(f, { concurrency })` | up to `concurrency` inputs and results | `"unbounded"` over an uncontrolled source |
| Limit rate | `Stream.throttle`, `Stream.schedule` | one chunk / one element | the goal is load shedding by count; that is a dropping buffer |
| Keep only the latest after a quiet period | `Stream.debounce(duration)` | the latest value | every value matters |
| Bound a push source | `Stream.callback(register, { bufferSize, strategy })` | **unbounded unless `bufferSize` is set** | the listener is synchronous and you describe the adapter as back-pressured |

Pull-based back-pressure bounds a pipeline only if every stage is bounded. Details: [Transforming streams](./concurrency/streaming-channels.md#2-transforming-streams), [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides), [Adapting, leftovers, and repeatable batching](./concurrency/streaming-channels.md#adapting-leftovers-and-repeatable-batching), [Batch by size or time when the source is live](./deep-dives/streaming-ingestion-without-accidental-buffering.md#batch-by-size-or-time-when-the-source-is-live).

## Wire codec: JSON, NDJSON, or SchemaBinary

| Codec | Framing | Failure type | Evolution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| JSON through a Schema codec (`Schema.toCodecJson`, `Schema.fromJsonString`; `RpcSerialization.layerJson`) | none: one document per message | `Schema.SchemaError` | ordinary Schema evolution: optional keys, decoding defaults, unions of versions | one request, one response; public HTTP; human-readable storage | many messages share one long-lived connection |
| `Ndjson` (`RpcSerialization.layerNdjson`) — unstable | one JSON value per line | `NdjsonError` (`kind: "Pack"` or `"Unpack"`) for the JSON step, `Schema.SchemaError` for validation | as JSON | streaming, sockets, the peer is not an Effect program, frames must be inspectable | payload size dominates, or an unbounded line from an untrusted peer is not capped |
| `SchemaBinary`, default mode (`RpcSerialization.layerSchemaBinary()`) — unstable | 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](./concurrency/streaming-channels.md#schemabinary), [Ndjson](./concurrency/streaming-channels.md#ndjson), [RpcSerialization](./interfaces/rpc.md#rpcserialization), [Serialization codecs](./data/schema-in-depth.md#2-serialization-codecs).

## HttpClient vs HttpRouter vs HttpApi vs RPC

These modules are `@stability unstable`; pin all Effect packages to exactly the same release. The adjacent [GraphQL](./interfaces/graphql.md) 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. |
| `HttpRouter` | Handlers retain typed errors/services until served; platform/server Layers supply runtime requirements. | Low-level inbound routes and middleware over HTTP requests/responses, including streaming. Server lifetime is scoped. | Remote HTTP endpoint, not durable by itself. | Webhooks, static/custom responses, or routing that does not fit a schema-first API. | A contract-first API with generated client and OpenAPI is desired. |
| `HttpApi` | Endpoint Schemas define decoded inputs, success, and typed HTTP errors; middleware declares services. Server/client platform Layers add requirements. | Contract-first HTTP groups/endpoints. Derives handlers, client, OpenAPI, security, docs, and in-memory tests. | Remote HTTP endpoint, not durable by itself. | Browser/public REST semantics, status codes, headers, and OpenAPI matter. | The interface is internal procedure calls with no need for HTTP resource semantics. |
| `RPC` | Each request has payload, success, and error Schemas; routers/middleware/transports add services and transport errors. | Typed request/response and streaming procedures over HTTP, sockets, workers, or in-memory transports. | Distributed transport, not durable by default. | Services share a typed procedure contract and may need streaming or multiple transports. | Public REST/OpenAPI compatibility matters, or calls must survive outages/restarts as workflows. |

Details: [Three failure classes](./interfaces/http-client.md#three-failure-classes), [Status mapping is part of the contract](./interfaces/http-api.md#status-mapping-is-part-of-the-contract), [Evolving a contract](./interfaces/rpc.md#evolving-a-contract), [Keep six failure categories distinguishable](./interfaces/rpc.md#keep-six-failure-categories-distinguishable).

### When the remote contract is GraphQL

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.

Details: [GraphQL](./interfaces/graphql.md).

## Retry vs repeat vs polling vs Workflow

| Primitive | Error and requirements | Scope, lifetime, and backpressure | Durability and distribution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `Effect.retry(schedule)` | 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. |

Always bound and classify retry. A retry policy that accepts every error can turn authorization, validation, or schema failures into an outage amplifier. The options form `{ while }` with no `schedule` or `times` is a zero-delay loop. `Effect.timeout` before `retry` bounds each attempt; after it, the whole operation. Details: [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist), [Shorthand options for retry and repeat](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat), [Where the timeout sits relative to retry](./deep-dives/failure-retry-fallback-and-interruption.md#where-the-timeout-sits-relative-to-retry), [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout).

Official guides: [Retrying](https://effect.website/docs/v4/error-management/retrying), [Using schedules](https://effect.website/docs/v4/scheduling/using-schedules), [Schedule cookbook](https://effect.website/docs/v4/scheduling/cookbook).

## Persistence vs EventLog vs Workflow vs Cluster

| Primitive | Error and requirements | Scope, lifetime, and backpressure | Durability and distribution | Choose it when | Avoid it when |
| --- | --- | --- | --- | --- | --- |
| `Persistence` / `PersistedCache` | 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. |

These systems compose rather than replace one another. A clustered Workflow runner may use Persistence for journals; a Workflow Activity may append to an EventLog; an Entity may use SQL for state. Select the semantic owner first, then add transport and storage deliberately. A write plus an external effect that must both happen is an outbox, not a bigger transaction. Details: [What each primitive guarantees](./tooling/persistence.md#what-each-primitive-guarantees), [Failure windows and honest guarantees](./tooling/persistence.md#failure-windows-and-honest-guarantees), [External effects after commit (outbox)](./interfaces/sql.md#external-effects-after-commit-outbox), [A compact selection guide](./deep-dives/durability-and-distribution-ladder.md#a-compact-selection-guide).

## Test tool by claim

Pick the tool by the claim you need to prove; each is evidence for that claim and nothing beyond it.

| Claim under test | Tool | It does not prove |
| --- | --- | --- |
| A delay, timeout, retry spacing, or TTL behaves as specified | `TestClock` inside `it.effect`: fork, adjust, join | that a real driver or OS timer honors the same timing |
| Orchestration, typed failures, interruption, cleanup | `it.effect` plus replacement Layers; assert on `Exit` | the real adapter's behavior |
| `Console.*` output / `Effect.log*` records | `TestConsole` / a capturing test `Logger` | each other |
| Reproducible crypto-service random bytes and UUIDs | A seeded [`SecureRandom`](./tooling/testing-dev-tooling.md#deterministic-crypto-in-tests) layer beside the host [crypto](./interfaces/cryptography.md) layers | cryptographic security of the seeded test generator; `Random` operations use a separate seed |
| A rule holds for every valid input | `Arbitrary.schema` via `it.effect.prop` | rejection of malformed wire input; generated values are already valid |
| A codec decodes, encodes, and round-trips | `TestSchema` | cross-field rules the schema does not state |
| HTTP or RPC contract, routing, middleware, status mapping | `HttpApiTest.groups`, `RpcTest.makeClient` | sockets, malformed wire input, and for `RpcTest` serialization |
| An adapter works against a real dependency | `layer(L, { excludeTestServices: true })` or `it.live`, with a scoped real fixture | that the packaged entry point starts, serves, and shuts down |
| Durable orchestration and storage *contracts* | `WorkflowEngine.layerMemory`, `Persistence.layerMemory`, `KeyValueStore.layerMemory` | durability across a restart |
| `E` and `R` are exactly what the contract says | `expectTypeOf` under the type checker | any runtime behavior |
| The shipped artifact starts, serves, and stops | launch the built bundle or container | — |

Details: [Testing & Dev Tooling](./tooling/testing-dev-tooling.md), [In-memory test runtimes shipped with Effect](./tooling/testing-dev-tooling.md#in-memory-test-runtimes-shipped-with-effect), [Model the proof before writing the test](./deep-dives/testing-an-effect-application.md#model-the-proof-before-writing-the-test), [The built-artifact lane](./deep-dives/testing-an-effect-application.md#the-built-artifact-lane).

## Host and runtime ownership

A platform Layer says how a capability is implemented; the host decides who owns the runtime, what cancels work, and whether cleanup is awaited.

| Host | Runner and owner | What cancels work | What it cannot promise | Avoid |
| --- | --- | --- | --- | --- |
| Node / Bun / Deno process | one platform `runMain` at the root; the launched Layer's scope owns everything | SIGINT and SIGTERM interrupt the main fiber; finalizers run before exit | surviving SIGKILL or an expired grace period | `process.exit()` in application code |
| Web-standard handler (serverless, edge) | `HttpRouter.toWebHandler` returns `{ handler, dispose }`; module scope owns the Layer, each request its own scope | `request.signal` interrupts the request fiber | that `dispose` is ever awaited, or that work continues after the response | `node:*` assumptions; work scheduled past the response |
| Request-scoped MCP on a serverless host | `McpServer.layerHttpRequestScoped`; each POST owns its server | the request ending closes its server scope | sessions, subscriptions, or background work past the request | using long-lived `layerHttp` fibers in a request-bound host |
| Foreign framework callback (Express, Hono, UI, plugin API) | one `ManagedRuntime`, created and warmed at boot, disposed by the host's shutdown hook | nothing, unless you forward the host's `AbortSignal` with `{ signal }` and stop admission yourself | a drain: `dispose()` interrupts managed fibers and awaits cleanup before releasing the Layer, rather than letting requests finish normally | a runtime per request |
| Browser page | `BrowserRuntime.runMain` | a non-persisted `pagehide` | completion of asynchronous finalizers or network flushes | relying on a final flush |
| Worker thread or child process | the parent's scope around the worker; the worker side runs a `WorkerRunner` | the parent scope closing | worker-side cleanup longer than the adapter's grace period | unscoped spawns |
| CLI | `Command.run` handed to the platform `runMain` | as a process | — | a second runner inside a command handler |
| Test | the scope of `it.effect` / `it.layer` | the end of the test; time is virtual | anything about real signals, ports, files, or bundling | claiming host behavior from fakes |

Business code is identical in every row; only the outermost line and the platform Layer change. Details: [Choosing a host](./interfaces/platform-runtime-hosts.md#choosing-a-host), [The host matrix](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#the-host-matrix), [Choose the correct runtime edge](./deep-dives/anatomy-of-a-real-effect-application.md#choose-the-correct-runtime-edge).

## More choosers on their owning pages

| Decision | Owning section |
| --- | --- |
| Which Schema decode runner, by who consumes the failure | [Decoding and encoding — pick your result style](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) |
| Optional key, `undefined`, `null`, or `Option` on the wire | [Optional fields, null, and Option](./data/schema-in-depth.md#6-optional-fields-null-and-option) |
| A setting is required, optional, or defaulted | [Deciding required, optional, and defaulted](./foundations/configuration-secrets.md#deciding-required-optional-and-defaulted) |
| `Config.withDefault` vs `ConfigProvider.orElse` vs `Config.orElse` | [Absence is not malformed input](./foundations/configuration-secrets.md#absence-is-not-malformed-input) |
| Log, span, or metric | [Which signal answers which question](./operations/observability.md#which-signal-answers-which-question) |
| Direct OTLP, the OpenTelemetry SDK bridge, or Prometheus | [One export path per signal](./operations/telemetry-export.md#one-export-path-per-signal) |
| RPC transport: HTTP, WebSocket or socket, worker, stdio | [RpcServer](./interfaces/rpc.md#rpcserver) |
| Cluster runner transport and serialization | [Transport options](./systems/cluster-sharding.md#transport-options) |
| Combining or splitting streams: `merge`, `zip`, `partition`, `broadcast` | [Combining and splitting streams](./concurrency/streaming-channels.md#4-combining-and-splitting-streams) |
| Stream recovery: `catch*`, `retry`, `timeout`, `timeoutOrElse` | [Handling stream failures](./concurrency/streaming-channels.md#5-handling-stream-failures) |
| Workflow finalizer, compensation, or scope finalizer | [Finalizers, compensation, and cancellation](./systems/workflows-durable-execution.md#finalizers-compensation-and-cancellation) |
| Which durability rung | [A compact selection guide](./deep-dives/durability-and-distribution-ladder.md#a-compact-selection-guide) |
| Five kinds of order under concurrency | [Five kinds of order](./deep-dives/structured-concurrency-through-a-bounded-worker.md#five-kinds-of-order) |
| `Match.exhaustive` vs `Match.orElse` | [Closing a matcher](./data/functional-toolkit.md#closing-a-matcher) |

## A compact selection order

0. 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.
1. Is this just data? Start with `Option`, `Result`, Array, Chunk, or Iterable. Keep pure, synchronous, dependency-free transformations as plain functions.
2. 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.
3. 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.
4. 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.
5. 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.
6. Is shared state involved? Choose Ref, SynchronizedRef, SubscriptionRef, or `Effect.tx` according to update and observation semantics.
7. 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.
8. Is work repeated? Measure the waste shape: one effect (`Effect.cached`), the same key (`Cache`), or many keys at once (`RequestResolver`).
9. 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.
10. 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.
11. 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.
12. How will you know? Pick the test tool by the claim, and finish with the [Review Checklists](./reference/review-checklists.md).

# 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](./troubleshooting/troubleshooting-and-anti-patterns.md); for choosing between primitives, from [Choosing Effect Primitives](./reference/choosing-effect-primitives.md).

## Effect construction and running

- 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](./foundations/core-runtime-execution.md#1-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](./foundations/core-runtime-execution.md#1-creating-effects)
- Does every `Effect.tryPromise` / `Effect.promise` thunk declare the `signal` parameter and pass it to the foreign API? [Cancellable adapters for promises and callbacks](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks)
- 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](./foundations/core-runtime-execution.md#8-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](./foundations/core-runtime-execution.md#11-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](./foundations/core-runtime-execution.md#11-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”](./troubleshooting/troubleshooting-and-anti-patterns.md#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](./troubleshooting/anti-patterns.md)
- 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](./foundations/core-runtime-execution.md#9-branching-and-looping)
- Do effect-returning functions use `Effect.fn("name")`, so they carry a span and a readable stack? [Sequencing with gen & fn](./foundations/core-runtime-execution.md#2-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](./deep-dives/adopting-effect-in-an-existing-codebase.md#decide-what-to-leave-out)

## Errors and recovery

- 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](./foundations/errors-option-result.md#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](./foundations/errors-option-result.md#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](./foundations/errors-option-result.md#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](./foundations/errors-option-result.md#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](./deep-dives/failure-retry-fallback-and-interruption.md#recover-at-the-narrowest-owner)
- Does folding (`Effect.match`, `matchEffect`) happen only at the terminal boundary that owns the response? [Folding both channels at a boundary](./foundations/errors-option-result.md#folding-both-channels-at-a-boundary)
- Is every whole-union classification closed with `Match.exhaustive` or `Match.tagsExhaustive`, with no `default` branch or unexplained `Match.orElse`? [Classifying an error union](./foundations/errors-option-result.md#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](./foundations/fibers-scopes-runtimes.md#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](./foundations/errors-option-result.md#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](./concurrency/scheduling-time.md#retry-policy-checklist)
- Is it clear whether each timeout bounds one attempt or the whole retried operation? [Where the timeout sits relative to retry](./deep-dives/failure-retry-fallback-and-interruption.md#where-the-timeout-sits-relative-to-retry)
- Do public error values expose only stable tags and safe identifiers — no `cause`, driver message, SQL text, or `Redacted`? [Designing the error model](./foundations/errors-option-result.md#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](./foundations/errors-option-result.md#accumulating-errors-instead-of-failing-fast)

## Services and Layers

- Is each service named for a business capability, with domain-verb methods that return Effects and never throw? [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract)
- Do all public service methods have `R = never`, with construction dependencies captured in the Layer? [Designing a service contract](./foundations/services-context-layers.md#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](./foundations/services-context-layers.md#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](./foundations/services-context-layers.md#designing-a-service-contract)
- Are live implementations provided only at application or module edges, and fakes only at test edges? [Providing one value or building a graph](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph)
- 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](./foundations/services-context-layers.md#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](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt)
- Does every `{ local: true }` and `Layer.fresh` have a stated isolation reason? [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt)
- Does anything that needs teardown use `Layer.effect` with `Effect.acquireRelease`, not `Layer.succeed`? [Resourceful services](./foundations/services-context-layers.md#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](./foundations/services-context-layers.md#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](./foundations/services-context-layers.md#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](./deep-dives/anatomy-of-a-real-effect-application.md#what-the-composition-root-owns)

## Configuration and secrets

- 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](./foundations/configuration-secrets.md#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](./foundations/configuration-secrets.md#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](./foundations/configuration-secrets.md#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](./foundations/configuration-secrets.md#validating-more-than-syntax)
- Is live-versus-fake infrastructure selected by an explicit mode rather than by whether a token is present? [Deciding required, optional, and defaulted](./foundations/configuration-secrets.md#deciding-required-optional-and-defaulted)
- Is source precedence written down next to the provider composition, and is key mapping done in one place? [Precedence and composition](./foundations/configuration-secrets.md#precedence-and-composition)
- Is a custom `ConfigProvider` Layer provided *beneath* the Layers that read it, not merged beside them? [Precedence and composition](./foundations/configuration-secrets.md#precedence-and-composition)
- Does a configuration failure cause zero resource acquisitions — do pool, listener, and exporter Layers depend on the typed config service? [Install configuration before anything that depends on it](./foundations/configuration-secrets.md#install-configuration-before-anything-that-depends-on-it)
- Are secrets read with `Config.Redacted`, kept wrapped until the single call that needs the bytes, and never logged after `Redacted.value`? [Redacted](./foundations/configuration-secrets.md#redacted)
- Do schemas that decode a secret set `disallowEncode` / `disallowJsonEncode` wherever their encoded side leaves the process? [Secrets that arrive through a schema](./foundations/configuration-secrets.md#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](./foundations/configuration-secrets.md#testing-the-contract)

## Resources, scopes, and fibers

- 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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#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](./deep-dives/anatomy-of-a-real-effect-application.md#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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#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](./troubleshooting/troubleshooting-and-anti-patterns.md#scope-closed-or-resource-leaked)
- Is all cleanup attached structurally (`ensuring`, `onExit`, `acquireRelease`), so it also runs on failure and interruption? [Success-only cleanup](./troubleshooting/troubleshooting-and-anti-patterns.md#success-only-cleanup)
- Does every finalizer have a time bound and a stated policy for its own failure? [When cleanup can fail](./foundations/core-runtime-execution.md#10-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](./foundations/fibers-scopes-runtimes.md#choosing-a-fork-by-its-owner)
- Is work that must outlive its request handed to a Layer-owned, bounded supervisor rather than detached? [Bridge into a host that is not Effect](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#bridge-into-a-host-that-is-not-effect)
- 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](./foundations/fibers-scopes-runtimes.md#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](./foundations/fibers-scopes-runtimes.md#deferred)
- Does a public cancel operation say whether it requests cancellation or awaits cleanup? [Requesting cancellation versus awaiting cleanup](./foundations/fibers-scopes-runtimes.md#requesting-cancellation-versus-awaiting-cleanup)

## Concurrency, queues, and streams

- Is the execution policy written down before the code: bound, order, failure mode, and shutdown behavior? [Write the execution policy first](./deep-dives/structured-concurrency-through-a-bounded-worker.md#write-the-execution-policy-first)
- Does every traversal over external input have a numeric `concurrency`, and is a shared limit a `Semaphore` or `Pool` owned by one Layer? [Put shared limits around the actual bottleneck](./deep-dives/structured-concurrency-through-a-bounded-worker.md#put-shared-limits-around-the-actual-bottleneck)
- Does every queue, PubSub, and buffer have a capacity and an overflow strategy chosen as a policy? [Queue](./concurrency/concurrency-coordination.md#queue)
- Wherever `dropping`, `sliding`, or `offerUnsafe` is used, is the loss counted and documented? [Make loss observable](./concurrency/concurrency-coordination.md#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](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does)
- Do producers accept `Queue.Enqueue` and consumers `Queue.Dequeue`, so only wiring code sees the full queue? [Put queue roles in function signatures](./concurrency/concurrency-coordination.md#put-queue-roles-in-function-signatures)
- Do batch consumers avoid relying on `takeN` / `takeBetween` with `min > 1` on a queue that can end? [Consuming: the consumer picks its waiting policy](./concurrency/concurrency-coordination.md#consuming-the-consumer-picks-its-waiting-policy)
- Was the delivery semantics — one taker or every subscriber, late joiners, nobody listening — chosen explicitly? [Delivery semantics: Queue or PubSub](./concurrency/concurrency-coordination.md#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](./concurrency/state-mutable-references.md#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](./concurrency/streaming-channels.md#7-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](./concurrency/streaming-channels.md#6-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](./concurrency/streaming-channels.md#5-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](./concurrency/streaming-channels.md#7-where-buffering-hides)

## Schema boundaries

- Is untrusted input decoded exactly once, at ingress, with no casts (`as Model`, `as EmployeeId`) standing in for a decode? [The boundary pipeline](./deep-dives/schema-from-external-input-to-domain-and-back.md#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](./deep-dives/schema-from-external-input-to-domain-and-back.md#answer-eight-questions-before-writing-the-schema)
- Is the excess-property policy chosen per boundary and covered by a test? [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy)
- 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](./data/schema.md#1-decoding-and-encoding-pick-your-result-style)
- Does every optional field state what absent, `undefined`, and `null` mean, using the matching helper? [Optional fields, null, and Option](./data/schema-in-depth.md#6-optional-fields-null-and-option)
- Are decoding defaults (`withDecodingDefault*`) and constructor defaults (`withConstructorDefault`) used for the side they actually affect? [Default values](./data/schema.md#8-default-values)
- Do external numbers use `Schema.Finite`, `Schema.Int`, or explicit checks rather than bare `Schema.Number`? [Refinements](./data/schema.md#5-refinements-check-and-refine)
- 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](./deep-dives/schema-from-external-input-to-domain-and-back.md#treat-stored-rows-as-another-encoded-form)
- Are "malformed" and "does not match" kept as different outcomes, and are issue details kept out of user-facing text? [Keep "malformed" and "does not match" as different outcomes](./deep-dives/schema-from-external-input-to-domain-and-back.md#keep-malformed-and-does-not-match-as-different-outcomes)
- When JSON Schema or OpenAPI is published, does its excess-property setting match the runtime parser's? [JsonSchema](./data/schema-tooling.md#jsonschema)
- Does a change to a persisted or wire schema keep old encoded values decodable, or introduce a new versioned identity? [Evolve persisted and wire schemas safely](./deep-dives/schema-from-external-input-to-domain-and-back.md#evolve-persisted-and-wire-schemas-safely)
- 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](./deep-dives/schema-from-external-input-to-domain-and-back.md#assert-the-law-that-actually-holds)

## HTTP and RPC boundaries

- Does each handler only translate one decoded request into one use-case Effect — no runner, no `SqlClient`, no client construction? [Handlers are lazy adapters](./interfaces/http-api.md#handlers-are-lazy-adapters)
- Does all request work stay in the request fiber, so a disconnect or shutdown can interrupt it? [Request work stays in the request fiber](./interfaces/http-server.md#request-work-stays-in-the-request-fiber)
- 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](./interfaces/http-api.md#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](./interfaces/http-api.md#authentication-is-not-authorization)
- Are body size, multipart limits, CORS origins, redacted headers, proxy trust, and the shutdown window set explicitly? [Edge policy checklist](./interfaces/http-server.md#edge-policy-checklist)
- Is the listener allocated during Layer acquisition, bound to port `0` in tests, and proven released? [Own the listener](./interfaces/http-server.md#own-the-listener-acquire-late-bind-port-0-prove-release)
- Does every outbound call have a finite time budget, and are retries limited to replay-safe requests? [Retries, time budgets, and cancellation](./interfaces/http-client.md#retries-time-budgets-and-cancellation)
- Is the response status checked before the success schema is decoded, and are transport, status, and decode failures kept distinct? [Three failure classes](./interfaces/http-client.md#three-failure-classes)
- Is every user-supplied URL allow-listed, resolved to a public address, and re-validated on each redirect? [User-controlled destinations](./interfaces/http-client.md#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](./interfaces/rpc.md#evolving-a-contract)
- Are `RpcServer` `concurrency`, `disableFatalDefects`, `streamBufferSize`, and every `Rpc.fork` chosen deliberately? [Operational defaults](./interfaces/rpc.md#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](./interfaces/rpc.md#retried-mutations-need-a-ledger)
- Is enforcement done at the server edge, with client middleware treated as a convenience only? [Client middleware attaches; only the server edge enforces](./interfaces/rpc.md#client-middleware-attaches-only-the-server-edge-enforces)
- Do both peers of a framed link agree on serialization, and is a frame-size limit set for untrusted peers? [RpcSerialization](./interfaces/rpc.md#rpcserialization)

## SQL and persistence

- 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](./interfaces/sql.md#where-sql-belongs-in-an-application)
- Is every value interpolated through the `sql` tagged template or its helpers, never concatenated into statement text? [The star: parameterized tagged-template queries](./interfaces/sql.md#the-star-parameterized-tagged-template-queries)
- Is the whole atomic unit inside `withTransaction`, and does every failure leave the body so that recovery happens outside? [Transactions](./interfaces/sql.md#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)](./interfaces/sql.md#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](./interfaces/sql.md#normalizing-errors-at-a-repository-boundary)
- Are rows decoded through a Schema that matches the driver's actual result types? [Upgrading @effect/sql-pg to the native client](./interfaces/sql.md#native-client-behavior-codecs-json-and-listen)
- Are migrations append-only with increasing ids, compatible with the release still running, and free of long backfills at startup? [Operating migrations](./interfaces/sql.md#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](./interfaces/sql.md#pools-reservations-and-streaming)
- Is there a repository contract suite against a real database, rather than an identity `withTransaction` fake? [Verification levels](./interfaces/sql.md#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](./tooling/persistence.md#failure-windows-and-honest-guarantees)
- Is each external-write outcome classified as failed-before, known-failed, or unknown, with no blind replay of the unknown case? [Classify every outcome of an external write](./deep-dives/durability-and-distribution-ladder.md#classify-every-outcome-of-an-external-write)
- Are persisted names — workflow tags, activity names, queue and deferred names — frozen while runs are in flight? [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout)

## Caching and batching

- Was the waste shape measured first, and does the tool match it: one effect, one repeated key, or many keys at once? [Which problem do you have?](./operations/caching-batching.md#which-problem-do-you-have)
- Are cache keys normalized at ingress and carried as small value classes rather than whole records or raw strings? [Keys are logical values](./operations/caching-batching.md#keys-are-logical-values)
- Does every cache have a capacity, a TTL, and a separate, deliberately short lifetime for failures? [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy)
- Is known staleness handled with `Cache.invalidate` / `refresh` as an event rather than by shortening the TTL? [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy)
- Do cached values that own resources live in a `ScopedCache`? [ScopedCache](./operations/caching-batching.md#scopedcache)
- Does every resolver settle every entry exactly once, join rows to entries by identity, and decide what a missing row means? [Resolver obligations](./operations/caching-batching.md#resolver-obligations)
- Does the resolver deduplicate ids before calling the backend, or use `withCache` / `asCache`? [Resolver obligations](./operations/caching-batching.md#resolver-obligations)
- Is a memoized single effect (`Effect.cached`, `cachedWithTTL`) constructed once where its owner lives, not per call? [Caching a single Effect](./operations/caching-batching.md#caching-a-single-effect)
- Are cache and resolver behavior tested with counters and virtual time rather than sleeps? [Testing a cache deterministically](./operations/caching-batching.md#testing-a-cache-deterministically)

## Observability signals and export

- Does each new signal name the question or alert it serves, and is it the right kind — log, span, or metric? [Which signal answers which question](./operations/observability.md#which-signal-answers-which-question)
- Are span names operation types and metric attributes bounded vocabularies — no ids, raw URLs, SQL text, or error messages? [Cardinality: names and attribute sets are bounded](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded)
- Is every logged or attributed field allow-listed and classified, with no whole objects (config, headers, bodies, rows, prompts) passed to a logger? [Privacy: allow-list fields before they are buffered](./operations/observability.md#privacy-allow-list-fields-before-they-are-buffered)
- Are secrets logged as `Redacted`, never after `Redacted.value`? [Keeping secrets masked in log payloads](./operations/observability.md#keeping-secrets-masked-in-log-payloads)
- Is a failure logged once, where recovery or translation is decided, with stable event text and variables in fields? [Logging practice](./operations/observability.md#logging-practice)
- Does a custom `Logger.layer([...])` keep `Logger.tracerLogger` (or use `mergeWithExisting`) when logs should still appear on spans? [Installing and swapping loggers](./operations/observability.md#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](./operations/observability.md#span-and-correlation-rules)
- Are in-flight gauges decremented in a finalizer? [Gauges that follow a lifetime](./operations/observability.md#gauges-that-follow-a-lifetime)
- Is each signal exported through exactly one path, installed once at the root and provided *beneath* the application Layers? [One export path per signal](./operations/telemetry-export.md#one-export-path-per-signal)
- Does every flush have a deadline, and is the collector kept out of readiness checks? [Layer order and shutdown](./operations/telemetry-export.md#layer-order-and-shutdown)
- Is the sampling owner written down, and are SLIs computed from unsampled metrics? [Sampling has one owner per path](./operations/telemetry-export.md#sampling-has-one-owner-per-path)
- Is telemetry verified with recording Layers and privacy or cardinality tests, not only by eyeballing a dashboard? [Verifying telemetry](./operations/telemetry-export.md#verifying-telemetry)

## Tests

- 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](./deep-dives/testing-an-effect-application.md#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](./deep-dives/testing-an-effect-application.md#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](./deep-dives/testing-an-effect-application.md#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](./deep-dives/testing-an-effect-application.md#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](./deep-dives/testing-an-effect-application.md#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](./concurrency/scheduling-time.md#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](./deep-dives/testing-an-effect-application.md#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](./tooling/testing-dev-tooling.md#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](./deep-dives/testing-an-effect-application.md#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](./tooling/testing-dev-tooling.md#what-a-derived-generator-cannot-test)
- Are laziness and the exact `E` and `R` pinned where they are part of the contract? [Prove laziness and the static contract](./tooling/testing-dev-tooling.md#prove-laziness-and-the-static-contract)
- Did the CI command collect the tests this change added, and is the built artifact launched somewhere in the pipeline? [The built-artifact lane](./deep-dives/testing-an-effect-application.md#the-built-artifact-lane)

## Hosts, startup, and shutdown

- Is there exactly one runner per host: one platform `runMain` per process, or one warmed `ManagedRuntime` per foreign host? [Choosing a host](./interfaces/platform-runtime-hosts.md#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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#startup-is-a-transaction)
- Are liveness, readiness, and draining separate answers, with liveness never checking dependencies and readiness false while draining? [Liveness, readiness, and draining are different questions](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#liveness-readiness-and-draining-are-different-questions)
- 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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#one-shutdown-operation)
- Is ordering that matters expressed as a Layer dependency rather than as a convention between `Layer.mergeAll` peers? [One shutdown operation](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#one-shutdown-operation)
- Does the sum of shutdown bounds fit inside the platform's grace period, and is the code free of `process.exit()`? [Signals, exit codes, and the time budget](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#signals-exit-codes-and-the-time-budget)
- In a foreign host, is the host's `AbortSignal` forwarded to the runner, admission stopped before `dispose()`, and shutdown memoized? [A production-shaped bridge](./recipes/managed-runtime-integration.md#a-production-shaped-bridge)
- Do platform and unstable `effect/<area>` imports sit behind app-owned capabilities, imported by one module each? [Keep platform and unstable imports behind a capability](./interfaces/platform-runtime-hosts.md#keep-platform-and-unstable-imports-behind-a-capability)
- Does each cross-cutting policy — time, recurrence, configuration, capacity, execution, export, atomicity — have exactly one owning value? [One owner per policy](./deep-dives/anatomy-of-a-real-effect-application.md#one-owner-per-policy)
- Do lifetime tests assert live state before close and terminal state after, including a failed startup? [Test the lifetime, not just the behavior](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#test-the-lifetime-not-just-the-behavior)

## MCP servers

- 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](./systems/mcp.md#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](./systems/mcp.md#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](./deep-dives/exposing-an-effect-application-over-mcp.md)
- 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](./systems/mcp.md#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](./deep-dives/exposing-an-effect-application-over-mcp.md)
- 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](./systems/mcp.md#mcpserver)

## Upgrading Effect versions

- Were experimental GraphQL and networking contracts re-checked even for a patch upgrade, including generated GraphQL output? [GraphQL](./interfaces/graphql.md), [Platform & Runtime Hosts](./interfaces/platform-runtime-hosts.md)
- Are `effect` and every `@effect/*` package pinned to one exact version, with a single installed copy of `effect`? [Incompatible unstable package versions](./troubleshooting/troubleshooting-and-anti-patterns.md#incompatible-unstable-package-versions)
- 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](./index.md#stability-and-support)
- Do both peers of every binary RPC, cluster, or EventLog link move to `SchemaBinary` together, with old journals accounted for? [SchemaBinary](./concurrency/streaming-channels.md#schemabinary)
- Do all boolean CLI flags have `Flag.withDefault(false)`, `Flag.optional`, or a fallback? [Flag](./tooling/cli-framework.md#flag)
- Were `Config`, `Flag`, and `Prompt` constructors renamed to PascalCase, and `Config.mapOrFail` to `Config.mapEffect`? [Built-in constructors](./foundations/configuration-secrets.md#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](./tooling/testing-dev-tooling.md#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](./interfaces/sql.md#native-client-behavior-codecs-json-and-listen)
- Were JSON Schema consumers and snapshots checked against open-by-default output? [JsonSchema](./data/schema-tooling.md#jsonschema)
- Is the code free of `yield*` on `Option`, `Result`, fibers, refs, and deferreds? [Moving between Option, Result, and Effect](./foundations/errors-option-result.md#moving-between-option-result-and-effect)
- Were `PersistedQueue` retry options moved to `make`, and are dead-lettered items monitored? [PersistedQueue](./tooling/persistence.md#persistedqueue)
- Do Effect diagnostics run in CI so removed APIs and floating Effects fail the build? [Effect diagnostics in the editor and in CI](./foundations/getting-started.md#effect-diagnostics-in-the-editor-and-in-ci)

## Deeper checklists on other pages

These sections go further than a review question can. Use them when a section above turns up more than one "no".

| Area | Checklist |
| --- | --- |
| Application shape, composition root, policies | [Anatomy — Operational checklist](./deep-dives/anatomy-of-a-real-effect-application.md#operational-checklist) |
| Lifetimes, startup, readiness, shutdown | [Owning Lifetimes — Operational checklist](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#operational-checklist) |
| Failure, retry, fallback, interruption | [Failure — Operational checklist](./deep-dives/failure-retry-fallback-and-interruption.md#operational-checklist), [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist) |
| Bounded workers and structured concurrency | [Structured Concurrency — Operational checklist](./deep-dives/structured-concurrency-through-a-bounded-worker.md#operational-checklist) |
| Streaming ingestion | [Streaming Ingestion — Operational checklist](./deep-dives/streaming-ingestion-without-accidental-buffering.md#operational-checklist) |
| Schema boundaries | [Schema — Operational checklist](./deep-dives/schema-from-external-input-to-domain-and-back.md#operational-checklist), [Proving the boundary](./recipes/schema-httpapi-sql-boundary.md#proving-the-boundary) |
| HTTP edge limits | [Edge policy checklist](./interfaces/http-server.md#edge-policy-checklist), [What each test ring proves](./interfaces/http-api.md#what-each-test-ring-proves) |
| Durability, queues, workflows, cluster | [Durability Ladder — Operational checklist](./deep-dives/durability-and-distribution-ladder.md#operational-checklist), [Recovery testing and operations](./systems/workflows-durable-execution.md#recovery-testing-and-operations) |
| Observability before production | [Before production](./recipes/production-observability.md#before-production), [Verifying telemetry](./operations/telemetry-export.md#verifying-telemetry) |
| Tests | [Testing — Operational checklist](./deep-dives/testing-an-effect-application.md#operational-checklist), [When green means nothing](./deep-dives/testing-an-effect-application.md#when-green-means-nothing) |
| Host bridges | [How to test this seam](./recipes/managed-runtime-integration.md#how-to-test-this-seam) |
| AI capabilities | [Production rules for model calls](./systems/ai-language-models.md#production-rules-for-model-calls), [AI — Operational checklist](./deep-dives/building-a-production-ai-capability.md#operational-checklist) |
| Reactive UI state | [Performance & correctness checklist](./deep-dives/reactivity-from-atoms-to-mastery.md#performance-correctness-checklist) |
| Brownfield adoption | [How to know you are done](./deep-dives/adopting-effect-in-an-existing-codebase.md#how-to-know-you-are-done) |

# Troubleshooting

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.

For a checklist of code shapes to search generated or pasted code for, use [Generated-Code Anti-Patterns](./troubleshooting/anti-patterns.md).

## Fast symptom map

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. | [“My Effect never ran”](#my-effect-never-ran) |
| Work happened before anything was run; a "lazy" value is stale; every retry reuses the first result | `Effect.succeed(sideEffect())` or `Effect.fail(build())`: arguments are evaluated while the program is being built. | `Effect.sync` / `Effect.try` for run-time work, `Effect.suspend` when choosing the next effect must wait. | [Creating effects](./foundations/core-runtime-execution.md#1-creating-effects) |
| 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. | [Cancellable adapters](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks) |
| Work continues after the client disconnected | The host's `AbortSignal` never reached the runner, or the adapter ignores Effect's signal. Cancellation crosses two hops and either one can be dropped. | `runPromise(effect, { signal })` **and** the adapter's own `signal`; check `signal.aborted` before calling the runtime. | [The two broken versions](./recipes/request-cancellation-through-a-host.md#the-two-broken-versions) |
| An `HttpServer.serve` app keeps running after the client disconnected or the server began shutting down | Server adapters run a bare app uninterruptibly; only `HttpRouter` routes and `HttpApi` handlers opt in to interruption by default. | Wrap the app (or the part that should stop) in `Effect.interruptible`, and keep the work inside the request fiber. | [HttpEffect](./interfaces/http-server.md#httpeffect) |
| Interrupting the outer fiber does not stop inner work; `TestClock`, the logger, or the current span is missing inside it | An interior `Effect.runPromise(inner)` created a separate root fiber with an empty context, and flattened its typed failure into a rejection. | Return the Effect. If a nested runner is unavoidable, forward `signal` and carry the `Exit` across. | [Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) |
| `Effect.runSync` throws `AsyncFiberError` | The effect reached an asynchronous boundary; the types cannot rule that out. | `runPromise` / `runPromiseExit`, or make the edge asynchronous. | [Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) |
| A process exits with code `130` after it ended itself on purpose | The main fiber was interrupted without a `Runtime.InterruptExitCode` annotation, so teardown reports a signal-style interruption. | Annotate the deliberate interruption with `Runtime.InterruptExitCode` instead of calling `process.exit`. | [Runtime](./foundations/fibers-scopes-runtimes.md#runtime) |
| `yield* fiber`, `yield* ref`, or `yield* someOption` does not compile, or dies with `Not a valid effect` | Handles, `Option`, and `Result` are not Effects and cannot be yielded inside `Effect.gen`, whatever the guides say. | `Fiber.join`, `Ref.get`, `Deferred.await`, `Effect.fromOption`, `Effect.fromResult`. | [Moving between Option, Result, and Effect](./foundations/errors-option-result.md#moving-between-option-result-and-effect) |
| `Effect.if`, `Effect.unless`, `Effect.loop`, `Effect.iterate`, `Effect.zipLeft`, or `Effect.zipRight` is not exported | They do not exist in Effect 4, though generated code still emits them. | Ordinary `if` / `for` inside `Effect.gen`; `Effect.when(conditionEffect)`; `Effect.andThen` / `Effect.tap`. | [Branching and looping](./foundations/core-runtime-execution.md#9-branching-and-looping) |
| A forked listener misses the first event | Forking only *schedules* the child; the parent published before the child subscribed. | `{ startImmediately: true }`, or a handshake the child completes after registering. | [When a forked fiber starts](./foundations/fibers-scopes-runtimes.md#when-a-forked-fiber-starts) |
| A cancel call blocks the request for seconds | `Fiber.interrupt` completes only after the target's finalizers have run. | Decide between *request cancellation* and *await cleanup*; bound the finalizer. | [Requesting cancellation versus awaiting cleanup](./foundations/fibers-scopes-runtimes.md#requesting-cancellation-versus-awaiting-cleanup) |
| A helper receives a number where it expected an optional argument | A function was passed by name: `Effect.forEach(ids, loadBand)` calls `loadBand(id, index)`. | Write the lambda: `(id) => loadBand(id)`. | [Generated-code anti-pattern index](./troubleshooting/anti-patterns.md) |

### Symptoms: errors and recovery

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| `catch` does not handle a crash | The failure is a defect or interruption, not a typed `E`. | Inspect `Cause`; fix defects rather than silently widening recovery. | [Typed failure versus defect and interruption](#typed-failure-versus-defect-and-interruption) |
| `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. | [Recovering from a mixed Cause](./foundations/fibers-scopes-runtimes.md#recovering-from-a-mixed-cause) |
| `catchTag("B")` never fires although `B` failed | Only the first `Fail` reason is inspected, so `[Fail(A), Fail(B)]` never matches `B`. | Accumulate as data with `Effect.validate` / `Effect.partition` instead of several `Fail` reasons. | [Recovery and mixed causes](./foundations/errors-option-result.md#recovery-and-mixed-causes) |
| `catchTag("SchemaError")` never fires | A synchronous decoder was wrapped in `Effect.sync`, so bad input is a defect. | `Schema.decodeUnknownEffect(S)(input)`. | [Decoding and encoding — pick your result style](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) |
| `Effect.ignore` did not swallow a crash | It discards typed failures only. | Fix the defect; reserve `Effect.ignoreCause` for best-effort cleanup. | [Fallback values and ignoring failures](./foundations/errors-option-result.md#fallback-values-and-ignoring-failures) |
| A new error variant shipped with no handling | A `switch` with `default`, or `Match.orElse`, assigned it to the old fallback. | `Match.exhaustive` / `Match.tagsExhaustive`. | [Classifying an error union](./foundations/errors-option-result.md#classifying-an-error-union) |
| Retries and alerts fire on a correct "no" | A negative answer every caller treats as ordinary output was modeled in `E`. | Return it in `A` as a tagged value, `Option`, or `Result`. | [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model) |
| A timeout or permission error is reported as "not found" or `404` | An infrastructure fault was collapsed into absence. | Only a query that succeeded and returned nothing is "not found". | [Status mapping is part of the contract](./interfaces/http-api.md#status-mapping-is-part-of-the-contract) |
| A client can read a wrapped driver message | A public error declares `cause: Schema.Defect()`, and every declared field is serialized. | Keep diagnostic causes on internal errors; publish stable tags and safe identifiers. | [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model) |
| The main task failed but the program keeps waiting | A heartbeat was combined with `Effect.race`, which waits for the first *success*. | `Effect.raceFirst`, with the side task made infallible. | [Running a side task for as long as the main task runs](./concurrency/scheduling-time.md#running-a-side-task-for-as-long-as-the-main-task-runs) |

### Symptoms: services, Layers, and configuration

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| A service remains in `R` | Its Layer was not provided, or it was hidden under the wrong Layer composition. | Trace the missing service tag and provide its live/test Layer at the composition root. | [A service is still present in R](#a-service-is-still-present-in-r) |
| A sibling Layer cannot see a provider | `Layer.merge` does not feed siblings, or a plain `Layer.provide` consumed the output. | `Layer.provide` for a private dependency, `Layer.provideMerge` when it must stay visible. | [Reading and composing the graph](./foundations/services-context-layers.md#reading-and-composing-the-graph) |
| A pool is opened once per call although "layers are memoized"; two pools exist | Sibling `Effect.provide(PoolLive)` calls each build their own; so do re-created Layer expressions, `{ local: true }`, and `Layer.fresh`. | Provide the graph once at the edge (or one `ManagedRuntime`) and reuse one named Layer value. | [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt) |
| A test reached a live system | A live `Effect.provide` is buried in reusable code, or the fake was declared but never provided. | Remove the deep `provide`; assert on something only the fake can produce. | [Test layers and substitution](./foundations/services-context-layers.md#test-layers-and-substitution) |
| A test `ConfigProvider`, `Clock`, or logger override is silently ignored | Default services are references that never appear in `R`, and a Layer merged *beside* its consumer does not reach it. | Provide the override beneath the consumer, or outermost at the edge. | [Default services](./foundations/services-context-layers.md#default-services) |
| Setting `X=0` or `X=false` is ignored | A falsy fallback with the logical-or operator outside `Config`. | `Config.withDefault`, which falls back on absence only. | [Absence is not malformed input](./foundations/configuration-secrets.md#absence-is-not-malformed-input) |
| `PORT=eighty` silently became the default | `Config.orElse` rescues **any** `ConfigError`, including a malformed value. | `Config.withDefault`; keep `Config.orElse` for a renamed key. | [Absence is not malformed input](./foundations/configuration-secrets.md#absence-is-not-malformed-input) |
| A pool opened before the configuration error was reported | Resources are acquired before the whole startup contract has decoded. | One `Config` program, decoded in a Layer that resource Layers depend on. | [Designing the startup contract](./foundations/configuration-secrets.md#designing-the-startup-contract) |
| A secret appears in a response, queue message, or stored row | `Schema.RedactedFromValue` encodes back to plaintext unless `{ disallowEncode: true }`. | Set the option on every schema whose encoded side leaves the process. | [Secrets that arrive through a schema](./foundations/configuration-secrets.md#secrets-that-arrive-through-a-schema) |
| Every call through a `ManagedRuntime` fails after one bad start | The Layer build runs once and a failed build is replayed to every later call. | Warm the runtime at boot and treat the failure as fatal. | [Bridge into a host that is not Effect](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#bridge-into-a-host-that-is-not-effect) |
| An inferred Layer type is unreadable | One monolithic inline graph. | Name feature Layers and close them only at the composition root. | [Reading and composing the graph](./foundations/services-context-layers.md#reading-and-composing-the-graph) |
| Missing `FileSystem`, `HttpClient`, `Path`, or server service | A capability was imported without a platform implementation Layer. | Provide the Node/Bun/Deno/browser/fetch implementation at the outer edge. | [Missing platform Layer](#missing-platform-layer) |
| Structurally incompatible unstable types | `effect` and `@effect/*` packages are from different releases. | Pin every Effect package to the exact same version and inspect the installed graph. | [Incompatible unstable package versions](#incompatible-unstable-package-versions) |

### Symptoms: resources, fibers, and coordination

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| “Scope closed” or a handle stops working | A scoped value escaped its owning scope. | Move its use inside `Effect.scoped`, or expose it through a scoped Layer/ManagedRuntime. | [Scope closed or resource leaked](#scope-closed-or-resource-leaked) |
| Cleanup ran on success only | Cleanup was attached with `tap` / `andThen`, or written after `yield*`. | `Effect.ensuring`, `Effect.acquireRelease`, or `Effect.onExit`. | [Success-only cleanup](#success-only-cleanup) |
| One handle leaks when acquisition fails halfway | A single `acquireRelease` opened two handles; the release is registered only after the whole acquire succeeds. | One bracket per resource. | [One bracket per resource](./deep-dives/anatomy-of-a-real-effect-application.md#one-bracket-per-resource) |
| Process never exits | A live server/stream/fiber is intentionally running, or a child is waiting on Queue/Deferred/Latch. | Decide the termination protocol; bound, end, interrupt, or supervise it. | [Fiber, Queue, Deferred, Latch, and TestClock hangs](#fiber-queue-deferred-latch-and-testclock-hangs) |
| A background failure was never reported | A detached or unobserved fiber died and nobody joined it. | Own it (`forkScoped`, `FiberSet`) and observe its `Exit`. | [Choosing a fork by its owner](./foundations/fibers-scopes-runtimes.md#choosing-a-fork-by-its-owner) |
| A counter or status loses updates under concurrency | `Ref.get` followed by `Ref.set`, with a suspension between them. | One `Ref.update` / `Ref.modify` transition. | [One transition, one call](./concurrency/state-mutable-references.md#one-transition-one-call) |
| Two reads of related `TxRef`s report a total that never existed | Each `TxRef.get` ran in its own transaction. | Read both inside one `Effect.tx`. | [Failure rolls back; snapshots need one transaction](./concurrency/software-transactional-memory.md#failure-rolls-back-snapshots-need-one-transaction) |
| Accepted jobs vanish at shutdown | `Queue.shutdown` was used as end-of-input; it discards the buffer. | `Queue.end`, then join the workers. | [Queue lifecycle](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does) |
| A batch consumer waits while the queue is open, or gets a short final batch | `Queue.takeN` / `takeBetween` waits for `min` on an open queue, but a closing queue drains a smaller remainder before its terminal error. | Use `takeBetween(q, 1, max)` or `takeAll` to consume whatever is ready; check batch length even with `takeN`. | [Consuming: the consumer picks its waiting policy](./concurrency/concurrency-coordination.md#consuming-the-consumer-picks-its-waiting-policy) |
| Consumers hang after the producer died | The producer's failure never reached the queue. | `Queue.fail`, `Queue.end`, or wrap the producer with `Queue.into(q)`. | [Queue lifecycle](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does) |
| Events vanish under load with no error | A dropping or sliding buffer, or an unchecked `offerUnsafe` / `publish` result from a synchronous callback. | Choose the loss policy explicitly and count the `false` results. | [Make loss observable](./concurrency/concurrency-coordination.md#make-loss-observable) |
| Only one observer saw an event, or every worker did the same job | `Queue` and `PubSub` delivery semantics were swapped. | One taker per value → `Queue`; a copy per subscriber → `PubSub`. | [Delivery semantics: Queue or PubSub](./concurrency/concurrency-coordination.md#delivery-semantics-queue-or-pubsub) |
| A restarted component reports "ready" instantly | A completed `Deferred` was reused for the next lifecycle generation. | A fresh `Deferred` per generation; fail the retired one. | [Deferred](./foundations/fibers-scopes-runtimes.md#deferred) |
| Results arrive in the wrong order | Completion order was mistaken for input or commit order. | Name which order the contract promises. | [Five kinds of order](./deep-dives/structured-concurrency-through-a-bounded-worker.md#five-kinds-of-order) |
| Requests are cut off at shutdown, or shutdown stalls | `ManagedRuntime.dispose()` is not a drain; or waits are cyclic and unbounded. | Stop intake, drain with a bound, interrupt survivors, then release. | [One shutdown operation](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#one-shutdown-operation) |
| A pool churns connections whenever queries fail | `Pool.invalidate` on every failure. | Invalidate only an item you believe is broken. | [TTL is not a health check](./concurrency/concurrency-coordination.md#ttl-is-not-a-health-check) |

### Symptoms: streams and buffers

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| Heap grows behind a callback stream | `Stream.callback` and `Stream.fromEventListener` buffer without bound by default. | Pass `{ bufferSize, strategy }`. | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| Memory grows somewhere in a pipeline | An unbounded queue, a lagging subscriber, `runCollect`, or `concurrency: "unbounded"`. | Inventory every stage and bound it. | [Unbounded by default](#unbounded-by-default) |
| A preview of a large source reads everything | `runCollect` then `slice`, or `take` placed *after* a `buffer`, which runs ahead of demand. | `Stream.take(n)` before buffers and before the runner. | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| A merged stream never ends | `Stream.merge` defaults to `haltStrategy: "both"`, so an infinite ticker keeps it alive. | Pass `"left"`, `"right"`, or `"either"`. | [Combining and splitting streams](./concurrency/streaming-channels.md#4-combining-and-splitting-streams) |
| A stream "finished" when the source merely went quiet | `Stream.timeout` ends the stream with no error; it is an idle timeout per pull. | `Stream.timeoutOrElse` with `Stream.fail(...)`. | [Handling stream failures](./concurrency/streaming-channels.md#5-handling-stream-failures) |
| A retry repeated writes | `Stream.retry` re-runs the entire upstream region. | Place `retry` directly after the source; recover per element inside `mapEffect`. | [Handling stream failures](./concurrency/streaming-channels.md#5-handling-stream-failures) |
| A handle closes before the first row is read | `Stream.scoped` wrapped only the one-element acquisition stream. | `Stream.unwrap` over the scoped acquisition. | [Owning resources inside a stream](./concurrency/streaming-channels.md#6-owning-resources-inside-a-stream) |
| The sink receives batches of unpredictable size | Buffer capacity is not batch size; chunks after `mapEffect` have one element. | `Stream.grouped(n)` or `Stream.rechunk(n)` directly before the consumer. | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| The last partial batch of a live feed never flushes | `Stream.grouped(n)` waits for `n` elements or the end. | `Stream.groupedWithin(n, duration)`. | [Batch by size or time when the source is live](./deep-dives/streaming-ingestion-without-accidental-buffering.md#batch-by-size-or-time-when-the-source-is-live) |

### Symptoms: time, retry, and caching

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| TestClock test hangs | The sleeping Effect was joined before virtual time advanced. | Fork work, adjust the TestClock, then join. | [Fiber, Queue, Deferred, Latch, and TestClock hangs](#fiber-queue-deferred-latch-and-testclock-hangs) |
| A clock test passes only with `Effect.yieldNow` sprinkled in, then flakes | Turn counting: the fiber registered its `sleep` after the adjustment. | A handshake per sleep boundary. | [Synchronize on phases, not on turns](./deep-dives/testing-an-effect-application.md#synchronize-on-phases-not-on-turns) |
| Dates read 1970 in tests | Virtual time starts at `0`. | `TestClock.setTime` whenever a calendar rule is under test. | [TestClock](./tooling/testing-dev-tooling.md#testclock) |
| Retry never happens | The error was converted to a defect, caught earlier, or rejected by the Schedule. | Keep retryable failures typed until after a bounded, filtered retry. | [Retrying the wrong error channel](#retrying-the-wrong-error-channel) |
| Retry hammers a dependency with no delay | The options form `{ while }` without `schedule` means zero delay and no bound. | Pair every predicate with `schedule`, `times`, or both. | [Shorthand options for retry and repeat](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat) |
| Every retry returns the same settled result | The Promise was created outside the retried Effect. | Create it inside `Effect.tryPromise`. | [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist) |
| A retry storm after an outage | Wrong classification, or synchronized callers. | Classify, cap, back off, and add `Schedule.jittered`. | [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist) |
| "Identical" cache keys keep missing | Keys compare structurally, so the difference is in the input: `"L4"`, `"l4"`, and `" L4 "` are three keys. | Normalize at ingress; carry the key as a small value class. | [Keys are logical values](./operations/caching-batching.md#keys-are-logical-values) |
| The cache keeps returning an error after the dependency recovered | With `Cache.make`, a failed `Exit` lives for the full success TTL. | `Cache.makeWith` with a short failure TTL; `Cache.invalidate` on the retry path. | [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy) |
| A request dies with `RequestResolver did not complete request` | The resolver skipped an entry, usually for a missing row. | Iterate the *entries* and settle each one. | [Resolver obligations](./operations/caching-batching.md#resolver-obligations) |
| Batched callers receive each other's data | Rows were paired to entries by position. | Index rows by id, then iterate the entries. | [Resolver obligations](./operations/caching-batching.md#resolver-obligations) |
| Duplicate ids reach the backend in one batch | Base batching collects entries; it does not collapse equal requests. | Deduplicate in the resolver, or add `RequestResolver.withCache`. | [Resolver obligations](./operations/caching-batching.md#resolver-obligations) |

### Symptoms: Schema and boundaries

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| Schema types seem reversed | Application `Type` and external `Encoded` were used at the wrong boundary. | Decode inbound `Encoded` to `Type`; encode `Type` before storage/wire output. | [Schema Type and Encoded mismatch](#schema-type-and-encoded-mismatch) |
| Extra or misspelled keys are silently accepted | The default `onExcessProperty: "ignore"` strips undeclared keys. | Choose the policy per boundary and test it. | [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy) |
| `{ key: undefined }` fails to decode | `Schema.optionalKey` rejects an explicit `undefined`; only `Schema.optional` accepts it. | Pick the field helper from the five input states; enable `exactOptionalPropertyTypes`. | [Optional fields, null, and Option](./data/schema-in-depth.md#6-optional-fields-null-and-option) |
| An omitted key decodes as absent despite a default | `withConstructorDefault` applies to `make` / `new` only. | `withDecodingDefault` / `withDecodingDefaultKey`. | [Default values](./data/schema.md#8-default-values) |
| Raw JSON fails with `Expected Option` | `Schema.Option(S)` is not a wire codec. | The `OptionFrom*` family. | [Optional fields, null, and Option](./data/schema-in-depth.md#6-optional-fields-null-and-option) |
| `decodeUnknownSync` throws a plain `Error` wrapping `AsyncFiberError` | The schema does asynchronous work. | An Effect runner (`decodeUnknownEffect`). | [Decoding and encoding — pick your result style](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) |
| "Malformed JSON" and "wrong shape" produce the same response | The two outcomes were folded together. | Keep them distinct to the boundary. | [Keep "malformed" and "does not match" as different outcomes](./deep-dives/schema-from-external-input-to-domain-and-back.md#keep-malformed-and-does-not-match-as-different-outcomes) |
| A round-trip property fails for a valid codec | The asserted law is the wrong one. | Assert the law that holds for that codec. | [Assert the law that actually holds](./deep-dives/schema-from-external-input-to-domain-and-back.md#assert-the-law-that-actually-holds) |

### Symptoms: HTTP, RPC, and SQL

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| A GraphQL call has both data and errors | GraphQL partial results are not an ordinary HTTP success/failure split. | Choose the client's error mode explicitly before consuming partial data. | [GraphQL](./interfaces/graphql.md) |
| A compressed upload gets `415` or its body fails to parse | Decompression rejects unsupported codings with `415`; malformed or oversized decoded bodies fail the read (`RequestParseError`, normally `400`). | Use gzip/deflate and set the decompressed body budget deliberately; do not assume a `413` response. | [Decompressing incoming bodies](./interfaces/http-server.md#decompressing-incoming-bodies) |
| A peer's `404` is reported as a schema failure | The success schema decoded the error body because the status was never checked. | `filterStatusOk` or `matchStatus` before decoding. | [Three failure classes](./interfaces/http-client.md#three-failure-classes) |
| A retried `POST` was applied twice | `retryTransient` does not look at the method. | Retry only replay-safe requests; use a server-honored idempotency key. | [Retries, time budgets, and cancellation](./interfaces/http-client.md#retries-time-budgets-and-cancellation) |
| A large upload exhausts memory | Collected request bodies and multipart parts have **no limit** by default. | `HttpIncomingMessage.MaxBodySize`, `Multipart.MaxParts`, `Multipart.MaxFileSize`. | [Edge policy checklist](./interfaces/http-server.md#edge-policy-checklist) |
| Clients receive a `400` the OpenAPI document never mentions | The implicit decode failure is not in the contract until declared. | Add `HttpApiError.BadRequestNoContent` to the endpoint's errors. | [Status mapping is part of the contract](./interfaces/http-api.md#status-mapping-is-part-of-the-contract) |
| Every in-flight RPC call on a connection fails at once | A handler defect is sent as a connection-level `Defect` by default. | Fix the defect; `disableFatalDefects: true` confines it to the failing request. | [Operational defaults](./interfaces/rpc.md#operational-defaults) |
| `concurrency: 1` on `RpcServer`, yet handlers overlap | `Rpc.fork` skips the server-wide semaphore. | Audit every `Rpc.fork`. | [Operational defaults](./interfaces/rpc.md#operational-defaults) |
| A procedure silently changed after merging groups | A duplicate tag replaces the earlier definition. | Prefix groups, or assert tag uniqueness in a test. | [Evolving a contract](./interfaces/rpc.md#evolving-a-contract) |
| Old clients fail with defects right after a deploy | A required payload field, tighter check, or new error member reached a peer that cannot decode it. | Evolve additively; add a new procedure for incompatible changes. | [Evolving a contract](./interfaces/rpc.md#evolving-a-contract) |
| A retried RPC mutation ran twice | `RpcClientError` means the outcome is unknown. | One idempotency key per intent, recorded with the mutation. | [Retried mutations need a ledger](./interfaces/rpc.md#retried-mutations-need-a-ledger) |
| Rows are left behind after a failed multi-write | The failure was caught **inside** `withTransaction` (the body then succeeds and commits), or the first write ran before it. | Put the whole unit inside; recover outside. | [Transactions](./interfaces/sql.md#transactions) |
| A query fails with `SqlError` "the transaction has already ended" | It ran from a fiber forked inside a transaction that has since committed or rolled back. | Join or scope forked work inside the transaction, or start a new transaction for work that outlives it. | [Transactions](./interfaces/sql.md#transactions) |
| A duplicate email or webhook after a retry or rollback | An external effect ran inside a transactional or retried body. | Write an intent row in the transaction; deliver after commit with the event id as idempotency key. | [External effects after commit (outbox)](./interfaces/sql.md#external-effects-after-commit-outbox) |
| An edited migration never ran | The migrator compares only the latest recorded id. | Append-only migrations with higher ids. | [Operating migrations](./interfaces/sql.md#operating-migrations) |
| Overload turns into a restart loop | The readiness probe queues behind a saturated pool. | A short probe deadline with its own headroom; liveness independent of the database. | [Pools, reservations, and streaming](./interfaces/sql.md#pools-reservations-and-streaming) |

### Symptoms: observability

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| An "active" gauge never returns to zero | The decrement runs on the success path only, or misses interruption. | Decrement in `Effect.ensuring`. | [Gauges that follow a lifetime](./operations/observability.md#gauges-that-follow-a-lifetime) |
| Metric series and backend cost explode | Ids, URLs, or error text used as metric attributes. | Bounded vocabularies; detail goes in logs and span attributes. | [Cardinality: names and attribute sets are bounded](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded) |
| Logs stopped appearing as span events after a logger change | `Logger.layer([...])` replaces the whole default set, including `Logger.tracerLogger`. | List `Logger.tracerLogger` again, or pass `{ mergeWithExisting: true }`. | [Installing and swapping loggers](./operations/observability.md#installing-and-swapping-loggers) |
| Logs from startup fibers and finalizers bypass the installed logger | `Layer.merge(App, ObservabilityLayer)` builds the two side by side. | `App.pipe(Layer.provide(ObservabilityLayer))`. | [Layer order and shutdown](./operations/telemetry-export.md#layer-order-and-shutdown) |
| Logs and metrics are reported twice, or one trace path is silent | Two export paths installed for the same signal. | Exactly one export path per signal. | [One export path per signal](./operations/telemetry-export.md#one-export-path-per-signal) |
| The process hangs on exit with a dead collector | A hand-rolled exporter flushes without a deadline. | `shutdownTimeout` on the OTLP layers; `Effect.timeoutOption` around any manual flush. | [Layer order and shutdown](./operations/telemetry-export.md#layer-order-and-shutdown) |
| A secret appears in logs | It was logged after `Redacted.value`. | Log the `Redacted`; allow-list fields before they are buffered. | [Keeping secrets masked in log payloads](./operations/observability.md#keeping-secrets-masked-in-log-payloads) |
| A trace breaks at a queue, worker, or message bus | Fiber context does not cross serialized boundaries. | Carry a trace header and rebuild the parent with `Tracer.externalSpan`. | [Span and correlation rules](./operations/observability.md#span-and-correlation-rules) |

### Symptoms: durable systems and AI

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| An MCP endpoint on Workers complains about work outside the request | A long-lived MCP server owns fibers beyond the host request. | Use `layerHttpRequestScoped` with a sessionless protocol; do not advertise subscriptions. | [McpServer](./systems/mcp.md#mcpserver) |
| An activity executed again after a refactor | The `Activity` `name` is the journal key; renaming it orphans the recorded `Exit`. | Freeze persisted names; introduce a `V2` identity for incompatible changes. | [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout) |
| Workflow finalizers or compensation did not run when a runner shut down | The interrupt was classified as an abandoned attempt; the next owner replays. | Expected: keep activities idempotent. | [Abandoned run attempts](./systems/workflows-durable-execution.md#abandoned-run-attempts) |
| The same persisted job ran on two workers | A lock is a lease: a stalled worker loses its claim while still running. | Make the sink reject stale owners; derive the idempotency key from the item id. | [Failure windows and honest guarantees](./tooling/persistence.md#failure-windows-and-honest-guarantees) |
| `MailboxFull` during a cold start | Per-runner resident-entity or mailbox limits engaged. | Size the limits from memory and alert on the gauges. | [Capacity limits and their defaults](./systems/cluster-sharding.md#capacity-limits-and-their-defaults) |
| One model turn floods a rate-limited dependency | Tool-call resolution runs with `concurrency: "unbounded"` by default. | Set a number. | [Tool-call resolution](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch) |
| A mutating tool ran before approval | The framework resolves tool calls during the generation call. | `disableToolCallResolution: true`, then dispatch through your own gates. | [Keep the framework from executing a mutation before your gates run](./deep-dives/building-a-production-ai-capability.md#keep-the-framework-from-executing-a-mutation-before-your-gates-run) |
| 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](./systems/mcp.md#mcpserver) |
| An MCP client receives JSON-RPC error `-32021` with `requiredCapabilities` | The tool needs a client capability the request did not declare (elicitation, sampling with tools, roots). | Declare the capability on the client, or gate the tool with `McpSchema.EnabledWhen` so clients that lack it never see it. | [McpServer](./systems/mcp.md#mcpserver), [Exposing an Effect Application over MCP](./deep-dives/exposing-an-effect-application-over-mcp.md) |
| A resumed `tools/call` on the stateless protocol fails with `InvalidParams` | The handler rejected the echoed `requestState`: tampered, expired, or minted for another caller. | Seal the state with an HMAC, bind it to the principal, give it a TTL, and treat a rejection as the client error it is. | [Exposing an Effect Application over MCP](./deep-dives/exposing-an-effect-application-over-mcp.md) |
| `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. | [Exposing an Effect Application over MCP](./deep-dives/exposing-an-effect-application-over-mcp.md) |
| Model retries loop or re-bill the prompt | Non-retryable reasons are retried, or retries continue after output exists. | Branch on `error.isRetryable`; bound the schedule. | [Classifying a failure before retrying](./systems/ai-language-models.md#classifying-a-failure-before-retrying) |

### Symptoms: tests

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| A test is green but never ran | An Effect was returned from plain `it(...)`. | `it.effect`; enable the `floatingEffectInVitest` diagnostic. | [When green means nothing](./deep-dives/testing-an-effect-application.md#when-green-means-nothing) |
| A property test ends `Exhausted` | An opaque `filter` rejects too many generated candidates. | Constructive Schema checks (`isBetween`, `isPattern`) instead of rejection filters. | [Shrinking, composition, and wire-side samples](./tooling/testing-dev-tooling.md#shrinking-composition-and-wire-side-samples) |
| A `FileSystem.layerNoop` test fails with `NotFound` or dies with `not implemented` | A method the code calls was not overridden. | Supply that method. | [Testing without a disk](./interfaces/platform-runtime-hosts.md#testing-without-a-disk) |
| `catchTag("InvalidValue")` on `Command.run` never fires | Parse failures arrive wrapped in one `ShowHelp`. | Inspect `ShowHelp.errors`. | [CliError](./tooling/cli-framework.md#clierror) |
| A test flakes | Real sleeps, polling, shared Layer state, or fixed ports. | Follow the flake protocol before adding a retry. | [When a test flakes](./deep-dives/testing-an-effect-application.md#when-a-test-flakes) |

### Symptoms: after an upgrade

| Symptom | Likely cause | First correction | Details |
| --- | --- | --- | --- |
| 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. | [SchemaBinary](./concurrency/streaming-channels.md#schemabinary), [RpcSerialization](./interfaces/rpc.md#rpcserialization) |
| A CLI fails with `MissingOption` for a boolean flag nobody passed | An omitted boolean flag is no longer an implicit `false`. | `Flag.withDefault(false)`, `Flag.optional`, or a fallback. | [Flag](./tooling/cli-framework.md#flag) |
| `Config.string is not a function`; `Flag.integer` is missing | Constructors are PascalCase. | `Config.String`, `Config.Redacted`, `Flag.Int`, `Prompt.String`, and so on. | [Built-in constructors](./foundations/configuration-secrets.md#built-in-constructors), [Flag constructors at a glance](./tooling/cli-framework.md#flag-constructors-at-a-glance) |
| `Schema.toArbitrary` or `effect/testing/FastCheck` is missing; saved seeds no longer reproduce; tests report `Exhausted` | The fast-check bridge was replaced by the native `Arbitrary` engine. | `Arbitrary.schema(S)`, `{ arbitrary: { runs } }`; re-record saved failures. | [Arbitrary](./tooling/testing-dev-tooling.md#arbitrary) |
| `Stream.partition` branches are swapped, or `bufferSize` is rejected | It returns `[passes, fails]` and the option is `capacity`. Swapped names still type-check. | Reorder the destructuring; rename the option. | [Combining and splitting streams](./concurrency/streaming-channels.md#4-combining-and-splitting-streams) |
| `Stream.mapBoth` rejects `onSuccess`/`onFailure`; `Stream.scan` rejects a plain seed | Stream signatures mirror Effect's. | `{ onElement, onError }`; `Stream.scan(() => seed, f)`. | [Transforming streams](./concurrency/streaming-channels.md#2-transforming-streams) |
| `"1.5 KiB"` is not assignable to `ByteSize.Input` | `ByteSize.Input` literals must be a whole number and a unit. | Parse text with `ByteSize.fromString`. | [ByteSize](./data/functional-toolkit.md#bytesize) |
| YAML that used to load now throws `SyntaxError` | The parser rejects unquoted plain scalars containing `: ` or ending in `:`, compact nested sequences, and multi-document input. | Quote the value. | [Yaml](./concurrency/streaming-channels.md#yaml) |
| `getter.compose`, `new SchemaGetter.Getter`, `SchemaGetter.onSome`, or `SchemaTransformation.make` is missing | Getters and transformations are plain data with standalone combinators. | `SchemaGetter.compose` / `map` / `run`, `transformOptionalEffect`, `SchemaTransformation.composeTransformation`, `makeTransformation`. | [SchemaGetter](./data/schema-tooling.md#schemagetter), [SchemaTransformation](./data/schema-tooling.md#schematransformation) |
| Saved `Arbitrary` replay tokens no longer reproduce | Replay tokens encode the generator's shrinking and replay paths, which may change between releases while `Arbitrary` is unstable. | Re-run the property, re-record the token, and keep important failing inputs as regression tests. | [Arbitrary](./tooling/testing-dev-tooling.md#arbitrary) |
| A custom `OpenRouterClient.Service` mock no longer type-checks | The service interface includes `createDecisions`. | Implement it in the mock. | [Provider packages](./systems/ai-language-models.md#provider-packages) |
| `HttpServerResponse.file` rejects `contentLength` | The option does not exist; lengths come from the file and the requested range. | Delete the option. | [HttpPlatform](./interfaces/http-server.md#httpplatform) |
| Generated JSON Schema now says `"additionalProperties": true` | JSON Schema generation is open by default. | `{ onExcessProperty: "error" }`; refresh snapshots. | [JsonSchema](./data/schema-tooling.md#jsonschema) |
| 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`. | [SQL](./interfaces/sql.md) |
| `onExcessProperty: "preserve"` or `propertyOrder` is rejected | Both parse options were removed. | Model unknown keys with `Schema.Record` / `Schema.StructWithRest`. | [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy) |
| Logs vanished from traces after installing a custom logger | `Logger.layer` replaces the whole logger set, `tracerLogger` included. | `Logger.layer([Logger.consoleJson, Logger.tracerLogger])`. | [Installing and swapping loggers](./operations/observability.md#installing-and-swapping-loggers) |
| 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. | [Stability and support](./index.md#stability-and-support), [Migration guide](https://github.com/Effect-TS/effect/blob/effect%404.0.5/MIGRATION.md) |

## “My Effect never ran”

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

```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](./foundations/core-runtime-execution.md#11-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](./tooling/testing-dev-tooling.md#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](./foundations/core-runtime-execution.md#9-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](https://effect.website/docs/v4/getting-started/running-effects) (it names the `runFork` result `RuntimeFiber`; it is `Fiber<A, E>`).

## A service is still present in R

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

```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](./foundations/services-context-layers.md#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](./foundations/services-context-layers.md#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.

## Typed failure versus defect and interruption

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

```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](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks)).

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 `Fail` *and* 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](./foundations/fibers-scopes-runtimes.md#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.**

```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
  )
)
```

Official guide: [Unexpected Errors](https://effect.website/docs/v4/error-management/unexpected-errors).

## Scope closed or resource leaked

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

```ts
const query = Effect.scoped(
  Effect.gen(function*() {
    const connection = yield* Pool.get(pool)
    return yield* connection.execute("select 1")
  })
)
```

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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#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](./deep-dives/anatomy-of-a-real-effect-application.md#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](./concurrency/streaming-channels.md#6-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](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail)).

Official guide: [Scope](https://effect.website/docs/v4/resource-management/scope).

## Success-only cleanup

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` | [Deferred](./foundations/fibers-scopes-runtimes.md#deferred) |
| An "in-flight" gauge decremented after the work | The gauge stays high after a failure or timeout | Decrement in `Effect.ensuring` | [Gauges that follow a lifetime](./operations/observability.md#gauges-that-follow-a-lifetime) |
| A subscription or file closed when the consumer finishes | It leaks on early stop, failure, or interruption | A scoped acquisition; `Stream.unwrap` for streams | [Proving a subscription did not leak](./concurrency/concurrency-coordination.md#proving-a-subscription-did-not-leak) |
| A resolver entry settled only when a row exists | The caller dies with `RequestResolver did not complete request` | Iterate the entries and settle every one | [Resolver obligations](./operations/caching-batching.md#resolver-obligations) |
| A span or exporter closed only on clean shutdown | Telemetry from the failing path — the interesting one — is lost | A scoped exporter Layer, provided beneath the application | [Layer order and shutdown](./operations/telemetry-export.md#layer-order-and-shutdown) |
| Partial multi-step setup left behind on failure | Earlier steps stay created | Exit-aware releases inside one `Effect.scoped` | [Roll back partial work with exit-aware finalizers](./deep-dives/failure-retry-fallback-and-interruption.md#roll-back-partial-work-with-exit-aware-finalizers) |

To prove the fix, assert the closing action under all three exits, not just success: [Test lifetimes, not just values](./deep-dives/testing-an-effect-application.md#test-lifetimes-not-just-values).

## 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](./concurrency/concurrency-coordination.md#consuming-the-consumer-picks-its-waiting-policy)).
- 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](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does)).
- `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](./foundations/fibers-scopes-runtimes.md#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](./concurrency/scheduling-time.md#running-a-side-task-for-as-long-as-the-main-task-runs)).

**Contextual fragment — virtual time must be driven from another fiber.**

```ts
const fiber = yield* Effect.sleep("10 seconds").pipe(
  Effect.as("ready"),
  Effect.forkChild
)

yield* TestClock.adjust("10 seconds")
const result = yield* Fiber.join(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](./deep-dives/testing-an-effect-application.md#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](./foundations/fibers-scopes-runtimes.md#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](https://effect.website/docs/v4/concurrency/fibers) (its prose calls `Effect.yieldNow()`; `Effect.yieldNow` is a value, and the guide does not mention the `startImmediately` fork option).

## Unbounded by default

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:

| Default | What is unbounded | Bound it with | Details |
| --- | --- | --- | --- |
| `Stream.callback`, `Stream.fromEventListener` | values pushed but not yet pulled | `{ bufferSize, strategy }` | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| `Queue.unbounded()`, `PubSub.unbounded()` | the backlog behind the slowest consumer | a bounded, dropping, or sliding constructor chosen as a policy | [Queue](./concurrency/concurrency-coordination.md#queue) |
| `SubscriptionRef.changes` | backlog of a permanently slow subscriber | a consumer that keeps up, or a bounded hand-off downstream | [SubscriptionRef](./concurrency/state-mutable-references.md#subscriptionref) |
| `{ concurrency: "unbounded" }` | in-flight effects and their results | a number, a shared `Semaphore`, or a `Pool` | [Write the execution policy first](./deep-dives/structured-concurrency-through-a-bounded-worker.md#write-the-execution-policy-first) |
| `RpcServer` `concurrency` | concurrently running handlers | a number; note that `Rpc.fork` bypasses it | [Operational defaults](./interfaces/rpc.md#operational-defaults) |
| AI tool-call resolution `concurrency` | tool handlers started by one model turn | a number on the generation call | [Tool-call resolution](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch) |
| HTTP request bodies, multipart part count and file size | bytes collected per request | `HttpIncomingMessage.MaxBodySize`, `Multipart.MaxParts`, `Multipart.MaxFileSize` | [Edge policy checklist](./interfaces/http-server.md#edge-policy-checklist) |
| `Ndjson` lines, `Stream.splitLines`, raw `SchemaBinary` frames | one incomplete line or frame from the peer | `Stream.limitBytes` upstream; `maxFrameSize` on `SchemaBinary` (the `RpcSerialization` NDJSON and SchemaBinary layers already default to 16 MiB) | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| `Stream.groupByKey` | one queue per key, keys never retired | `bufferSize`, `idleTimeToLive` | [Transforming streams](./concurrency/streaming-channels.md#2-transforming-streams) |
| `Stream.runCollect`, `Sink.collect()` | the whole stream | `Stream.take`, a fold, or a bounded `Sink` | [Running streams](./concurrency/streaming-channels.md#3-running-streams) |
| Retry options with a predicate and no `schedule` or `times` | attempts, with zero delay | `schedule`, `times`, or both | [Shorthand options for retry and repeat](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat) |

## Retrying the wrong error channel

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

```ts
const retryTransient = Schedule.exponential("200 millis").pipe(
  Schedule.setInputType<HttpError>(),
  Schedule.while(({ input }) => input.retryable),
  Schedule.upTo({ times: 5 })
)

const response = callProvider.pipe(
  Effect.retry(retryTransient),
  Effect.catchTag("HttpError", reportPermanentFailure)
)
```

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](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks)).
- **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](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat)).
- **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](./concurrency/scheduling-time.md#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](./deep-dives/failure-retry-fallback-and-interruption.md#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](./interfaces/http-client.md#retries-time-budgets-and-cancellation)), a failed RPC call has an unknown outcome ([RPC](./interfaces/rpc.md#retried-mutations-need-a-ledger)), and a model call must not be retried once output or a side effect exists ([AiError](./systems/ai-language-models.md#classifying-a-failure-before-retrying)).

Official guide: [Retrying](https://effect.website/docs/v4/error-management/retrying).

## Schema Type and Encoded mismatch

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

```ts
const EmployeeId = Schema.NumberFromString

const id: Effect.Effect<number, Schema.SchemaError> =
  Schema.decodeUnknownEffect(EmployeeId)("42")

const encoded: Effect.Effect<string, Schema.SchemaError> =
  Schema.encodeEffect(EmployeeId)(42)
```

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](./data/schema-in-depth.md#5-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](./data/schema-in-depth.md#6-optional-fields-null-and-option)).

Official guide: [Introduction to Effect Schema](https://effect.website/docs/v4/schema/introduction).

## Missing platform Layer

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](./interfaces/platform-runtime-hosts.md#choosing-a-host)). Quarantine platform imports and `@stability unstable` `effect/<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](./interfaces/platform-runtime-hosts.md#keep-platform-and-unstable-imports-behind-a-capability)).

## Incompatible unstable package versions

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](./foundations/getting-started.md#install-effect-4)).

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.

## What to capture in a bug report

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.

Then consult [Core Runtime & Execution](./foundations/core-runtime-execution.md), [Services, Context & Layers](./foundations/services-context-layers.md), [Errors, Option & Result](./foundations/errors-option-result.md), [Concurrency & Coordination](./concurrency/concurrency-coordination.md), [Schema](./data/schema.md), and [Testing & Dev Tooling](./tooling/testing-dev-tooling.md) for the full API surface. To choose between plausible primitives, use [Choosing Effect Primitives](./reference/choosing-effect-primitives.md); to review a change before it ships, use the [Review Checklists](./reference/review-checklists.md).

# Generated-Code Anti-Patterns

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](./reference/review-checklists.md).

## Effect 3 names that do not exist in Effect 4

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.

| Effect 3 name | Effect 4 |
| --- | --- |
| `Effect.catchAll` | `Effect.catch` |
| `Effect.catchAllCause` | `Effect.catchCause` |
| `Effect.catchSome` | `Effect.catchIf` or `Effect.catchTag` |
| `Effect.either` | `Effect.result` (returns a `Result`) |
| `Effect.tapErrorCause` | `Effect.tapCause` |
| `Effect.zipLeft` / `Effect.zipRight` | `Effect.tap` / `Effect.andThen` |
| `Context.Tag`, `Effect.Service` | `Context.Service` — see [Services, Context & Layers](./foundations/services-context-layers.md) |
| `Layer.scoped` | `Layer.effect` (it already handles a `Scope` requirement) |
| `Schema.decodeUnknown` / `Schema.encodeUnknown` | `Schema.decodeUnknownEffect` / `Schema.encodeUnknownEffect` (or the `Sync`, `Result`, `Exit`, `Option`, and `Promise` variants) — see [Schema](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) |
| `Schema.decode(schema)` as a decoder | `Schema.decodeEffect(schema)`; in Effect 4 `Schema.decode` builds a transformation from getters |
| `@effect/platform`, `@effect/rpc`, `@effect/sql`, `@effect/cli` | modules inside `effect`: `FileSystem` and `Path` from `"effect"`, HTTP from `"effect/http"`, and so on; host Layers from `@effect/platform-node` — see [Getting Started](./foundations/getting-started.md#install-effect-4) |
| `NodeRuntime` from `"effect"` | `NodeRuntime` from `@effect/platform-node` |

## Anti-patterns: construction and running

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| `Effect.succeed(sideEffect())`, `Effect.fail(buildError())` | The argument is evaluated while the program is built; every run and retry replays one captured value. | `Effect.sync(() => ...)`, `Effect.failSync`, or `Effect.suspend`. | [Creating effects](./foundations/core-runtime-execution.md#1-creating-effects) |
| `Effect.sync(() => JSON.parse(text))` or any throwing code in `Effect.sync` | `sync` asserts "cannot throw"; the throw becomes a defect, invisible to `catchTag` and retry. | `Effect.try({ try, catch })` with a real error mapper. | [Creating effects](./foundations/core-runtime-execution.md#1-creating-effects) |
| `Effect.promise(() => fetch(url))` | A rejection becomes a defect, and no `signal` is forwarded. | `Effect.tryPromise({ try: (signal) => fetch(url, { signal }), catch })`. | [Creating effects](./foundations/core-runtime-execution.md#1-creating-effects) |
| `Effect.tryPromise({ try: () => sdk.call(x), ... })` | No `signal` parameter is declared, so no `AbortController` exists; timeouts and races abandon the I/O instead of cancelling it. | Declare and forward `signal` in every adapter. | [Cancellable adapters](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks) |
| `catch: (cause) => new SdkError({ cause })` for every rejection | A `TypeError` inside the adapter becomes an "expected outage" and gets retried. | Recognize the failures the contract allows; `Effect.die` the rest. | [Cancellable adapters](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks) |
| `async`/`await` throughout Effect services | Native Promise work escapes typed errors, services, cancellation, and test services. | Compose Effects; wrap a real Promise boundary once with `Effect.tryPromise`. | [Sequencing with gen & fn](./foundations/core-runtime-execution.md#2-sequencing-with-gen-fn) |
| `Effect.runPromise` inside a service method or handler | Creates a root fiber with an empty context: interruption, provided services, and the typed failure are lost. | Return `Effect<A, E, R>`; run at an owned edge. | [Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) |
| `Effect.runSync(parse(x))` while building a description | Construction is no longer inert, and `runSync` throws at the first asynchronous boundary. | Compose the effect; run once at the edge. | [Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) |
| `Effect.map(() => someEffect)`; an Effect built in a callback and discarded | Produces a nested or dropped Effect that never runs. | `Effect.flatMap`, `Effect.andThen`, or `yield*`. | [“My Effect never ran”](./troubleshooting/troubleshooting-and-anti-patterns.md#my-effect-never-ran) |
| Point-free callbacks: `Effect.forEach(ids, loadBand)`, `Effect.map(f)` with an overloaded `f`, `flow(...)` | `forEach` calls `f(element, index)`, so an optional second parameter silently receives the index; overloads and generics can be erased. | Write the lambda: `(id) => loadBand(id)`. | Official guide: [Guidelines](https://effect.website/docs/v4/code-style/guidelines) |
| `Effect.if`, `Effect.unless`, `Effect.whenEffect`, `Effect.loop`, `Effect.iterate`, `Effect.zipLeft`, `Effect.zipRight` | Not exported. | Plain `if` / `for` in `Effect.gen`; `Effect.when(conditionEffect)`; `Effect.andThen` / `Effect.tap`. | [Branching and looping](./foundations/core-runtime-execution.md#9-branching-and-looping) |
| `Date.now()`, `new Date()`, `Math.random()` in domain work | Bypasses Clock/Random services and deterministic tests; direct workflow use also breaks replay determinism. | Effect Clock/DateTime/Random APIs; TestClock and seeded services. Put nondeterminism in a Workflow Activity. | [Clock](./foundations/fibers-scopes-runtimes.md#clock), [Random](./concurrency/scheduling-time.md#random) |
| `process.exit()` in application code | Skips finalizers and the drain. | Let the platform `runMain` translate the `Exit` into an exit code. | [Signals, exit codes, and the time budget](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#signals-exit-codes-and-the-time-budget) |

## Anti-patterns: errors and recovery

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| `Effect.catch(() => fallback)` everywhere | Erases domain distinctions and often hides operational failures. | Recover by tag/reason at the layer that owns the policy; preserve unexpected failures. | [Selective recovery beyond one tag](./foundations/errors-option-result.md#selective-recovery-beyond-one-tag) |
| Retrying every failure forever | Retries permanent failures and amplifies outages. | Typed retryable errors, `Schedule.while`, jitter, and hard time/attempt bounds. | [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist) |
| Retrying or defaulting a defect | Hides a bug behind a plausible value. | Let it fail; report it at a process or request boundary. | [The three failure buckets](./foundations/errors-option-result.md#the-three-failure-buckets) |
| `Effect.orDie` to tidy an error union; `Effect.die` on an expected failure | Callers lose a condition they could act on. | Keep it typed; translate with `Effect.mapError`; declare it on the endpoint. | [Recovering from a mixed Cause](./foundations/fibers-scopes-runtimes.md#recovering-from-a-mixed-cause) |
| `Effect.catchCause(() => Effect.void)`, `Effect.ignoreCause` in domain code | Swallows defects and interruption; can block shutdown. | A guarded `catchCause` that re-fails, or `catchDefect` that re-dies the unknown. | [Typed failure versus defect and interruption](./troubleshooting/troubleshooting-and-anti-patterns.md#typed-failure-versus-defect-and-interruption) |
| Translating interruption into a domain error, retrying it, or logging it as a fault | Interruption is cancellation, not failure. | Let it propagate; finalizers do the work. | [The three failure buckets](./foundations/errors-option-result.md#the-three-failure-buckets) |
| `Option.getOrThrow`, or re-throwing `result.failure`, in domain code | Reintroduces the hidden branch the type removed. | `Effect.fromOption` / `Effect.fromResult`, or collapse at a real boundary. | [Fallbacks and boundary exits](./foundations/errors-option-result.md#fallbacks-and-boundary-exits) |
| `switch` with `default`, or `Match.orElse`, in an error-policy match | Tomorrow's variant is silently assigned to today's fallback. | `Match.exhaustive` / `Match.tagsExhaustive`. | [Classifying an error union](./foundations/errors-option-result.md#classifying-an-error-union) |
| Folding (`Effect.match`) or catching everything in a low-level function | Steals policy from every caller. | Fold once, at the terminal boundary that owns the response. | [Folding both channels at a boundary](./foundations/errors-option-result.md#folding-both-channels-at-a-boundary) |
| Mapping a timeout, pool exhaustion, or driver error to `NotFound` / `404` | Clients act on a lie. | Only a query that succeeded and returned nothing is "not found". | [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model) |
| A `throw` inside a service method or a test fake | It becomes a defect; tests then exercise a different channel than production. | `Effect.fail(new DomainError(...))`. | [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract) |
| A correct negative answer modeled as an error | Retry schedules and alerts treat a right answer as a fault. | Return it in `A`. | [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model) |

## Anti-patterns: services, Layers, and configuration

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| Providing a live Layer or service inside business logic | `R` looks clean while production I/O is hard-wired; tests reach the network and each call is its own build. | Provide live implementations at application edges, fakes at test edges. | [Providing one value or building a graph](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph) |
| Per-request `Effect.provide(DbLive)`; a `ManagedRuntime`, pool, or exporter per request | Sibling provides each build the Layer: a pool per request. | One enclosing build at the edge, or one `ManagedRuntime` per host. | [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt) |
| Rebuilding Layers inline at multiple branches | Different Layer identities may acquire duplicate pools/resources. | Name and reuse one Layer value inside the composition graph. | [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt) |
| `Layer.fresh` or `{ local: true }` "to fix the types" | Duplicates pools, caches, and subscriptions. | Read the remaining requirements and wire exactly that. | [Reading and composing the graph](./foundations/services-context-layers.md#reading-and-composing-the-graph) |
| `Layer.succeed` for something that needs teardown | It packages a finished value and cannot register a finalizer. | `Layer.effect` with `Effect.acquireRelease`. | [Resourceful services](./foundations/services-context-layers.md#resourceful-services) |
| A service method typed `Effect<A, E, SomeDependency>` | Every caller and test must provide what only the implementation needs. | Capture dependencies in the Layer constructor; public methods have `R = never`. | [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract) |
| A service per helper, or one god service | Boundaries that exist only for mocking, or none at all. | One service per capability with a substitution reason. | [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract) |
| Module-level `createServer()`, `Ref`, or counter | Shared by every build of the Layer: two tests or tenants share state. | Allocate during Layer acquisition. | [Own the listener](./interfaces/http-server.md#own-the-listener-acquire-late-bind-port-0-prove-release) |
| Casting `R` away, or `as any` on a Layer | The missing service fails at run time instead. | Find the tag, provide its Layer at the right level. | [A service is still present in R](./troubleshooting/troubleshooting-and-anti-patterns.md#a-service-is-still-present-in-r) |
| `process.env` reads in services | A second, untyped definition of "valid deployment". | One `Config` program, decoded during a Layer build. | [Designing the startup contract](./foundations/configuration-secrets.md#designing-the-startup-contract) |
| `Config.orElse(() => Config.succeed(d))` as a default; a logical-or fallback | Masks a malformed value; treats `0` and `false` as absent. | `Config.withDefault(d)`. | [Absence is not malformed input](./foundations/configuration-secrets.md#absence-is-not-malformed-input) |
| Choosing live or fake infrastructure from whether a token is set | A missing secret silently selects the fake in production. | An explicit mode: `Config.Literals(["live", "sandbox"], "MODE")`. | [Deciding required, optional, and defaulted](./foundations/configuration-secrets.md#deciding-required-optional-and-defaulted) |
| `Layer.mergeAll(Service.layer, ConfigLive)` | The provider override does not reach its sibling. | `Service.layer.pipe(Layer.provide(ConfigLive))`, or provide it outermost. | [Precedence and composition](./foundations/configuration-secrets.md#precedence-and-composition) |
| Node platform imports (`@effect/platform-node`, `node:*`) in domain code or in a browser or edge bundle | The module now knows which host it runs in, and the bundle breaks elsewhere. | Depend on the capability; import the platform package in one module at the edge. | [Keep platform and unstable imports behind a capability](./interfaces/platform-runtime-hosts.md#keep-platform-and-unstable-imports-behind-a-capability) |
| `Redacted.value` early, then passing the string around | Nothing downstream can mask it again. | Keep it `Redacted` until the single call that needs the bytes. | [Redacted](./foundations/configuration-secrets.md#redacted) |

## Anti-patterns: resources, fibers, and state

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| Manual acquire/use without a finalizer | Failure or interruption leaks the handle. | `Effect.acquireRelease`, `acquireUseRelease`, a scoped Layer, Pool, ScopedCache, or another owner-aware primitive. | [Interruption & resource safety](./foundations/core-runtime-execution.md#6-interruption-resource-safety) |
| Cleanup attached with `Effect.tap` / `andThen`, or written after `yield*` | Runs on success only; misses failure and interruption. | `Effect.ensuring`, `Effect.onExit`, `Effect.acquireRelease`. | [Success-only cleanup](./troubleshooting/troubleshooting-and-anti-patterns.md#success-only-cleanup) |
| One `acquireRelease` that opens two handles | A failure on the second leaks the first. | One bracket per resource. | [One bracket per resource](./deep-dives/anatomy-of-a-real-effect-application.md#one-bracket-per-resource) |
| An unbounded or fallible finalizer | Finalizers run uninterruptibly: an unbounded finalizer is an unbounded shutdown. | Bound it, then apply a stated failure policy. | [When cleanup can fail](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail) |
| `Effect.forkDetach` without a named owner and stop path | Nothing closes, bounds, or observes the fiber. | `forkChild`, `forkScoped`, `forkIn`, or a `FiberSet` owned by a Layer. | [Choosing a fork by its owner](./foundations/fibers-scopes-runtimes.md#choosing-a-fork-by-its-owner) |
| An interior `Effect.runFork` or `forkDetach` "so the write survives the request" | Shutdown cannot interrupt it, and it keeps using a pool after release. | Transfer the work to a Layer-owned, bounded supervisor. | [Bridge into a host that is not Effect](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#bridge-into-a-host-that-is-not-effect) |
| `Ref.get` then `Ref.set` | Two transitions; a suspension between them loses updates. | One `Ref.update` / `Ref.modify`; `SynchronizedRef` when the transition is effectful. | [One transition, one call](./concurrency/state-mutable-references.md#one-transition-one-call) |
| Mutating the object stored in a `Ref` | Bypasses the atomic transition and changes values other fibers already read. | Install a new immutable value in one `update`. | [One transition, one call](./concurrency/state-mutable-references.md#one-transition-one-call) |
| Reading a `MutableRef`, suspending, then writing from the stale value | Another fiber can update it during the suspension; replacing it with separate `Ref.get` / `Ref.set` calls has the same race. | One synchronous `MutableRef.update`, one `Ref.update`, or `SynchronizedRef` for an effectful transition. | [MutableRef](./concurrency/state-mutable-references.md#mutableref) |
| Non-idempotent I/O inside `Effect.tx` | A transaction body can rerun on conflict. | Keep external effects outside the transaction. | [The mental model](./concurrency/software-transactional-memory.md#the-mental-model) |
| Reusing a completed `Deferred` for the next generation | The next generation is "ready" instantly. | A fresh `Deferred` per generation; complete it on every outcome. | [Deferred](./foundations/fibers-scopes-runtimes.md#deferred) |
| `Queue.shutdown` as end-of-input | Discards the buffer; on an open queue, interrupts takers/awaiters and rejects pending offers through their result values. | `Queue.end`, then join the workers. | [Queue lifecycle](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does) |
| Readiness published before acquisition, or left true while draining | Traffic is routed to a process that cannot serve. | Readiness is a Layer acquired last and released first. | [Liveness, readiness, and draining](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#liveness-readiness-and-draining-are-different-questions) |

## Anti-patterns: concurrency, streams, and caching

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| `{ concurrency: "unbounded" }` over uncontrolled input | Can exhaust sockets, memory, API quotas, or database connections. | Use a numeric bound, shared Semaphore, bounded Queue/Stream stage, or Pool. | [Capacity is part of the contract](./deep-dives/structured-concurrency-through-a-bounded-worker.md#capacity-is-part-of-the-contract) |
| `Queue.unbounded` chosen because a test hung | Hides the deadlock and removes backpressure. | Find the missing consumer or end signal; test with capacity `1`. | [Queue lifecycle](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does) |
| `dropping` / `sliding` as a performance switch; an unchecked `offerUnsafe` result | Silent data loss. | Treat it as a stated loss policy and count what was shed. | [Make loss observable](./concurrency/concurrency-coordination.md#make-loss-observable) |
| `Stream.callback` without `bufferSize` | The buffer is unbounded by default. | `{ bufferSize, strategy }`, and say which loss policy it is. | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| `Stream.runCollect` on unknown or infinite input | Materializes the full stream and may never return or exhaust memory. | Incremental `runForEach`, a bounded Sink, batching, or streaming output. | [Running streams](./concurrency/streaming-channels.md#3-running-streams) |
| `runCollect` then `slice` for a preview; `take` after `buffer` | Reads far more than the prefix. | `Stream.take(n)` upstream of buffers and concurrent stages. | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| Opening a handle before the stream and closing it "when done" | Leaks on early stop or decode failure. | `Stream.unwrap` over a scoped acquisition. | [Owning resources inside a stream](./concurrency/streaming-channels.md#6-owning-resources-inside-a-stream) |
| `Stream.buffer({ capacity: n })` to get batches of `n` | Capacity is flow-control depth, not batch size. | `Stream.grouped(n)`, `groupedWithin(n, d)`, or `rechunk(n)`. | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| `Stream.timeout` as a failure detector | It ends the stream with no error. | `Stream.timeoutOrElse` with `Stream.fail(...)`. | [Handling stream failures](./concurrency/streaming-channels.md#5-handling-stream-failures) |
| Pairing resolver rows to entries by position, or skipping entries without a row | Callers receive each other's data, or die with "did not complete request". | Index rows by id; iterate the entries and settle each. | [Resolver obligations](./operations/caching-batching.md#resolver-obligations) |
| A hand-written promise map or lock for single-flight | `Cache.get` already shares one lookup among concurrent misses. | `Cache`, or `Effect.cached` for a keyless effect. | [Which problem do you have?](./operations/caching-batching.md#which-problem-do-you-have) |
| `Cache.make` with a long TTL over a fallible lookup | One transient failure is replayed for the full TTL. | `Cache.makeWith` with a short failure TTL. | [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy) |
| Whole records or un-normalized strings as cache keys | Equal real-world things produce different keys. | Normalize at ingress; a small key class. | [Keys are logical values](./operations/caching-batching.md#keys-are-logical-values) |

## Anti-patterns: Schema and boundaries

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| `Schema.Number` for every external number | Accepts `NaN` and infinities and says nothing about integer/range constraints. | `Schema.Finite`, `Schema.Int`, `Schema.Natural`, BigDecimal/BigInt codecs, and explicit checks. | [Refinements](./data/schema.md#5-refinements-check-and-refine) |
| `JSON.parse(raw) as Model`, `raw as EmployeeId` | A cast validates nothing. | Decode once at ingress; obtain brands through the decoder. | [Branded schemas](./data/schema.md#7-branded-schemas) |
| `Effect.sync(() => Schema.decodeUnknownSync(S)(x))` | Bad input becomes a defect. | `Schema.decodeUnknownEffect(S)(x)`. | [Decoding and encoding — pick your result style](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) |
| Decode, then `Effect.orElseSucceed(() => default)` | Malformed input is hidden behind a plausible value. | A declared decoding default for *absence*; fail on malformed input. | [Construction and deliberate fallbacks](./data/schema-in-depth.md#4-construction-and-deliberate-fallbacks) |
| `withConstructorDefault` expected to fill a missing key while decoding | It applies to `make` / `new` only. | `withDecodingDefault` / `withDecodingDefaultKey`. | [Default values](./data/schema.md#8-default-values) |
| Never choosing `onExcessProperty` | Undeclared keys are stripped silently. | Decide per boundary and test the policy. | [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy) |
| Decoding the same value again at internal function boundaries | Cost with no new information, and a second place for drift. | Decode once at ingress; pass the `Type`. | [Schema Type and Encoded mismatch](./troubleshooting/troubleshooting-and-anti-patterns.md#schema-type-and-encoded-mismatch) |
| `Schema.RedactedFromValue` without `disallowEncode` on a model that is also encoded | Every derived codec writes the secret back in clear text. | Set the option, or keep secrets out of encodable models. | [Secrets that arrive through a schema](./foundations/configuration-secrets.md#secrets-that-arrive-through-a-schema) |
| The endpoint's `success` schema is the table row | A persistence detail becomes a published contract. | Separate DTOs; map in the use case or repository. | [Handlers are lazy adapters](./interfaces/http-api.md#handlers-are-lazy-adapters) |

## Anti-patterns: HTTP, RPC, and SQL

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| A handler that runs an Effect, builds a client, or yields `SqlClient` | Breaks request ownership and absorbs policy no other entry point shares. | Return one use-case Effect. | [Handlers are lazy adapters](./interfaces/http-api.md#handlers-are-lazy-adapters) |
| Decoding the success schema before checking the status | A `404` body is reported as a schema failure. | `filterStatusOk` or `matchStatus` first. | [Three failure classes](./interfaces/http-client.md#three-failure-classes) |
| `retryTransient` on a client that sends mutations | It replays a `POST` as readily as a `GET`. | Two derived clients; idempotency keys the server honors. | [Retries, time budgets, and cancellation](./interfaces/http-client.md#retries-time-budgets-and-cancellation) |
| Fetching a user-supplied URL directly | Server-side request forgery. | Allow-list scheme and port, reject non-public addresses, re-validate every redirect. | [User-controlled destinations](./interfaces/http-client.md#user-controlled-destinations) |
| Treating a valid token, a reachable route, or a client middleware as authorization | None of them checks actor, action, tenant, and resource. | Authenticate in middleware (`401`); authorize in the use case (`403`). | [Authentication is not authorization](./interfaces/http-api.md#authentication-is-not-authorization) |
| A catch-all that serializes `error.message` into a response | Leaks internals; defects are already sanitized to a content-free `500`. | Declared errors with safe fields only. | [Status mapping is part of the contract](./interfaces/http-api.md#status-mapping-is-part-of-the-contract) |
| Mapping every RPC failure to one "RPC failed" error | Discards whether a retry is safe and whose bug it is. | Keep the six categories distinguishable. | [Keep six failure categories distinguishable](./interfaces/rpc.md#keep-six-failure-categories-distinguishable) |
| `Effect.ignore` / `Effect.catch` around a step inside `withTransaction` | The body succeeds, so the earlier writes **commit**. | Let the failure leave the body; recover outside. | [Transactions](./interfaces/sql.md#transactions) |
| Sending an email, webhook, or model call inside a transaction | Irreversible work inside a body that can roll back or retry. | Intent row in the transaction; deliver after commit. | [External effects after commit (outbox)](./interfaces/sql.md#external-effects-after-commit-outbox) |
| Mapping every `UniqueViolation` to one domain error | The wrong conflict is reported when another constraint fires. | Check which constraint fired. | [Normalizing errors at a repository boundary](./interfaces/sql.md#normalizing-errors-at-a-repository-boundary) |
| Editing an applied migration, or merging a lower-numbered one late | The migrator compares only the latest recorded id; the file never runs. | Append-only, higher ids. | [Operating migrations](./interfaces/sql.md#operating-migrations) |
| Assuming exactly-once delivery | A crash can occur after an external commit and before acknowledgement/journaling. | Idempotency keys, uniqueness constraints, transactions/outbox, and at-least-once-safe handlers. | [Failure windows and honest guarantees](./tooling/persistence.md#failure-windows-and-honest-guarantees) |

## Anti-patterns: observability and tests

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| Metric attributes with unbounded cardinality: employee, request, or session ids, raw URLs, error messages | Every distinct combination is a stored, billed time series. | Bounded vocabularies; detail in logs and span attributes. | [Cardinality](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded) |
| Instance data in a span name: `hris.fetchCompBand E-1042` | Backends group and index by name. | A stable operation name; ids in `attributes`. | [Cardinality](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded) |
| Logging whole objects: config, headers, bodies, rows, prompts | Secrets and personal data reach a production store. | Build each record from named, allow-listed fields. | [Privacy](./operations/observability.md#privacy-allow-list-fields-before-they-are-buffered) |
| `Logger.layer([Logger.consoleJson])` as a drop-in format swap | Replaces the whole logger set; logs stop becoming span events. | Add `Logger.tracerLogger`, or `{ mergeWithExisting: true }`. | [Installing and swapping loggers](./operations/observability.md#installing-and-swapping-loggers) |
| `Layer.merge(App, ObservabilityLayer)`; an exporter per request or inside a library | The application is built without the telemetry references; exporters compete. | One exporter graph at the root, provided beneath the application. | [Layer order and shutdown](./operations/telemetry-export.md#layer-order-and-shutdown) |
| The collector in a readiness check; SLIs computed from sampled spans | A telemetry outage becomes an outage; ratios are wrong. | Readiness from serving dependencies; SLIs from unsampled metrics. | [Telemetry is not readiness, liveness, or an audit log](./operations/observability.md#telemetry-is-not-readiness-liveness-or-an-audit-log) |
| An Effect returned from plain `it(...)` | Vitest never runs it: a green test that proves nothing. | `it.effect`. | [When green means nothing](./deep-dives/testing-an-effect-application.md#when-green-means-nothing) |
| Tests that assert elapsed milliseconds or pretty-printed failure strings | Flaky, and brittle across releases. | `TestClock` timelines; structural assertions on `Exit`, `_tag`, and fields. | [Assert typed failures as data](./deep-dives/testing-an-effect-application.md#assert-typed-failures-as-data) |
| `Effect.yieldNow` sprinkled to order fibers | Turn counting passes until something adds a turn. | A handshake per phase. | [Synchronize on phases, not on turns](./deep-dives/testing-an-effect-application.md#synchronize-on-phases-not-on-turns) |
| Fakes that never fail; socket, signal, or filesystem behavior asserted only against a fake | The failure path and the adapter are never exercised. | Fakes honor the contract; adapters get a real fixture. | [In-memory test runtimes shipped with Effect](./tooling/testing-dev-tooling.md#in-memory-test-runtimes-shipped-with-effect) |
| An identity `withTransaction` fake | Commits nothing and rolls back nothing, so atomicity is untested. | A repository contract suite against a real database. | [Verification levels](./interfaces/sql.md#verification-levels) |
| Using `declare const` in a supposedly runnable example | It type-checks only because the actual dependency is missing. | Label it contextual, or supply a complete fixture/runnable program. | — |

## Anti-patterns: durable systems and AI

| Anti-pattern | Why it is wrong | Preferred shape | Details |
| --- | --- | --- | --- |
| Renaming an `Activity`, workflow tag, or durable primitive while runs are in flight | The name is the journal key: replay re-executes or orphans. | Freeze persisted names; add a `V2` identity. | [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout) |
| Reading a feature flag or ambient config in a workflow body | The replay can take a different path. | Capture it in an `Activity` or the payload. | [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout) |
| An idempotency key generated per attempt | It deduplicates nothing. | Derive it from the intent or item id. | [Failure windows and honest guarantees](./tooling/persistence.md#failure-windows-and-honest-guarantees) |
| Treating a lock or lease as a fence | A stalled owner keeps running after losing the claim. | The sink rejects stale owners. | [A lease is not a fence](./deep-dives/durability-and-distribution-ladder.md#a-lease-is-not-a-fence) |
| Taking actor, tenant, or approval from model output | Model output is untrusted input. | Trusted request context only. | [Production rules for model calls](./systems/ai-language-models.md#production-rules-for-model-calls) |
| An agent loop with no turn limit, or tool handlers with default concurrency | Unbounded cost and load. | A bounded loop with a typed exhaustion error; a numeric `concurrency`. | [Bound every agentic loop](./deep-dives/building-a-production-ai-capability.md#bound-every-agentic-loop) |

# Recipe: A Service with Live and Test Layers

Define the capability once, keep implementations in Layers, and let the program’s `R` show whether wiring is complete.

## Contract

- **Classification:** Runnable example; complete `service-and-layers.ts`.
- **Install:** `pnpm add effect@4.1.4`
- **Run:** Node 26+: `node service-and-layers.ts`
- **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](./foundations/services-context-layers.md#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.

## Complete file

**Runnable example.**

<!-- effect-example id=service-live-test-layers check=run runtime=service-live-test-layers -->
```ts
import { Context, Effect, Layer } from "effect"

class GreetingService extends Context.Service<GreetingService, {
  readonly greet: (name: string) => Effect.Effect<string>
}>()("app/GreetingService") {
  // The primary implementation lives on a static `layer`; a variant gets a
  // descriptive suffix (`layerTest`, `layerConfig`, …) rather than a new name.
  static readonly layer = Layer.succeed(this)({
    greet: (name) => Effect.succeed(`Hello, ${name}!`)
  })

  static readonly layerTest = Layer.succeed(this)({
    greet: (name) => Effect.succeed(`[test] ${name}`)
  })
}

const greet = (name: string): Effect.Effect<string, never, GreetingService> =>
  Effect.gen(function*() {
    const service = yield* GreetingService
    return yield* service.greet(name)
  })

const liveProgram: Effect.Effect<string> = greet("Ada").pipe(
  Effect.provide(GreetingService.layer)
)

const testProgram: Effect.Effect<string> = greet("Ada").pipe(
  Effect.provide(GreetingService.layerTest)
)

console.log(await Effect.runPromise(liveProgram))
console.log(await Effect.runPromise(testProgram))
```

## Why this primitive?

`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](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph) has the decision table, and [Designing a service contract](./foundations/services-context-layers.md#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`](./foundations/services-context-layers.md#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](https://effect.website/docs/v4/requirements-management/layers) extends this pattern to services with dependencies and to test injection (it names the dependency-free Layer `layerWithoutDependencies`; this handbook uses `layerNoDeps`).

## Variations

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

```ts
import { Context, Effect, Layer, Ref } from "effect"

class GreetingService extends Context.Service<GreetingService, {
  readonly greet: (name: string) => Effect.Effect<string>
}>()("app/GreetingService") {}

const greet = (name: string) => GreetingService.use((service) => service.greet(name))

// A ready value needs no Layer.
const unitProgram = greet("Ada").pipe(
  Effect.provideService(
    GreetingService,
    GreetingService.of({ greet: (name) => Effect.succeed(`[unit] ${name}`) })
  )
)

// A recording fake: per-build state, observable through a probe service.
class GreetingCalls extends Context.Service<GreetingCalls, Ref.Ref<ReadonlyArray<string>>>()(
  "test/GreetingCalls"
) {}

const GreetingRecording = Layer.effect(GreetingService, Effect.gen(function*() {
  const calls = yield* GreetingCalls
  return GreetingService.of({
    greet: (name) => Ref.update(calls, (seen) => [...seen, name]).pipe(Effect.as(`[test] ${name}`))
  })
})).pipe(
  Layer.provideMerge(Layer.effect(GreetingCalls, Ref.make<ReadonlyArray<string>>([])))
)

// Yields ["Ada"] on every run; it cannot pass unless GreetingRecording handled the call.
const provesWiring = Effect.gen(function*() {
  yield* greet("Ada")
  const calls = yield* GreetingCalls
  return yield* Ref.get(calls)
}).pipe(Effect.provide(GreetingRecording))
```

`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](./tooling/testing-dev-tooling.md) and [Testing an Effect Application](./deep-dives/testing-an-effect-application.md).

## Common wrong alternative

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.

# Recipe: Schema to HttpApi to SQL

Use one domain Schema across the HTTP contract and SQL result decoder, while keeping transport decoding and database access at their respective boundaries.

## Contract

- **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.
- **Install:** `pnpm add effect@4.1.4 @effect/sql-pglite@4.1.4`
- **Run:** Node 26+: `node employees-api.ts`
- **Expected output:** `[{"id":1,"name":"Ada","email":"ada@example.com"}]`.
- **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.

## Complete file

**Runnable example.**

<!-- effect-example id=schema-httpapi-sql check=run runtime=schema-httpapi-sql -->
```ts
import { PgliteClient } from "@effect/sql-pglite"
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect"
import { Etag, HttpPlatform } from "effect/http"
import {
  HttpApi,
  HttpApiBuilder,
  HttpApiEndpoint,
  HttpApiGroup,
  HttpApiTest
} from "effect/http-api"
import { SqlClient, SqlSchema } from "effect/sql"

class Employee extends Schema.Class<Employee>("Employee")({
  id: Schema.Int.check(Schema.isGreaterThan(0)),
  name: Schema.String,
  email: Schema.String
}) {}

class EmployeesApi extends HttpApiGroup.make("employees")
  .add(
    HttpApiEndpoint.post("create", "/", {
      payload: Employee,
      success: Employee
    }),
    HttpApiEndpoint.get("list", "/", {
      success: Schema.Array(Employee)
    })
  )
  .prefix("/employees")
{}

class Api extends HttpApi.make("employee-api").add(EmployeesApi) {}

class EmployeeRepository extends Context.Service<EmployeeRepository, {
  readonly create: (employee: Employee) => Effect.Effect<Employee>
  readonly list: Effect.Effect<Array<Employee>>
}>()("app/EmployeeRepository") {}

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
      `
    })

    const selectAll = SqlSchema.findAll({
      Request: Schema.Void,
      Result: Employee,
      execute: () => sql`select id, name, email from employees order by id`
    })

    return EmployeeRepository.of({
      // A malformed database row or SQL failure is not part of this tiny API's
      // declared domain contract. A production API may instead map selected
      // SQL errors to explicit Schema.TaggedError endpoint errors.
      create: (employee) => insert(employee).pipe(Effect.orDie),
      list: selectAll(undefined).pipe(Effect.orDie)
    })
  })
)

const EmployeesHandlers = HttpApiBuilder.group(
  Api,
  "employees",
  Effect.fn(function*(handlers) {
    const repository = yield* EmployeeRepository
    return handlers
      .handle("create", ({ payload }) => repository.create(payload))
      .handle("list", () => repository.list)
  })
).pipe(Layer.provide(EmployeeRepositoryLive))

const DatabaseLive = PgliteClient.layer()

const Migrations = Layer.effectDiscard(
  Effect.gen(function*() {
    const sql = yield* SqlClient.SqlClient
    yield* sql`
      create table employees (
        id integer primary key,
        name text not null,
        email text not null unique
      )
    `
  })
)

// Both branches receive the same named database Layer value, so one managed
// client is shared within this build graph.
const ApplicationLive = Layer.merge(EmployeesHandlers, Migrations).pipe(
  Layer.provide(DatabaseLive)
)

const HttpTestServices = Layer.mergeAll(
  Path.layer,
  Etag.layerWeak,
  HttpPlatform.layer
).pipe(
  Layer.provideMerge(FileSystem.layerNoop({}))
)

const apiProgram = Effect.scoped(
  Effect.gen(function*() {
    const client = yield* HttpApiTest.groups(Api, ["employees"])
    yield* client.employees.create({
      payload: new Employee({
        id: 1,
        name: "Ada",
        email: "ada@example.com"
      })
    })
    return yield* client.employees.list()
  })
).pipe(Effect.orDie)

const runnable = apiProgram.pipe(
  Effect.provide(Layer.merge(ApplicationLive, HttpTestServices))
)

console.log(JSON.stringify(await Effect.runPromise(runnable)))
```

## Why these primitives?

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

```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](./interfaces/http-api.md#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.
- The status table behind these choices is in [HttpApi status mapping](./interfaces/http-api.md#status-mapping-is-part-of-the-contract); repository error normalization is in [SqlError](./interfaces/sql.md#sqlerror); making related writes atomic, and delivering side effects only after commit, is the [transactional write with outbox recipe](./recipes/transactional-write-with-outbox.md).

## Proving the boundary

`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](./interfaces/http-api.md#what-each-test-ring-proves).

## Common wrong alternative

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.

# Recipe: A Resource-Safe Bounded Worker

Use a bounded Queue for producer backpressure, a fixed number of supervised consumers for concurrency, and `acquireUseRelease` around each resource-owning job.

## Contract

- **Classification:** Runnable example; complete `bounded-worker.ts`.
- **Install:** `pnpm add effect@4.1.4`
- **Run:** Node 26+: `node bounded-worker.ts`
- **Expected output:** `{"results":[2,4,6,8,10],"released":5,"maxActive":2}`.
- **Program type:** `Effect<Summary, never, never>`.
- **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.

## Complete file

**Runnable example.**

<!-- effect-example id=resource-safe-bounded-worker check=run runtime=resource-safe-bounded-worker -->
```ts
import { Cause, Effect, Fiber, Queue, Ref, Stream } from "effect"

interface Job {
  readonly id: number
  readonly value: number
}

interface Summary {
  readonly results: Array<number>
  readonly released: number
  readonly maxActive: number
}

const program: Effect.Effect<Summary> = Effect.gen(function*() {
  // At most two jobs may wait in memory. A faster producer suspends when full.
  const queue = yield* Queue.bounded<Job, Cause.Done>(2)
  const results = yield* Ref.make<Array<number>>([])

  let active = 0
  let released = 0
  let maxActive = 0

  const processJob = (job: Job) =>
    Effect.acquireUseRelease(
      Effect.sync(() => {
        active += 1
        maxActive = Math.max(maxActive, active)
        return { jobId: job.id }
      }),
      () => Effect.sleep("10 millis").pipe(Effect.as(job.value * 2)),
      () => Effect.sync(() => {
        active -= 1
        released += 1
      })
    ).pipe(
      Effect.tap((result) => Ref.update(results, (values) => [...values, result])),
      Effect.asVoid
    )

  const worker = Stream.fromQueue(queue).pipe(
    Stream.runForEach(processJob)
  )

  // Two consumers compete for Queue elements: one job goes to one worker.
  const workers = yield* Effect.all([worker, worker], {
    concurrency: "unbounded",
    discard: true
  }).pipe(Effect.forkChild)

  yield* Queue.offerAll(queue, [
    { id: 1, value: 1 },
    { id: 2, value: 2 },
    { id: 3, value: 3 },
    { id: 4, value: 4 },
    { id: 5, value: 5 }
  ])
  yield* Queue.end(queue)
  yield* Fiber.join(workers)

  const completed = yield* Ref.get(results)
  return {
    results: [...completed].sort((a, b) => a - b),
    released,
    maxActive
  }
})

console.log(JSON.stringify(await Effect.runPromise(program)))
```

## Why these primitives?

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/concurrency-coordination.md#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](./concurrency/concurrency-coordination.md#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](./deep-dives/structured-concurrency-through-a-bounded-worker.md) builds the same design step by step, including failure policy and shutdown.

## Common wrong alternative

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.

# Recipe: Typed Retry with TestClock

Keep transient failures typed, classify them in the Schedule, fork the retrying operation, and advance virtual time instead of waiting in real time.

> **Official guides:** [Retrying](https://effect.website/docs/v4/error-management/retrying), [TestClock](https://effect.website/docs/v4/testing/testclock). Where that guide and the edition's tagged source disagree, this page and the source win.

## Contract

- **Classification:** Runnable example; complete `retry-test-clock.ts`.
- **Install:** `pnpm add effect@4.1.4`
- **Run:** Node 26+: `node retry-test-clock.ts`
- **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](#assert-the-shape-of-the-policy) adds both.

## Complete file

**Runnable example.**

<!-- effect-example id=typed-retry-testclock check=run runtime=typed-retry-testclock -->
```ts
import { Effect, Fiber, Ref, Schedule, Schema } from "effect"
import { TestClock } from "effect/testing"

class TransientError extends Schema.TaggedError<TransientError>()(
  "TransientError",
  {
    attempt: Schema.Int,
    retryable: Schema.Boolean
  }
) {}

const retryPolicy = Schedule.exponential("1 second").pipe(
  Schedule.setInputType<TransientError>(),
  Schedule.while(({ input }) => input.retryable),
  Schedule.upTo({ times: 2 })
)

const testProgram = Effect.gen(function*() {
  const attempts = yield* Ref.make(0)

  const operation: Effect.Effect<string, TransientError> = Effect.gen(function*() {
    const attempt = yield* Ref.updateAndGet(attempts, (n) => n + 1)
    if (attempt < 3) {
      return yield* new TransientError({ attempt, retryable: true })
    }
    return "ready"
  })

  // The sleeping retry fiber must run independently while the test drives time.
  const fiber = yield* operation.pipe(
    Effect.retry(retryPolicy),
    Effect.forkChild
  )

  yield* TestClock.adjust("1 second")
  yield* TestClock.adjust("2 seconds")

  return {
    value: yield* Fiber.join(fiber),
    attempts: yield* Ref.get(attempts)
  }
})

const runnable = testProgram.pipe(
  Effect.provide(TestClock.layer())
)

console.log(JSON.stringify(await Effect.runPromise(runnable)))
```

## Why these primitives?

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

## Assert the shape of the policy

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

```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](./concurrency/scheduling-time.md#testing-a-policy) lists the same checks as a policy checklist.

## Common wrong alternative

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.

# Recipe: Production Observability

Instrument business work once with structured logs, metrics, and spans; select a local JSON logger or the OTLP exporter at the Layer boundary.

## Contract

- **Classification:** Runnable example; complete `observability.ts`.
- **Install:** `pnpm add effect@4.1.4`
- **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](https://effect.website/docs/v4/observability/tracing) 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.

## Complete file

**Runnable example.**

<!-- effect-example id=production-observability check=run runtime=production-observability -->
```ts
import { Config, Effect, Layer, Logger, Metric } from "effect"
import { FetchHttpClient } from "effect/http"
import { Otlp } from "effect/observability"

interface OrderResult {
  readonly orderId: string
  readonly status: "accepted"
}

const acceptedOrders = Metric.counter("orders_accepted_total", {
  description: "Accepted orders",
  incremental: true
})

const acceptOrder = (orderId: string): Effect.Effect<OrderResult> =>
  Effect.gen(function*() {
    yield* Metric.update(acceptedOrders, 1)
    yield* Effect.logInfo("order accepted")
    return { orderId, status: "accepted" as const }
  }).pipe(
    Effect.withSpan("orders.accept", {
      kind: "server",
      attributes: { "order.id": orderId }
    }),
    Effect.annotateLogs({ service: "orders", orderId })
  )

const Observability = Layer.unwrap(
  Effect.gen(function*() {
    const endpoint = yield* Config.String("OTEL_EXPORTER_OTLP_ENDPOINT").pipe(
      Config.withDefault("")
    )

    if (endpoint === "") {
      // Logger.layer replaces the default logger set, so re-add tracerLogger:
      // it is what turns each log call into an event on the active span.
      return Logger.layer([Logger.consoleJson, Logger.tracerLogger])
    }

    return Otlp.layerJson({
      baseUrl: endpoint,
      resource: {
        serviceName: "orders",
        serviceVersion: "1.0.0",
        attributes: { "deployment.environment": "production" }
      },
      loggerExportInterval: "1 second",
      metricsExportInterval: "10 seconds",
      tracerExportInterval: "1 second",
      // Upper bound for the flush on shutdown, per exporter.
      shutdownTimeout: "3 seconds"
    }).pipe(Layer.provide(FetchHttpClient.layer))
  })
)

const RuntimeLayer = Layer.merge(
  Observability,
  Metric.enableRuntimeMetricsLayer
)

const main: Effect.Effect<OrderResult, Config.ConfigError> = acceptOrder("ord-42").pipe(
  Effect.provide(RuntimeLayer)
)

console.log(JSON.stringify(await Effect.runPromise(main)))
```

## Why these primitives?

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](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded)).
- **`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.

## Before production

- 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](./operations/observability.md#privacy-allow-list-fields-before-they-are-buffered)).
- Each signal has exactly one export path — no SDK bridge and direct OTLP for the same signal (see [One export path per signal](./operations/telemetry-export.md#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](./operations/telemetry-export.md#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](./operations/telemetry-export.md#verifying-telemetry).

## Common wrong alternative

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.

# Recipe: A Graceful Node Entrypoint

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](https://effect.website/docs/v4/code-style/guidelines) (why `runMain` rather than `runPromise`). Where that guide and the edition's tagged source disagree, this page and the source win.

## Contract

- **Classification:** Runnable example; complete `main.ts`.
- **Install:** `pnpm add effect@4.1.4 @effect/platform-node@4.1.4`
- **Run:** Node 26+: `node main.ts`
- **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.

## Complete file

**Runnable example.**

<!-- effect-example id=graceful-entrypoint-shutdown check=run runtime=graceful-entrypoint-shutdown -->
```ts
import { NodeRuntime } from "@effect/platform-node"
import { Effect, Layer } from "effect"

const WorkerLive = Layer.effectDiscard(
  Effect.gen(function*() {
    yield* Effect.logInfo("worker started")
    yield* Effect.addFinalizer(() => Effect.logInfo("worker stopped"))

    yield* Effect.forkScoped(
      Effect.forever(
        Effect.logInfo("heartbeat").pipe(
          Effect.andThen(Effect.sleep("1 second"))
        )
      )
    )
  })
)

const main: Effect.Effect<never> = Layer.launch(WorkerLive)

NodeRuntime.runMain(main)
```

## Why these primitives?

`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)](https://effect.website/docs/v4/platform/runtime). 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](./foundations/fibers-scopes-runtimes.md#runtime).

## Adding readiness and a bounded drain

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:

```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 work
declare 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](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md).

## Common wrong alternative

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.

# 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](https://effect.website/docs/v4/runtime). Where that guide and the edition's tagged source disagree, this page and the source win.

## Contract

- **Classification:** Runnable example; complete `managed-runtime.ts`.
- **Install:** `pnpm add effect@4.1.4`
- **Run:** Node 26+: `node managed-runtime.ts`
- **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](./recipes/request-cancellation-through-a-host.md) 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.

## Complete file

**Runnable example.**

<!-- effect-example id=managed-runtime-integration check=run runtime=managed-runtime-integration -->
```ts
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.

## A production-shaped bridge

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.

```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 = true
const 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> | undefined
export 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.

The reasons behind each step, and the Effect-native equivalent built from Layer order alone, are in [Owning Lifetimes — Startup, Readiness, and Shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md).

## How to test this seam

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](./recipes/request-cancellation-through-a-host.md) is that test written as a program.

## Why this primitive?

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.

## Common wrong alternative

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.

# Recipe: Request Cancellation Through a Host

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.

## Contract

- **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 flight
host: 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 L5
layer: HRIS directory released
host: runtime disposed
```

## Complete file

**Runnable example.**

<!-- effect-example id=request-cancellation-host check=run runtime=request-cancellation-host -->
```ts
import { Cause, Context, Data, Effect, Exit, Layer, ManagedRuntime } from "effect"

// --- A Promise SDK the application does not own (stands in for fetch or a driver).
// It honors an AbortSignal. `nextLookupInFlight` is a demo latch: it lets the simulated
// client disconnect at a known point instead of after a sleep.
let markInFlight: () => void = () => {}
const nextLookupInFlight = (): Promise<void> =>
  new Promise((resolve) => {
    markInFlight = resolve
  })

const hrisSdk = {
  lookupBand: (employeeId: string, signal: AbortSignal): Promise<string> =>
    new Promise((resolve, reject) => {
      console.log(`  sdk: lookup ${employeeId} in flight`)
      const timer = setTimeout(() => resolve(`${employeeId} is in band L5`), 25)
      signal.addEventListener("abort", () => {
        clearTimeout(timer)
        console.log(`  sdk: lookup ${employeeId} aborted, socket freed`)
        reject(new Error("aborted"))
      }, { once: true })
      markInFlight()
    })
}

// --- The Effect application.
class HrisUnavailable extends Data.TaggedError("HrisUnavailable")<{
  readonly cause: unknown
}> {}

class HrisDirectory extends Context.Service<HrisDirectory, {
  readonly band: (employeeId: string) => Effect.Effect<string, HrisUnavailable>
}>()("app/HrisDirectory") {
  static layer = Layer.effect(
    HrisDirectory,
    Effect.gen(function*() {
      yield* Effect.acquireRelease(
        Effect.sync(() => console.log("layer: HRIS directory acquired")),
        () => Effect.sync(() => console.log("layer: HRIS directory released"))
      )
      return {
        band: (employeeId) =>
          Effect.tryPromise({
            // Hop two: Effect aborts THIS signal when the calling fiber is interrupted.
            try: (signal) => hrisSdk.lookupBand(employeeId, signal),
            catch: (cause) => new HrisUnavailable({ cause })
          })
      }
    })
  )
}

const outcome = (exit: Exit.Exit<unknown, unknown>): string =>
  Exit.isSuccess(exit) ? "success" : Cause.hasInterruptsOnly(exit.cause) ? "interrupted" : "failure"

const compBand = Effect.fn("compBand")(function*(employeeId: string) {
  const hris = yield* HrisDirectory
  // A request-scoped resource: it must be returned however the request ends.
  yield* Effect.acquireRelease(
    Effect.sync(() => console.log("  effect: rate-limit permit taken")),
    (_, exit) => Effect.sync(() => console.log(`  effect: rate-limit permit returned (${outcome(exit)})`))
  )
  return yield* hris.band(employeeId)
}, Effect.scoped)

// --- The host: plain Promise code, standing in for an HTTP framework.
const runtime = ManagedRuntime.make(HrisDirectory.layer)

interface HostResponse {
  readonly status: number
  readonly body: string
}

const handle = async (employeeId: string, requestSignal: AbortSignal): Promise<HostResponse> => {
  // Hop one: the host's signal interrupts the fiber that runs this request.
  const exit = await runtime.runPromiseExit(compBand(employeeId), { signal: requestSignal })
  if (Exit.isSuccess(exit)) return { status: 200, body: exit.value }
  if (Cause.hasInterruptsOnly(exit.cause)) return { status: 499, body: "client closed request" }
  return { status: 503, body: "HRIS unavailable" }
}

// Request 1: the client disconnects while the HRIS call is in flight.
const first = new AbortController()
const lookupInFlight = nextLookupInFlight()
const firstResponse = handle("emp-1042", first.signal)
await lookupInFlight
console.log("host: client disconnected, aborting request 1")
first.abort()
const one = await firstResponse
console.log(`host: request 1 -> ${one.status} ${one.body}`)

// Request 2: same runtime, nobody aborts.
const two = await handle("emp-2077", new AbortController().signal)
console.log(`host: request 2 -> ${two.status} ${two.body}`)

await runtime.dispose()
console.log("host: runtime disposed")
```

## Why it is shaped this way

**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()`.

### The two broken versions

Both come from editing one line of the file above and running it against the complete file's harness:

| Dropped hop | Edit | What request 1 prints instead | What it costs |
| --- | --- | --- | --- |
| Hop one | `runtime.runPromiseExit(compBand(employeeId))` | No `sdk: … aborted` line; `permit returned (success)`; `request 1 -> 200` | The full HRIS call, the permit, and a response body are spent on a client that is gone. |
| Hop two | `try: () => hrisSdk.lookupBand(employeeId, someOtherSignal)` | `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.

```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](./foundations/core-runtime-execution.md#effect); this recipe is only the seam.

## Variations

- **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](./interfaces/http-server.md#httpeffect).
- **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](./recipes/managed-runtime-integration.md) has the protocol and [Owning Lifetimes](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md) explains why.

# Recipe: A Transactional Write with an Outbox

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.

## Contract

- **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.
- **Install:** `pnpm add effect@4.1.4 @effect/sql-pglite@4.1.4`
- **Run:** Node 26+: `node raise-outbox.ts`
- **Expected output:** six JSON lines, reproduced byte for byte under [Expected output](#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.

### Expected output

```text
{"step":"approve ada","salary":130000,"outbox":[{"id":"raise-approved:2026:1","delivered":false,"attempts":0}],"received":0}
{"step":"approve grace","outcome":"MeritBudgetExceeded overBy=5000","salary":150000,"outboxRows":1}
{"step":"relay 1","delivered":0,"failed":1,"outbox":[{"id":"raise-approved:2026:1","delivered":false,"attempts":1}]}
{"step":"relay 2","delivered":1,"failed":0,"outbox":[{"id":"raise-approved:2026:1","delivered":true,"attempts":2}]}
{"step":"relay 3","delivered":0,"failed":0}
{"step":"payroll","received":2,"duplicates":1,"applied":["raise-approved:2026:1"]}
```

| Line | What it proves |
| --- | --- |
| `approve ada` | The salary change and its `RaiseApproved` outbox row committed together, and nothing has been delivered yet (`received: 0`). |
| `approve grace` | The merit-budget rule failed *after* both writes, inside the transaction: the salary is unchanged and no second outbox row exists. |
| `relay 1` | Payroll accepted the event but the acknowledgement was lost, so the row is still pending with `attempts: 1`. |
| `relay 2` | The same outbox id was redelivered; only now is the row marked delivered. |
| `relay 3` | Nothing is pending, so nothing is sent. |
| `payroll` | Two deliveries, one application: the consumer deduplicated on the outbox id. |

## Complete file

**Runnable example.**

<!-- effect-example id=transactional-outbox check=run runtime=transactional-outbox -->
```ts
import { PgliteClient } from "@effect/sql-pglite"
import { Context, Data, Effect, Layer, Option, Ref, Schema } from "effect"
import { SqlClient, SqlSchema } from "effect/sql"
import type { SqlError } from "effect/sql"

// --- Domain -----------------------------------------------------------------

class RaiseApproved extends Schema.Class<RaiseApproved>("RaiseApproved")({
  employeeId: Schema.Int,
  cycle: Schema.String,
  newSalary: Schema.Int
}) {}

class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", {
  employeeId: Schema.Int
}) {}

class MeritBudgetExceeded extends Schema.TaggedError<MeritBudgetExceeded>()("MeritBudgetExceeded", {
  cycle: Schema.String,
  overBy: Schema.Int
}) {}

class DeliveryFailed extends Schema.TaggedError<DeliveryFailed>()("DeliveryFailed", {
  messageId: Schema.String,
  reason: Schema.String
}) {}

// The one storage error both repositories expose. The cause stays typed, so a
// caller can still inspect `cause.reason` for a domain decision.
class RepositoryError extends Data.TaggedError("RepositoryError")<{
  readonly operation: string
  readonly cause: SqlError.SqlError | Schema.SchemaError
}> {}

// Maps only the typed channel. Defects and interruption pass through untouched.
const owned = (operation: string) =>
<A, R>(self: Effect.Effect<A, SqlError.SqlError | Schema.SchemaError, R>) =>
  Effect.mapError(self, (cause) => new RepositoryError({ operation, cause }))

// --- Outbox repository --------------------------------------------------------

class OutboxMessage extends Schema.Class<OutboxMessage>("OutboxMessage")({
  id: Schema.String,
  topic: Schema.String,
  payload: Schema.fromJsonString(RaiseApproved),
  attempts: Schema.Int,
  delivered: Schema.Boolean
}) {}

class Outbox extends Context.Service<Outbox, {
  readonly enqueue: (id: string, topic: string, event: RaiseApproved) => Effect.Effect<void, RepositoryError>
  readonly all: Effect.Effect<Array<OutboxMessage>, RepositoryError>
  readonly pending: Effect.Effect<Array<OutboxMessage>, RepositoryError>
  readonly recordAttempt: (id: string) => Effect.Effect<void, RepositoryError>
  readonly markDelivered: (id: string) => Effect.Effect<void, RepositoryError>
}>()("app/Outbox") {
  static readonly layer = Layer.effect(
    Outbox,
    Effect.gen(function*() {
      const sql = yield* SqlClient.SqlClient

      const insert = SqlSchema.void({
        Request: OutboxMessage,
        execute: (row) => sql`insert into outbox ${sql.insert(row)}`
      })
      const select = SqlSchema.findAll({
        Request: Schema.Struct({ pendingOnly: Schema.Boolean }),
        Result: OutboxMessage,
        execute: ({ pendingOnly }) =>
          sql`select id, topic, payload, attempts, delivered from outbox ${
            pendingOnly ? sql`where delivered = false` : sql``
          } order by seq`
      })

      return Outbox.of({
        enqueue: (id, topic, event) =>
          insert(new OutboxMessage({ id, topic, payload: event, attempts: 0, delivered: false })).pipe(
            owned("Outbox.enqueue")
          ),
        all: select({ pendingOnly: false }).pipe(owned("Outbox.all")),
        pending: select({ pendingOnly: true }).pipe(owned("Outbox.pending")),
        recordAttempt: (id) =>
          sql`update outbox set attempts = attempts + 1 where id = ${id}`.pipe(
            Effect.asVoid,
            owned("Outbox.recordAttempt")
          ),
        markDelivered: (id) =>
          sql`update outbox set delivered = true where id = ${id} and delivered = false`.pipe(
            Effect.asVoid,
            owned("Outbox.markDelivered")
          )
      })
    })
  )
}

// --- Raises use case: owns the transaction boundary ---------------------------

const Salary = Schema.Struct({ salary: Schema.Int })
const Remaining = Schema.Struct({ remaining: Schema.Int })

class Raises extends Context.Service<Raises, {
  readonly approve: (input: {
    readonly employeeId: number
    readonly cycle: string
    readonly amount: number
  }) => Effect.Effect<RaiseApproved, EmployeeNotFound | MeritBudgetExceeded | RepositoryError>
  readonly salaryOf: (employeeId: number) => Effect.Effect<number, EmployeeNotFound | RepositoryError>
}>()("app/Raises") {
  static readonly layer = Layer.effect(
    Raises,
    Effect.gen(function*() {
      const sql = yield* SqlClient.SqlClient
      const outbox = yield* Outbox

      const applyRaise = SqlSchema.findOneOption({
        Request: Schema.Struct({ employeeId: Schema.Int, amount: Schema.Int }),
        Result: Salary,
        execute: ({ amount, employeeId }) =>
          sql`update employees set salary = salary + ${amount} where id = ${employeeId} returning salary`
      })
      const drawBudget = SqlSchema.findOneOption({
        Request: Schema.Struct({ cycle: Schema.String, amount: Schema.Int }),
        Result: Remaining,
        execute: ({ amount, cycle }) =>
          sql`update merit_budgets set remaining = remaining - ${amount} where cycle = ${cycle} returning remaining`
      })
      const selectSalary = SqlSchema.findOneOption({
        Request: Schema.Int,
        Result: Salary,
        execute: (employeeId) => sql`select salary from employees where id = ${employeeId}`
      })

      const approve = Effect.fn("Raises.approve")(function*(input: {
        readonly employeeId: number
        readonly cycle: string
        readonly amount: number
      }) {
        const unit = Effect.gen(function*() {
          // Zero rows is domain absence; a bad row or a failed statement is not.
          const raised = yield* applyRaise(input).pipe(owned("Raises.approve.applyRaise"))
          if (Option.isNone(raised)) {
            return yield* new EmployeeNotFound({ employeeId: input.employeeId })
          }
          const event = new RaiseApproved({
            employeeId: input.employeeId,
            cycle: input.cycle,
            newSalary: raised.value.salary
          })
          // Same SqlClient, same fiber context: this insert joins the transaction.
          yield* outbox.enqueue(`raise-approved:${input.cycle}:${input.employeeId}`, "RaiseApproved", event)
          const budget = yield* drawBudget(input).pipe(owned("Raises.approve.drawBudget"))
          // A cycle without a budget row has nothing to draw from.
          const remaining = Option.match(budget, { onNone: () => -input.amount, onSome: (row) => row.remaining })
          // The rule is checked AFTER both writes. Failing here fails the body,
          // so the salary update and the outbox row roll back together.
          if (remaining < 0) {
            return yield* new MeritBudgetExceeded({ cycle: input.cycle, overBy: -remaining })
          }
          return event
        })
        // No recovery inside the body: commit or rollback is decided by its Exit.
        return yield* sql.withTransaction(unit).pipe(
          Effect.catchTag("SqlError", (cause) => Effect.fail(new RepositoryError({ operation: "Raises.approve", cause })))
        )
      })

      const salaryOf = Effect.fn("Raises.salaryOf")(function*(employeeId: number) {
        const row = yield* selectSalary(employeeId).pipe(owned("Raises.salaryOf"))
        if (Option.isNone(row)) {
          return yield* new EmployeeNotFound({ employeeId })
        }
        return row.value.salary
      })

      return Raises.of({ approve, salaryOf })
    })
  )
}

// --- Relay: runs after commit, outside any transaction ------------------------

class Publisher extends Context.Service<Publisher, {
  readonly publish: (message: OutboxMessage) => Effect.Effect<void, DeliveryFailed>
}>()("app/Publisher") {}

const relayPass = Effect.gen(function*() {
  const outbox = yield* Outbox
  const publisher = yield* Publisher
  const pending = yield* outbox.pending
  const outcomes = yield* Effect.forEach(pending, (message) =>
    outbox.recordAttempt(message.id).pipe(
      Effect.andThen(publisher.publish(message)),
      // Acknowledge only after the publish succeeded.
      Effect.andThen(outbox.markDelivered(message.id)),
      Effect.as(true),
      // A failed delivery is an expected outcome: the row stays pending.
      Effect.catchTag("DeliveryFailed", () => Effect.succeed(false))
    ))
  return {
    delivered: outcomes.filter((ok) => ok).length,
    failed: outcomes.filter((ok) => !ok).length
  }
})

// --- A scripted broker and an idempotent consumer for the demo ---------------

interface PayrollStats {
  readonly received: number
  readonly duplicates: number
  readonly applied: ReadonlyArray<string>
}

class Payroll extends Context.Service<Payroll, {
  readonly receive: (message: OutboxMessage) => Effect.Effect<void>
  readonly stats: Effect.Effect<PayrollStats>
}>()("app/Payroll") {
  static readonly layer = Layer.effect(
    Payroll,
    Effect.gen(function*() {
      const state = yield* Ref.make<PayrollStats>({ received: 0, duplicates: 0, applied: [] })
      return Payroll.of({
        // Deduplicate on the outbox id: a redelivery is acknowledged, not re-applied.
        receive: (message) =>
          Ref.update(state, ({ applied, duplicates, received }) =>
            applied.includes(message.id)
              ? { received: received + 1, duplicates: duplicates + 1, applied }
              : { received: received + 1, duplicates, applied: [...applied, message.id] }),
        stats: Ref.get(state)
      })
    })
  )
}

// Loses the acknowledgement of the first publish AFTER the consumer accepted it.
const PublisherLosesFirstAck = Layer.effect(
  Publisher,
  Effect.gen(function*() {
    const payroll = yield* Payroll
    const acksToLose = yield* Ref.make(1)
    return Publisher.of({
      publish: Effect.fn("Publisher.publish")(function*(message: OutboxMessage) {
        yield* payroll.receive(message)
        const lose = yield* Ref.modify(acksToLose, (n) => [n > 0, Math.max(0, n - 1)] as const)
        if (lose) {
          return yield* new DeliveryFailed({ messageId: message.id, reason: "acknowledgement lost" })
        }
      })
    })
  })
)

// --- Wiring ---------------------------------------------------------------------

const Migrations = Layer.effectDiscard(
  Effect.gen(function*() {
    const sql = yield* SqlClient.SqlClient
    yield* sql`create table employees (id integer primary key, name text not null, salary integer not null)`
    yield* sql`create table merit_budgets (cycle text primary key, remaining integer not null)`
    yield* sql`
      create table outbox (
        seq serial,
        id text primary key,
        topic text not null,
        payload text not null,
        attempts integer not null default 0,
        delivered boolean not null default false
      )
    `
    yield* sql`insert into employees ${
      sql.insert([
        { id: 1, name: "Ada", salary: 120000 },
        { id: 2, name: "Grace", salary: 150000 }
      ])
    }`
    yield* sql`insert into merit_budgets ${sql.insert({ cycle: "2026", remaining: 12000 })}`
  })
)

// One named database Layer value: `Raises` and `Outbox` share one SqlClient, which
// is what lets `outbox.enqueue` join the transaction opened by `Raises.approve`.
const DatabaseLive = Migrations.pipe(Layer.provideMerge(PgliteClient.layer()))

const ApplicationLive = Raises.layer.pipe(
  Layer.provideMerge(Outbox.layer),
  Layer.provide(DatabaseLive),
  Layer.merge(PublisherLosesFirstAck.pipe(Layer.provideMerge(Payroll.layer)))
)

const program = Effect.gen(function*() {
  const raises = yield* Raises
  const outbox = yield* Outbox
  const payroll = yield* Payroll
  const lines: Array<unknown> = []
  const outboxView = Effect.map(outbox.all, (rows) =>
    rows.map(({ attempts, delivered, id }) => ({ id, delivered, attempts })))

  // 1. The salary change and its event commit together; nothing is delivered yet.
  yield* raises.approve({ employeeId: 1, cycle: "2026", amount: 10000 })
  lines.push({
    step: "approve ada",
    salary: yield* raises.salaryOf(1),
    outbox: yield* outboxView,
    received: (yield* payroll.stats).received
  })

  // 2. A business rule that fails inside the transaction rolls both writes back.
  const outcome = yield* raises.approve({ employeeId: 2, cycle: "2026", amount: 7000 }).pipe(
    Effect.as("approved"),
    Effect.catchTag("MeritBudgetExceeded", (error) => Effect.succeed(`${error._tag} overBy=${error.overBy}`))
  )
  lines.push({
    step: "approve grace",
    outcome,
    salary: yield* raises.salaryOf(2),
    outboxRows: (yield* outbox.all).length
  })

  // 3 + 4. Deliver after commit. The first pass loses the acknowledgement, so the
  // row stays pending and the second pass redelivers the same outbox id.
  lines.push({ step: "relay 1", ...(yield* relayPass), outbox: yield* outboxView })
  lines.push({ step: "relay 2", ...(yield* relayPass), outbox: yield* outboxView })
  lines.push({ step: "relay 3", ...(yield* relayPass) })
  lines.push({ step: "payroll", ...(yield* payroll.stats) })
  return lines
})

const runnable = program.pipe(Effect.provide(ApplicationLive))

for (const line of await Effect.runPromise(runnable)) {
  console.log(JSON.stringify(line))
}
```

## Why it is shaped this way

**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](./deep-dives/durability-and-distribution-ladder.md#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.

The rules behind each step are in [SQL: Transactions](./interfaces/sql.md#transactions), [External effects after commit](./interfaces/sql.md#external-effects-after-commit-outbox), and [Normalizing errors at a repository boundary](./interfaces/sql.md#normalizing-errors-at-a-repository-boundary).

## Variations

- **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](./interfaces/sql.md#native-client-behavior-codecs-json-and-listen)).
- **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](./interfaces/sql.md#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](./tooling/persistence.md#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](./interfaces/http-api.md); the shared-Schema wiring is shown in [Recipe: Schema to HttpApi to SQL](./recipes/schema-httpapi-sql-boundary.md).
- **Beyond one database.** When the work spans services or must survive long waits, move up [the durability and distribution ladder](./deep-dives/durability-and-distribution-ladder.md) to workflows and cluster messaging.

# CLI Framework

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src/70_cli) provides a compact runnable companion.

## CliConfig

`effect/cli/CliConfig` — unstable

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.

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

## Command

`effect/cli/Command` — unstable

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

```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 commands
const 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 subcommands
const 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 employee
const 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 cycle
const 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 subcommand
const review = Command.make("review").pipe(
  Command.withDescription("Manage merit review cycles"),
  Command.withSubcommands([reviewStart])
)

// Wire subcommands and run
comp.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.

### Key combinators

| Combinator | Purpose |
| --- | --- |
| `Command.make(name, config, handler)` | 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](#validating-input-across-flags)) |
| `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.

### Validating input across flags

`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` |

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

### Testing a command

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

```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):

```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](./deep-dives/testing-an-effect-application.md#the-built-artifact-lane)) |

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`](#clioutput).

Use when you need a type-safe CLI application with subcommands, help generation, and shell completions.

## Flag

`effect/cli/Flag` — unstable

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.

```ts
import { Config } from "effect"
import { Flag, Prompt } from "effect/cli"

// Boolean: --dry-run / --no-dry-run
const 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 shares
const shares = Flag.Int("shares").pipe(
  Flag.withAlias("s"),
  Flag.withDescription("Number of RSU shares"),
  Flag.withDefault(500)
)

// Constrained enum: target merit cycle
const 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 absent
const hrisToken = Flag.String("hris-token").pipe(
  Flag.withFallbackConfig(Config.String("HRIS_API_TOKEN"))
)

// Redacted string — value is masked in help and logs
const apiSecret = Flag.Redacted("api-secret")

// Optional — yields Option<string>, None when omitted
const 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: " })
  )
)
```

### Flag constructors at a glance

Key APIs: Flag.String, Flag.Boolean, Flag.Int, Flag.Finite, Flag.Date, Flag.Literals, Flag.ChoiceWithValue, Flag.Path, Flag.File, Flag.Directory, Flag.Redacted, Flag.FileText, Flag.FileParse, Flag.FileSchema, Flag.KeyValuePair

### Validation, alternatives, and awkward values

```ts
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 |

### GNU-style optional flag values

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

```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`](#commandspec) reports them.

Use when you need named `--` options for type-safe command configuration.

## Argument

`effect/cli/Argument` — unstable

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.

```ts
import { Argument } from "effect/cli"

// Required positional: the employee ID to look up
const employeeArg = Argument.String("employee-id").pipe(
  Argument.withDescription("Employee ID (e.g. e-42)")
)

// Optional positional: an output file path
const outFile = Argument.String("output-file").pipe(
  Argument.optional   // yields Option<string>
)

// Variadic — collect zero or more employee IDs for a bulk operation
const employeeIds = Argument.String("employee-ids").pipe(
  Argument.variadic,
  Argument.withDescription("Employee IDs to process")
)

// Read a comp-plan JSON file directly from a positional path
const planFile = Argument.FileText("plan-path").pipe(
  Argument.withDescription("Path to the comp plan JSON file")
)

// Parse positional as a chosen enum value
const 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:

```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 ids
const idsOrAll = Argument.String("employee-id").pipe(
  Argument.atLeast(1),
  Argument.withDefault(["all"])
)

// Bounded: between one and five ids, no default
const 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.

## Param

`effect/cli/Param` — unstable

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`](#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.

## Primitive

`effect/cli/Primitive` — unstable

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.String** — Identity: accepts any string.

- **Primitive.Boolean** — Accepts `true/false/yes/no/on/off/1/0`. Recognises `--no-<flag>` canonical negation.

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

## Prompt

`effect/cli/Prompt` — unstable

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`](#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.

```ts
import { Effect } from "effect"
import { Flag, Prompt } from "effect/cli"

// Text input — for capturing an employee's new title on promotion
const titlePrompt = Prompt.String({ message: "New job title: " })

// Password — masked input for the HRIS API token
const hrisTokenPrompt = Prompt.Password({ message: "HRIS API token: " })

// Yes/No confirm — guard a raise that exceeds the pay band
const confirmAboveBand = Prompt.Confirm({
  message: "Salary exceeds band midpoint by > 20%. Proceed anyway?",
  initial: false
})

// Select from a list — choose a performance rating
const 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 recommendation
const approvalToggle = Prompt.Toggle({
  message: "Approve raise recommendation?",
  active: "approve",
  inactive: "reject",
  initial: true
})

// Multi-select — pick which comp components to adjust
const 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 wizard
const 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: " }))
)
```

### Built-in prompt types

Key APIs: Prompt.String, Prompt.Password, Prompt.Hidden, Prompt.Confirm, Prompt.Select, Prompt.AutoComplete, Prompt.MultiSelect, Prompt.Toggle, Prompt.Int, Prompt.Number, Prompt.Date, Prompt.List, Prompt.File, Prompt.Custom

> **Example:** The `employeeFlag` above accepts `--employee e-42`; when the flag is omitted, it asks for the employee id interactively.

### Theming prompts

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.

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

## HelpDoc

`effect/cli/HelpDoc` — unstable

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.

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

## Completions

`effect/cli/Completions` — unstable

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_completion
comp --completions zsh  >> ~/.zshrc
comp --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:

```ts
import { Completions } from "effect/cli"

// Usually derive the descriptor from the command tree itself — handlers never run:
//   Completions.generate("comp", "zsh", Completions.fromCommand(compCommand))
// A hand-written descriptor works too:
const descriptor: Completions.CommandDescriptor = {
  name: "comp",
  description: "Compensation administration CLI",
  flags: [
    {
      name: "format",
      aliases: ["-f"],
      description: "Output format",
      type: { _tag: "Choice", values: ["table", "json", "csv"] }
    }
  ],
  arguments: [],
  subcommands: [
    {
      name: "grant",
      description: "Grant equity to an employee",
      flags: [
        {
          name: "employee",
          aliases: ["-e"],
          description: "Employee ID",
          type: { _tag: "String" }
        },
        {
          name: "shares",
          aliases: ["-s"],
          description: "Number of RSU shares",
          type: { _tag: "Int" }
        },
        {
          name: "cliff",
          aliases: [],
          description: "Cliff period",
          type: { _tag: "String" }
        }
      ],
      arguments: [],
      subcommands: []
    },
    {
      name: "review",
      description: "Manage merit review cycles",
      flags: [],
      arguments: [],
      subcommands: [
        {
          name: "start",
          description: "Start a new merit review cycle",
          flags: [
            {
              name: "budget",
              aliases: [],
              description: "Approved merit budget in USD",
              type: { _tag: "Int" }
            }
          ],
          arguments: [],
          subcommands: []
        }
      ]
    }
  ]
}

const bashScript = Completions.generate("comp", "bash", descriptor)
const zshScript  = Completions.generate("comp", "zsh",  descriptor)
const fishScript = Completions.generate("comp", "fish", descriptor)
```

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`](#commandspec).

## CommandSpec

`effect/cli/CommandSpec` — unstable

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`](#completions) 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.

| `Spec` field | Contents |
| --- | --- |
| `path`, `name`, `alias`, `description`, `shortDescription`, `unlisted`, `annotations` | 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`](#flag). 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`.

```ts
import { Config, Context, Option } from "effect"
import { Command, CommandSpec, Flag } from "effect/cli"

const EnvVar = Context.Service<never, string>("docs/EnvVar")

const push = Command.make("push", {
  dbUrl: Flag.String("db-url").pipe(
    Flag.withFallbackConfig(Config.String("DB_URL")),
    Flag.annotate(EnvVar, "DB_URL")
  ),
  dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false))
})
const cli = Command.make("app").pipe(Command.withSubcommands([push]))

// One reference-table row per flag of `app push`, without running anything.
export const rows = Option.map(CommandSpec.resolve(cli, ["app", "push"], { builtIns: [] }), (spec) =>
  spec.flags.map((flag) => ({
    flag: `--${flag.name}`,
    type: flag.typeName,
    required: flag.required,
    env: Option.getOrUndefined(Context.getOption(flag.annotations, EnvVar)),
    default: flag.fallbacks.find((fallback) => fallback._tag === "Default")?.value
  }))
)
// Some([{ flag: "--db-url", type: "string", required: true, env: "DB_URL", default: undefined },
//       { flag: "--dry-run", type: "boolean", required: false, env: undefined, default: false }])
```

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

## GlobalFlag

`effect/cli/GlobalFlag` — unstable

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.

```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 command
const grantWithGlobals = grantCmd.pipe(
  Command.withGlobalFlags([licenseFlag, dryRunSetting])
)
```

### Built-in globals

| Flag | Type | Effect |
| --- | --- | --- |
| `--help / -h` | Action | Renders help doc and exits |
| `--version / -v` | Action | Prints `name version` and exits |
| `--wizard` | Action | 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.

## CliError

`effect/cli/CliError` — unstable

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`](#validating-input-across-flags) 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.

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

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

## CliOutput

`effect/cli/CliOutput` — unstable

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`](#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.

```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 tooling
const 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.

## TerminalCapabilities

`effect/cli/TerminalCapabilities` — unstable

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.

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

# Persistence

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.

## What each primitive guarantees

Pick the primitive from the guarantee you need, and read the right-hand column before relying on it.

| Primitive | Gives you | Does **not** give you |
| --- | --- | --- |
| `KeyValueStore` | Durable strings / bytes behind a swappable backend | Atomic read-modify-write, transactions across keys, typed values (add `toSchemaStore`) |
| `Persistence` | Schema-typed `Exit` values with TTL, shared by every process on the same backing store | Freshness: a stored `Exit` is replayed until it expires or is removed |
| `PersistedCache` | A lookup that survives restarts; concurrent gets for one key share one lookup **inside a process** | A fleet-wide single flight (two processes that both miss both run the lookup), or a source of truth |
| `PersistedQueue` | **At-least-once** processing with durable attempt counts, retry delays, and a dead-letter state | Exactly-once effects, ordering across retries, or atomicity with your domain tables — except through [the SQL store on a shared client](#using-the-sql-store-as-a-transactional-outbox) |
| `RateLimiter` | Atomic counters; shared across processes with the Redis store | Coordination with the memory store (it is node-local); availability or fairness guarantees from Redis itself |
| `CircuitBreaker` | Keyed Closed / Open / HalfOpen circuits that reject calls to a failing dependency; shared across processes with the Redis store | Retries, timeouts, or waiting — a rejected call fails at once; metrics or spans |
| `Redis` pub/sub | A wake-up signal | Delivery: messages published while a subscriber is away are gone |

## KeyValueStore

`effect/persistence/KeyValueStore` — unstable

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.

```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 layer
const 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
```

### Available layers

- **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`](#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.

## UserDirectories

`effect/persistence/UserDirectories` — unstable

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 `NotFound` `PlatformError`.

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

## Persistence

`effect/persistence/Persistence` — unstable

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.

```ts
import { Effect, Exit, Schema } from "effect"
import {
  Persistence,
  Persistable
} from "effect/persistence"

// A persistable request for fetching a CompBand by level
class 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 prod
const layers = Persistence.layerMemory
// Persistence.layerRedis       — needs Redis service
// Persistence.layerSql         — needs SqlClient
// Persistence.layerKvs         — needs KeyValueStore
```

### Backing layers

| Layer | Storage | Requires |
| --- | --- | --- |
| `Persistence.layerMemory` | 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.

## Persistable

`effect/persistence/Persistable` — unstable

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.

```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 request
const 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](./operations/caching-batching.md#requestresolver).

**Reach for it when** building a `PersistedCache` or using `RequestResolver.persisted` — schemas must be declared upfront so the persistence layer can serialize results.

## PersistedCache

`effect/persistence/PersistedCache` — unstable

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.

```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 fetch
declare 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 production
const 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.

## PersistedQueue

`effect/persistence/PersistedQueue` — unstable

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.

```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.layerStoreMemory
const 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.

### Using the SQL store as a transactional outbox

**`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](./interfaces/sql.md#external-effects-after-commit-outbox) without a hand-written relay.

```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](./recipes/transactional-write-with-outbox.md).

### Failure windows and honest guarantees

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

### Recovery testing and operations

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](./deep-dives/durability-and-distribution-ladder.md).

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

## RateLimiter

`effect/persistence/RateLimiter` — unstable

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.

```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 RateLimiterStore
const 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.

### Algorithms

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

## CircuitBreaker

`effect/persistence/CircuitBreaker` — experimental

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`](#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.timeout` *inside* it so it sees one outcome per call, and retry rejections *outside* it if you want to wait for the circuit.

```ts
// @effect-diagnostics experimentalApiUsage:off
import { 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](./interfaces/http-client.md).

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

## Redis

`effect/persistence/Redis` — unstable

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.

```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: RawClient

const 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.effect
const 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 counter
const 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.

# Testing & Dev Tooling

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](https://github.com/Effect-TS/effect/tree/effect%404.1.4/ai-docs/src) for executable examples across Effect. [`LLMS.md`](https://github.com/Effect-TS/effect/blob/effect%404.1.4/LLMS.md) is its generated single-file aggregate and begins with Effect's coding conventions.

> **Official guides:** [Devtools](https://effect.website/docs/v4/getting-started/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](./deep-dives/testing-an-effect-application.md) 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 | [`TestClock`](#testclock) inside `it.effect` | that a real driver, socket, or OS timer honors the same timing |
| A program writes the expected `Console.*` output | [`TestConsole`](#testconsole) | anything about `Effect.log*` records — capture those with a test `Logger` |
| A rule holds for every valid input | [`Arbitrary`](#arbitrary) via `it.effect.prop` | rejection of malformed wire input — generators produce valid decoded values |
| A codec decodes, encodes, and round-trips | [`TestSchema`](#testschema) | cross-field business rules the schema does not state |
| Orchestration, typed failures, interruption, cleanup | `it.effect` plus replacement Layers | the real adapter's behavior — a fake is not an adapter |
| An adapter works against a real dependency | `layer(L, { excludeTestServices: true })` or `it.live` | that the packaged entry point starts, serves, and shuts down |
| `E` and `R` are exactly what the contract says | `expectTypeOf` under the type checker | any runtime behavior |
| Editor, `tsc`, and CI agree on Effect-specific mistakes | [`@effect/tsgo`](#effect-language-service-effect-tsgo) | anything a test would have to run to observe |

## TestClock

`effect/testing/TestClock` — stable

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.

Key APIs: TestClock.adjust(duration), TestClock.setTime(timestamp), TestClock.withLive(effect), TestClock.layer(options?), TestClock.make(options?)

`@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](./deep-dives/testing-an-effect-application.md#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. |

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

Retry policies have their own home: [Recipe: Typed Retry with TestClock](./recipes/retry-with-test-clock.md) is a complete file, and [Schedule](./concurrency/scheduling-time.md#schedule) covers the policy combinators those tests exercise.

Use when code under test touches `Effect.sleep`, `Effect.timeout`, schedules, retry delays, or rate limiters.

Official guide: [TestClock](https://effect.website/docs/v4/testing/testclock).

## Deterministic crypto in tests

`effect/testing` has no crypto test service. Crypto is a set of family services in [`effect/crypto`](./interfaces/cryptography.md) — `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`).

```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`](./concurrency/scheduling-time.md#deterministic-testing).

## TestConsole

`effect/testing/TestConsole` — unstable

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.

```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](./deep-dives/testing-an-effect-application.md#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.

## Arbitrary

`effect/Arbitrary` — unstable

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.

```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 *unconstrained* `Schema.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.

### Shrinking, composition, and wire-side samples

```ts
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.FiniteFromString
const 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"]`:

```ts
import { Arbitrary, Effect, Schema } from "effect"

const reviewAction = Arbitrary.schema(Schema.Literals(["Approve", "Reject", "Reopen"]))
const reviewHistory = Arbitrary.array(reviewAction, { minLength: 1, maxLength: 20 })

// Property: once a raise is rejected, no later action approves it.
const rejectionSticks = Arbitrary.checkEffect(reviewHistory, (actions) => {
  const rejected = actions.indexOf("Reject")
  return rejected === -1 || !actions.slice(rejected + 1).includes("Approve")
}, { runs: 100, seed: 0 })

const _ = Effect.map(rejectionSticks, (result) => result._tag)
```

### What a derived generator cannot test

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`](#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](./deep-dives/schema-from-external-input-to-domain-and-back.md).

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:

```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](https://github.com/Effect-TS/effect/blob/effect%404.1.4/packages/effect/ARBITRARY.md) 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](https://effect.website/docs/v4/schema/arbitrary) (its `checkEffect` option list is shorter than this module's, which also accepts `size`, `maxDiscards`, `maxShrinks`, and `concurrency`).

## TestSchema

`effect/testing/TestSchema` — unstable

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.

```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 input
await dec.fail(42, 'Expected "exceeds" | "meets" | "below"')

// --- encoding a NumberFromString salary representation ---
const SalaryFromString = Schema.FiniteFromString
const 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.

## @effect/vitest

`@effect/vitest` — package

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`](#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.
- Everything else Vitest exports, including `expectTypeOf` for [type-level contract tests](#prove-laziness-and-the-static-contract).

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

```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`](#effect-language-service-effect-tsgo) 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 |

### Basic test shapes

```ts
import { assert, describe, it } from "@effect/vitest"
import { Effect, Fiber, Ref, Schedule } from "effect"
import { TestClock } from "effect/testing"

describe("comp-service: it.effect basics", () => {
  // Runs as an Effect. TestClock and TestConsole are provided automatically.
  it.effect("normalises employee names to title case", () =>
    Effect.gen(function*() {
      const names = ["ada lovelace", "grace hopper"].map((s) =>
        s.replace(/\b\w/g, (c) => c.toUpperCase())
      )
      assert.deepStrictEqual(names, ["Ada Lovelace", "Grace Hopper"])
    }))

  // Parameterized: it.effect.each accepts an array of cases.
  it.effect.each([
    { rating: "exceeds", multiplier: 1.07 },
    { rating: "meets",   multiplier: 1.03 },
    { rating: "below",   multiplier: 1.00 }
  ])("merit multiplier for rating %#", ({ rating, multiplier }) =>
    Effect.gen(function*() {
      const raise = (base: number) => base * multiplier
      assert.strictEqual(raise(100_000), 100_000 * multiplier)
    }))

  // it.live — uses real clock; useful for smoke-testing actual I/O timing.
  it.live("passes a minimal real-time smoke test", () =>
    Effect.gen(function*() {
      yield* Effect.sleep(1) // 1 ms of real sleep
      assert.isTrue(true)
    }))

  // Time-based test — TestClock is already active inside it.effect.
  it.effect("fast-forwards a vesting cliff without real waiting", () =>
    Effect.gen(function*() {
      const fiber = yield* Effect.forkChild(
        Effect.sleep("365 days").pipe(Effect.as("cliff-reached"))
      )
      yield* TestClock.adjust("365 days")
      assert.strictEqual(yield* Fiber.join(fiber), "cliff-reached")
    }))
})
```

### Prove laziness and the static contract

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.

```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`](#effect-language-service-effect-tsgo) 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.

### Sharing a layer across tests

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.

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

```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 | `TestClock.withLive(effect)` |
| A single smoke test of real runtime services | `it.live` |

### Property-based tests with `it.effect.prop`

```ts
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."

### In-memory test runtimes shipped with Effect

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.

| Harness | Keeps real | Replaces | Does not prove |
| --- | --- | --- | --- |
| [`HttpApiTest.groups`](./interfaces/http-api.md#httpapitest) (unstable) | request encoding, routing, middleware, response encoding, client decoding | the HTTP server and socket | that a server binds a port, negotiates TLS, or releases the port on shutdown |
| [`RpcTest.makeClient`](./interfaces/rpc.md#rpctest) (unstable) | client and server protocol machinery: streams, acknowledgements, interrupts, headers, middleware | transport **and serialization** | that payloads survive a real codec and wire |
| `NodeHttpServer.layerTest` | a real HTTP server on an ephemeral port plus a client pointed at it | the fixed address | deployment concerns: proxies, TLS, production configuration |
| [`TestRunner.layer`](./systems/cluster-sharding.md#testrunner) (unstable) | sharding, entity registration, mailbox persistence logic | storage (in-memory), runner transport (no-op), health checks | multi-runner rebalancing, durable storage behavior |
| [`McpTest.makeClient`](./systems/mcp.md) (unstable) | `McpServer` registrations, middleware, and the JSON-RPC wire encoding | the stdio or HTTP transport | that a real MCP client connects and negotiates the protocol over a socket or process |
| [`Entity.makeTestClient`](./systems/cluster-sharding.md#entity) (unstable) | 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 |
| `WorkflowEngine.layerMemory`, `Persistence.layerMemory`, `KeyValueStore.layerMemory`, `EventJournal.layerMemory` (unstable) | the orchestration or storage *contract* | the durable backend | 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 language service (@effect/tsgo)

`@effect/tsgo` — external package ([Effect-TS/tsgo](https://github.com/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 hints
npx @effect/tsgo setup
# Non-interactive flags, for scripts and coding agents
npx @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:

```json
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "@effect/language-service",
        "includeSuggestionsInTsc": true,
        "ignoreEffectWarningsInTscExitCode": false,
        "ignoreEffectErrorsInTscExitCode": false,
        "diagnosticSeverity": { "floatingEffect": "error" }
      }
    ]
  }
}
```

| Surface | How | Notes |
| --- | --- | --- |
| Editor | 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 **unpatched** `tsc` 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:

| Group | Examples (default severity) | What it catches |
| --- | --- | --- |
| Correctness | `floatingEffect`, `floatingEffectInVitest`, `missingEffectContext`, `missingEffectError`, `missingLayerContext`, `missingStarInYieldEffectGen` (all `error`); `duplicatePackage`, `outdatedApi` (`warning`); `unsafeEffectTypeAssertion` (`off`) | 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` |
| Anti-pattern | `multipleEffectProvide`, `layerMergeAllWithDependencies`, `globalErrorInEffectFailure` (`warning`); `catchUnfailableEffect`, `runEffectInsideEffect`, `tryCatchInEffectGen`, `leakingRequirements` (`suggestion`) | 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 |
| Effect-native | `globalDateInEffect`, `globalTimersInEffect`, `globalRandomInEffect`, `globalFetchInEffect`, `processEnvInEffect`, `globalConsoleInEffect` (all `off`) | 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. |
| Style | `unnecessaryEffectGen`, `catchAllToMapError`, `effectFnOpportunity`, `schemaStructWithTag` (`suggestion`); `missingConcurrencyOption`, `forLoopPushToForEach` (`off`) | 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`](#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](./foundations/getting-started.md) covers the project setup around it.

Use when you want the mistakes in [Troubleshooting & Anti-Patterns](./troubleshooting/troubleshooting-and-anti-patterns.md) reported by the compiler instead of discovered in review.

**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`](./interfaces/graphql.md#graphql-generator), `@effect/docgen`, and `@effect/doctest`; the rest of the list below is repository-internal.

## @effect/docgen

`@effect/docgen` — package

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

```json
{
  "$schema": "node_modules/@effect/docgen/schema.json",
  "srcDir": "src",
  "outDir": "docs",
  "exclude": ["src/internal/**/*.ts"],
  "enforceDescriptions": true,
  "enforceExamples": true,
  "enforceVersion": true
}
```

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.

## @effect/doctest

`@effect/doctest` — package

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.

<!-- effect-example id=tooling.doctest.run check=run runtime=doctest -->
```ts import.meta.vitest name="runs Effect values explicitly"
import { Effect } from "effect"

Effect.runSync(Effect.succeed(42)) // => 42
```

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

# Cheat Sheet & Index

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.

## The house style, distilled

```ts
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.

## Start here

| You are… | Go to |
| --- | --- |
| Installing Effect 4, configuring TypeScript, or writing a first program | [Getting Started](./foundations/getting-started.md) |
| Choosing between primitives that all look plausible | [Choosing Effect Primitives](./reference/choosing-effect-primitives.md) |
| Looking at a symptom, or checking generated code against known mistakes | [Troubleshooting & Anti-Patterns](./troubleshooting/troubleshooting-and-anti-patterns.md) |
| Reviewing a design or a diff | [Review Checklists](./reference/review-checklists.md) |
| Coming from Effect 3 | [Migration guide](https://github.com/Effect-TS/effect/blob/effect%404.1.4/MIGRATION.md) |
| Moving an existing Promise codebase over, one leaf at a time | [Adopting Effect in an Existing TypeScript Codebase](./deep-dives/adopting-effect-in-an-existing-codebase.md) |
| Wanting a connected walkthrough rather than a lookup | [Deep Dives](./deep-dives/index.md) |

## When several primitives look right

The companion [Choosing Effect Primitives](./reference/choosing-effect-primitives.md) 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 | [Boundary rules before primitives](./reference/choosing-effect-primitives.md#boundary-rules-before-primitives) |
| Which constructor wraps this JavaScript | [Constructor by source convention](./reference/choosing-effect-primitives.md#constructor-by-source-convention) |
| Which runner the host needs | [Runner by host contract](./reference/choosing-effect-primitives.md#runner-by-host-contract) |
| Absence, pure failure, a recorded outcome, or effectful work | [`Option` vs `Result` vs `Effect`](./reference/choosing-effect-primitives.md#option-vs-result-vs-effect) |
| Which recovery operator expresses the intent | [Recovery operator by intent](./reference/choosing-effect-primitives.md#recovery-operator-by-intent) |
| Stop at the first failure or collect them all | [Fail fast or accumulate](./reference/choosing-effect-primitives.md#fail-fast-or-accumulate) |
| `provideService`, a Layer, `{ local: true }`, or `Layer.fresh` | [Providing dependencies by seam](./reference/choosing-effect-primitives.md#providing-dependencies-by-seam) |
| Which fork, by who owns the fiber | [Fork by owner](./reference/choosing-effect-primitives.md#fork-by-owner) |
| Which bracket, by how long the resource lives | [Resource lifetime and bracket](./reference/choosing-effect-primitives.md#resource-lifetime-and-bracket) |
| One cell, effectful update, live changes, or atomic multi-value state | [`Ref` vs `SynchronizedRef` vs `SubscriptionRef` vs transactions](./reference/choosing-effect-primitives.md#ref-vs-synchronizedref-vs-subscriptionref-vs-transactions) |
| One result, a gate, worker handoff, or broadcast | [`Deferred` vs `Latch` vs `Queue` vs `PubSub`](./reference/choosing-effect-primitives.md#deferred-vs-latch-vs-queue-vs-pubsub) |
| Wait, shed, keep the latest, or grow without bound | [Overload semantics at a glance](./reference/choosing-effect-primitives.md#overload-semantics-at-a-glance) |
| Local parallelism, a shared permit budget, or reusable objects | [Per-call concurrency vs `Semaphore` vs `Pool`](./reference/choosing-effect-primitives.md#per-call-concurrency-vs-semaphore-vs-pool) |
| One effect repeated, one key repeated, or many keys at once | [Single-flight, cache, or batching](./reference/choosing-effect-primitives.md#single-flight-cache-or-batching) |
| Cached values, cached resources, refresh, or batching | [`Cache` vs `ScopedCache` vs `Resource` vs `RequestResolver`](./reference/choosing-effect-primitives.md#cache-vs-scopedcache-vs-resource-vs-requestresolver) |
| Finite collections or incremental protocols | [`Array`/`Chunk`/`Iterable` vs `Stream`/`Sink`/`Channel`](./reference/choosing-effect-primitives.md#array-chunk-iterable-vs-stream-sink-channel) |
| Buffer depth, batch size, or rate | [Stream buffering and batching operators](./reference/choosing-effect-primitives.md#stream-buffering-and-batching-operators) |
| JSON, NDJSON, SSE, or schema-derived binary frames | [Wire codec: JSON, NDJSON, or SchemaBinary](./reference/choosing-effect-primitives.md#wire-codec-json-ndjson-or-schemabinary) |
| Outbound HTTP, low-level routing, contract HTTP, or procedures | [`HttpClient` vs `HttpRouter` vs `HttpApi` vs RPC](./reference/choosing-effect-primitives.md#httpclient-vs-httprouter-vs-httpapi-vs-rpc) |
| Failed attempts, successful repetition, polling, or restart survival | [Retry vs repeat vs polling vs Workflow](./reference/choosing-effect-primitives.md#retry-vs-repeat-vs-polling-vs-workflow) |
| Durable state, history, orchestration, or distributed identity | [Persistence vs EventLog vs Workflow vs Cluster](./reference/choosing-effect-primitives.md#persistence-vs-eventlog-vs-workflow-vs-cluster) |
| Which test tool proves which claim | [Test tool by claim](./reference/choosing-effect-primitives.md#test-tool-by-claim) |
| Who owns the runtime and what cancels work | [Host and runtime ownership](./reference/choosing-effect-primitives.md#host-and-runtime-ownership) |

## What to reach for when…

### Build and run

| You want to… | Reach for |
| --- | --- |
| Run async/fallible code with typed errors | [`Effect`](./foundations/core-runtime-execution.md#effect) (`tryPromise`, `callback`, `gen`, `fn`) |
| Wrap a Promise or callback API so that a timeout really cancels it | [Cancellable adapters](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks): forward the `signal` |
| Branch or loop (there is no `Effect.if`, `unless`, or `loop`) | [plain `if` / `for` in `Effect.gen`, `Effect.when`](./foundations/core-runtime-execution.md#9-branching-and-looping) |
| Run an effect from a host, keeping cancellation distinct | [`runPromiseExit` with `{ signal }`](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge) |
| Call Effect from Express, Hono, a UI, or a plugin API | [`ManagedRuntime`](./foundations/fibers-scopes-runtimes.md#managedruntime), the [ManagedRuntime recipe](./recipes/managed-runtime-integration.md), and its [production-shaped bridge](./recipes/managed-runtime-integration.md#a-production-shaped-bridge) |
| Carry a host request's abort through to the SDK call | [Recipe: Request Cancellation Through a Host](./recipes/request-cancellation-through-a-host.md) |
| Start a process and shut it down gracefully | [platform `runMain`](./foundations/fibers-scopes-runtimes.md#runtime), the [graceful entrypoint recipe](./recipes/graceful-entrypoint-and-shutdown.md), and [readiness plus a bounded drain](./recipes/graceful-entrypoint-and-shutdown.md#adding-readiness-and-a-bounded-drain) |
| Choose the host: process, Web handler, framework callback, browser, worker, test | [Choosing a host](./interfaces/platform-runtime-hosts.md#choosing-a-host) |
| Fall back across providers or models | [`ExecutionPlan`](./foundations/core-runtime-execution.md#executionplan) |

### Fail and recover

| You want to… | Reach for |
| --- | --- |
| Decide whether an outcome is a result, a typed failure, or a defect | [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model) |
| Recover from some failures and leave the rest typed | [`catchTag`, `catchIf`, `catchFilter`, `catchReason`](./foundations/errors-option-result.md#selective-recovery-beyond-one-tag) |
| Translate an error, or fail an unacceptable success | [`mapError`, `filterOrFail`](./foundations/errors-option-result.md#transforming-the-error-channel) |
| Turn every outcome into one response | [`Effect.match` / `matchEffect`](./foundations/errors-option-result.md#folding-both-channels-at-a-boundary) |
| Collect every validation problem | [`Effect.validate`, `Effect.partition`, `mode: "result"`](./foundations/errors-option-result.md#accumulating-errors-instead-of-failing-fast) |
| Map an error union to statuses or policies exhaustively | [`Match.exhaustive` / `tagsExhaustive`](./foundations/errors-option-result.md#classifying-an-error-union) |
| Keep a defect that sits beside a typed failure | [a guarded `catchCause`](./foundations/fibers-scopes-runtimes.md#recovering-from-a-mixed-cause) |
| Move between `Option`, `Result`, and `Effect` (they are not yieldable) | [`Effect.fromOption`, `Effect.fromResult`](./foundations/errors-option-result.md#moving-between-option-result-and-effect) |
| Decide what a failed cleanup means | [When cleanup can fail](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail) |
| Undo partial in-process work | [exit-aware finalizers](./deep-dives/failure-retry-fallback-and-interruption.md#roll-back-partial-work-with-exit-aware-finalizers) |
| Combine retry with a timeout | [Where the timeout sits relative to retry](./deep-dives/failure-retry-fallback-and-interruption.md#where-the-timeout-sits-relative-to-retry) |
| Report defects at the process edge | [`ErrorReporter`](./foundations/errors-option-result.md#errorreporter) |

### Depend and configure

| You want to… | Reach for |
| --- | --- |
| Inject a dependency | [`Context.Service` + `Layer`](./foundations/services-context-layers.md) and the [service recipe](./recipes/service-and-layers.md) |
| Shape a service contract (`R = never`, no throws, domain verbs) | [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract) |
| Provide one fake in a test without building a Layer | [`Effect.provideService`](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph) |
| Know whether a pool is shared or rebuilt | [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt) |
| Own a connection or client for the application's lifetime | [Resourceful services](./foundations/services-context-layers.md#resourceful-services) |
| Use a capability only if the host installed it | [`Effect.serviceOption`](./foundations/services-context-layers.md#optional-services) |
| Ambient, override-able settings | [`Context.Reference` / `References`](./foundations/services-context-layers.md#references) and the [default services](./foundations/services-context-layers.md#default-services) |
| Keep a value fresh in the background | [`Resource`](./foundations/services-context-layers.md#resource) |
| One Layer per tenant or key | [`LayerMap`](./foundations/services-context-layers.md#layermap) |
| Read config / hide secrets | [`Config` + `ConfigProvider` / `Redacted`](./foundations/configuration-secrets.md) (PascalCase constructors: `Config.String`, `Config.Int`, `Config.Redacted`, `Config.Duration`, `Config.URL`) |
| Define what a valid deployment looks like, once | [Designing the startup contract](./foundations/configuration-secrets.md#designing-the-startup-contract) |
| Default a setting without hiding a typo | [`Config.withDefault`, not `Config.orElse`](./foundations/configuration-secrets.md#absence-is-not-malformed-input) |
| Layer CLI overrides over environment over defaults | [Precedence and composition](./foundations/configuration-secrets.md#precedence-and-composition) |
| Decode a secret from a payload without ever encoding it back | [`Schema.RedactedFromValue` with `disallowEncode`](./foundations/configuration-secrets.md#secrets-that-arrive-through-a-schema) |

### Own lifetimes and fibers

| You want to… | Reach for |
| --- | --- |
| Fork work with the right owner | [Choosing a fork by its owner](./foundations/fibers-scopes-runtimes.md#choosing-a-fork-by-its-owner) |
| Make sure a forked listener is registered before you publish | [`{ startImmediately: true }`](./foundations/fibers-scopes-runtimes.md#when-a-forked-fiber-starts) |
| Coordinate fibers | [`Deferred`, `Latch`, `Fiber`, `FiberHandle`/`Map`/`Set`](./foundations/fibers-scopes-runtimes.md#fiber) |
| List every long-lived thing with its owner, bound, and release | [the ownership ledger](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md#write-the-ownership-ledger-first) |
| Start up all-or-nothing; separate liveness, readiness, and draining | [Owning Lifetimes — Startup, Readiness, and Shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md) |
| Run a heartbeat only while the main task runs | [`Effect.raceFirst`](./concurrency/scheduling-time.md#running-a-side-task-for-as-long-as-the-main-task-runs) |
| Run a worker with bounded admission and a drain | [the bounded-worker recipe](./recipes/resource-safe-bounded-worker.md) and [deep dive](./deep-dives/structured-concurrency-through-a-bounded-worker.md) |

### Coordinate, share state, and stream

| You want to… | Reach for |
| --- | --- |
| Cap concurrency | [`Semaphore`, `PartitionedSemaphore`](./concurrency/concurrency-coordination.md#semaphore), or the `{ concurrency }` option |
| Hand work to workers with backpressure | [`Queue`](./concurrency/concurrency-coordination.md#queue), with [roles in signatures](./concurrency/concurrency-coordination.md#put-queue-roles-in-function-signatures) and an explicit [lifecycle](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does) |
| Fan events out to every subscriber | [`PubSub`](./concurrency/concurrency-coordination.md#pubsub) and its [delivery semantics](./concurrency/concurrency-coordination.md#delivery-semantics-queue-or-pubsub) |
| Shed load deliberately and count it | [Make loss observable](./concurrency/concurrency-coordination.md#make-loss-observable) |
| Share expensive connections | [`Pool`](./concurrency/concurrency-coordination.md#pool) |
| Hold shared state | [`Ref` / `SynchronizedRef`; reactive → `SubscriptionRef`](./concurrency/state-mutable-references.md), always as [one transition per call](./concurrency/state-mutable-references.md#one-transition-one-call) |
| Mutate several pieces of state atomically | [STM: `TxRef` and friends](./concurrency/software-transactional-memory.md), run with `Effect.tx` |
| Process a sequence or stream over time | [`Stream` + `Sink` + `Channel`](./concurrency/streaming-channels.md) |
| Merge, zip, partition, or broadcast streams | [Combining and splitting streams](./concurrency/streaming-channels.md#4-combining-and-splitting-streams) |
| Recover, retry, or time out a stream | [Handling stream failures](./concurrency/streaming-channels.md#5-handling-stream-failures) |
| Keep a file or cursor open exactly as long as a stream is consumed | [`Stream.unwrap` over a scoped acquisition](./concurrency/streaming-channels.md#6-owning-resources-inside-a-stream) |
| Find every place a pipeline buffers | [Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides) |
| Batch by size or time | [`Stream.grouped` / `groupedWithin`](./concurrency/streaming-channels.md#2-transforming-streams), [`Stream.transduce`](./concurrency/streaming-channels.md#adapting-leftovers-and-repeatable-batching) |
| Frame bytes on a socket or file | [`Ndjson`](./concurrency/streaming-channels.md#ndjson), [`Sse`](./concurrency/streaming-channels.md#sse), [`SchemaBinary`](./concurrency/streaming-channels.md#schemabinary) |
| Import a large file without buffering it | [Streaming Ingestion Without Accidental Buffering](./deep-dives/streaming-ingestion-without-accidental-buffering.md) |

### Time and scheduling

| You want to… | Reach for |
| --- | --- |
| Retry, repeat, or poll | [`Schedule` + `Duration` + `Cron`](./concurrency/scheduling-time.md), the [retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist), and the [`{ schedule, while, until, times }` options](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat) |
| See the delays a composed schedule will produce | [`Schedule.toStep`](./concurrency/scheduling-time.md#inspecting-a-schedule) |
| Prove a retry policy's shape | [Testing a policy](./concurrency/scheduling-time.md#testing-a-policy) and the [TestClock recipe](./recipes/retry-with-test-clock.md) |
| Work with time correctly | [`DateTime` + `Clock`](./concurrency/scheduling-time.md#datetime) (never `Date.now`) |
| Parse a duration from config or a payload | [`Config.Duration`, `Schema.DurationFromString`](./concurrency/scheduling-time.md#parsing-untrusted-durations-and-interop-edges) |
| Build a zoned time from wall-clock input; format for people | [Constructing zoned values](./concurrency/scheduling-time.md#constructing-zoned-values-from-wall-clock-input), [Formatting](./concurrency/scheduling-time.md#formatting) |
| Build a cron expression from fields | [`Cron.make`](./concurrency/scheduling-time.md#building-a-cron-from-structured-fields) |

### Data and boundaries

| You want to… | Reach for |
| --- | --- |
| Validate / parse / encode data | [`Schema` + `JsonSchema`](./data/schema.md) and the [Schema deep dive](./deep-dives/schema-from-external-input-to-domain-and-back.md) |
| Pick the decode runner | [by who consumes the failure](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) |
| Reject or strip unknown keys, collect all issues | [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy) |
| Model an optional, nullable, or `Option` field | [Optional fields, null, and Option](./data/schema-in-depth.md#6-optional-fields-null-and-option) |
| Put `Option`, `Result`, `Exit`, `Duration`, maps, sets, or `Redacted` on the wire | [Effect data types at the boundary](./data/schema-in-depth.md#7-effect-data-types-at-the-boundary) |
| Write human-readable validation messages | [Custom error messages](./data/schema-in-depth.md#8-custom-error-messages) |
| Validate against a service (uniqueness, lookup) | [Effectful schemas and services](./data/schema-in-depth.md#9-effectful-schemas-and-services) |
| Hand a schema to a form library or router | [`Schema.toStandardSchemaV1`](./data/schema-tooling.md#standardschema) |
| Generate JSON Schema (open objects by default) | [`JsonSchema`](./data/schema-tooling.md#jsonschema) |
| Pattern-match exhaustively | [`Match`](./data/functional-toolkit.md#match) and [how to close a matcher](./data/functional-toolkit.md#closing-a-matcher) |
| Compare or hash values structurally | [`Equal`](./data/functional-toolkit.md#equal) and its [pitfalls](./data/functional-toolkit.md#equality-pitfalls-and-opt-outs) |
| Deeply update immutable data | [`Optic`](./data/functional-toolkit.md#optic) |
| Branded / nominal types | [`Brand` + `Newtype`](./data/functional-toolkit.md#brand) |
| Exact decimal math (money) | [`BigDecimal`](./data/functional-toolkit.md#bigdecimal) |
| Exact byte counts and size limits | [`ByteSize`](./data/functional-toolkit.md#bytesize) (replaces `FileSystem.MiB` and friends) |
| Model and analyze a graph (org chart, approval chain) | [`Graph`](./data/data-structures.md#graph) and its [witnesses, reductions, and matchings](./data/data-structures.md#witnesses-reductions-and-matchings) |

### Interfaces

| You want to… | Reach for |
| --- | --- |
| Call an HTTP API | [`HttpClient`](./interfaces/http-client.md), with [budgets and safe retries](./interfaces/http-client.md#retries-time-budgets-and-cancellation) and [three failure classes](./interfaces/http-client.md#three-failure-classes) |
| Fetch a URL a user supplied | [User-controlled destinations](./interfaces/http-client.md#user-controlled-destinations) |
| Call an existing GraphQL API with typed operations and subscriptions | [GraphQL](./interfaces/graphql.md) and [`@effect/graphql-generator`](./interfaces/graphql.md#graphql-generator) (experimental; not a server executor) |
| Build a contract-first HTTP API | [`HttpApi`](./interfaces/http-api.md), its [status mapping](./interfaces/http-api.md#status-mapping-is-part-of-the-contract), and [authentication vs authorization](./interfaces/http-api.md#authentication-is-not-authorization) |
| Serve HTTP and set edge limits | [`HttpServer`](./interfaces/http-server.md#httpserver) and the [edge policy checklist](./interfaces/http-server.md#edge-policy-checklist) |
| Work with status codes and media types | [`HttpStatus`](./interfaces/http-server.md#httpstatus), [`Mime`](./interfaces/http-server.md#mime) |
| Typed client⇄server calls | [the RPC modules](./interfaces/rpc.md), [contract evolution](./interfaces/rpc.md#evolving-a-contract), and [operational defaults](./interfaces/rpc.md#operational-defaults) |
| Talk to a database | [the SQL modules](./interfaces/sql.md) (`SqlClient`, `SqlModel`) and [where SQL belongs](./interfaces/sql.md#where-sql-belongs-in-an-application) |
| Write state and an external effect atomically | [the outbox](./interfaces/sql.md#external-effects-after-commit-outbox) and [Recipe: A Transactional Write with an Outbox](./recipes/transactional-write-with-outbox.md) |
| Give a repository one stable error | [Normalizing errors at a repository boundary](./interfaces/sql.md#normalizing-errors-at-a-repository-boundary) |
| Run migrations and operate pools in production | [Operating migrations](./interfaces/sql.md#operating-migrations), [Operating SQL in production](./interfaces/sql.md#operating-sql-in-production) |
| Upgrade `@effect/sql-pg` | [Upgrading to the native client](./interfaces/sql.md#native-client-behavior-codecs-json-and-listen) |
| Go end to end from Schema to HttpApi to SQL | [the boundary recipe](./recipes/schema-httpapi-sql-boundary.md) |
| Files, sockets, workers, child processes | [Platform & Runtime Hosts](./interfaces/platform-runtime-hosts.md); sockets are pull-based (`reader` / `writer`) |
| Parse and match IP addresses and networks | [`NetAddress`](./interfaces/platform-runtime-hosts.md#netaddress), [`IpNetwork`](./interfaces/platform-runtime-hosts.md#ipnetwork), [`IpInterface`](./interfaces/platform-runtime-hosts.md#ipinterface) |
| Parse host names, query DNS, or resolve endpoints | [`Host`, `Dns`, `AddressResolver`](./interfaces/platform-runtime-hosts.md#host) (experimental; DNS validation alone does not prevent SSRF) |
| Send or receive UDP datagrams | [`DatagramSocket`](./interfaces/platform-runtime-hosts.md#datagramsocket) (experimental; not a byte stream) |
| Test file code without a disk | [`FileSystem.layerNoop`](./interfaces/platform-runtime-hosts.md#testing-without-a-disk) |

### Operate

| You want to… | Reach for |
| --- | --- |
| Logs, traces, metrics (+ export) | [`Logger` / `Tracer` / `Metric` + exporters](./operations/observability.md) and the [production observability recipe](./recipes/production-observability.md) |
| Decide which signal to add, and bound its cardinality | [Designing signals](./operations/observability.md#designing-signals) |
| Swap the log format without losing log-to-span correlation | [Installing and swapping loggers](./operations/observability.md#installing-and-swapping-loggers) |
| Set the minimum log level from config, or for one operation | [Scoping and configuring the minimum level](./operations/observability.md#scoping-and-configuring-the-minimum-level) |
| Count, time, and gauge an effect without touching its body | [`Effect.track*`](./operations/observability.md#tracking-effects-with-metrics), [lifetime gauges](./operations/observability.md#gauges-that-follow-a-lifetime) |
| Choose OTLP, the OpenTelemetry SDK, or Prometheus | [Choosing and owning an export path](./operations/telemetry-export.md#choosing-and-owning-an-export-path) |
| Memoize one expensive effect | [`Effect.cached` / `cachedWithTTL`](./operations/caching-batching.md#caching-a-single-effect) |
| Memoize expensive lookups by key | [`Cache` / `ScopedCache`](./operations/caching-batching.md), with a [failure TTL](./operations/caching-batching.md#failure-and-freshness-policy) |
| Kill N+1 queries (batch) | [`Request` + `RequestResolver`](./operations/caching-batching.md#request) (or [`SqlResolver`](./interfaces/sql.md#sqlresolver)), honoring the [resolver obligations](./operations/caching-batching.md#resolver-obligations) |

### Durable and distributed systems

| You want to… | Reach for |
| --- | --- |
| Persist across restarts | [`KeyValueStore`, `PersistedQueue`, `PersistedCache`](./tooling/persistence.md), after reading [what each guarantees](./tooling/persistence.md#what-each-primitive-guarantees) |
| Process durable jobs at least once | [`PersistedQueue`](./tooling/persistence.md#persistedqueue) (retry policy lives on `make`) and its [failure windows](./tooling/persistence.md#failure-windows-and-honest-guarantees) |
| Run a durable, resumable process | [`Workflow`](./systems/workflows-durable-execution.md), with [replay and versioning rules](./systems/workflows-durable-execution.md#replay-versioning-and-rollout) |
| Distribute stateful entities | [the cluster modules](./systems/cluster-sharding.md), their [transport options](./systems/cluster-sharding.md#transport-options) and [capacity limits](./systems/cluster-sharding.md#capacity-limits-and-their-defaults) |
| Event-source / local-first sync | [the event-log modules](./systems/event-log-event-sourcing.md) |
| Decide how much durability the problem needs | [The Durability and Distribution Ladder](./deep-dives/durability-and-distribution-ladder.md) |
| Reactive UI state | [`Atom` + framework bindings](./systems/reactivity-atom.md), or the [deep dive](./deep-dives/reactivity-from-atoms-to-mastery.md) |
| Call an LLM (provider-agnostic) | [`LanguageModel` + an `@effect/ai-*` provider](./systems/ai-language-models.md), under the [production rules](./systems/ai-language-models.md#production-rules-for-model-calls) |
| Gate tool calls behind approval, or bound their concurrency | [Tool-call resolution](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch) |
| Expose tools over MCP | [`McpServer`](./systems/mcp.md#mcpserver) |
| Host MCP on a serverless request lifetime | [`layerHttpRequestScoped`](./systems/mcp.md#request-scoped-http-and-typed-requirements) (stateless adapters only) |
| Ship an AI feature with budgets, gates, and tests | [Building a Production AI Capability](./deep-dives/building-a-production-ai-capability.md) |

### Test and tool

| You want to… | Reach for |
| --- | --- |
| Test effects deterministically | [`@effect/vitest` + `TestClock`](./tooling/testing-dev-tooling.md) and [Testing an Effect Application](./deep-dives/testing-an-effect-application.md) |
| Seed random bytes and IDs without faking digests | A seeded [`SecureRandom`](./tooling/testing-dev-tooling.md#deterministic-crypto-in-tests) layer beside the host digest layer |
| Property-test from a Schema | [`Arbitrary`](./tooling/testing-dev-tooling.md#arbitrary) (`effect/Arbitrary`; the fast-check bridge was removed) |
| Know what an in-memory harness does *not* prove | [In-memory test runtimes shipped with Effect](./tooling/testing-dev-tooling.md#in-memory-test-runtimes-shipped-with-effect) |
| Test laziness and the exact `E` and `R` | [Prove laziness and the static contract](./tooling/testing-dev-tooling.md#prove-laziness-and-the-static-contract) |
| Capture `Effect.log*` records or spans in a test | [a test Logger](./deep-dives/testing-an-effect-application.md#capture-effect-log-records-with-a-test-logger), [structural span tests](./deep-dives/testing-an-effect-application.md#test-spans-structurally) |
| Audit a green suite for false greens | [When green means nothing](./deep-dives/testing-an-effect-application.md#when-green-means-nothing) |
| Catch floating Effects and removed APIs in the editor and CI | [`@effect/tsgo`](./tooling/testing-dev-tooling.md#effect-language-service-effect-tsgo) and [diagnostics setup](./foundations/getting-started.md#effect-diagnostics-in-the-editor-and-in-ci) |
| Build a command-line app | [the CLI modules](./tooling/cli-framework.md) (PascalCase constructors; boolean flags need `Flag.withDefault(false)`), and [testing a command](./tooling/cli-framework.md#testing-a-command) |

## Recipes and deep dives by task

| Task | Recipe (one complete file) | Deep dive (connected walkthrough) |
| --- | --- | --- |
| Define a service with live and test Layers | [Service and Layers](./recipes/service-and-layers.md) | [Anatomy of a Real Effect Application](./deep-dives/anatomy-of-a-real-effect-application.md) |
| Decode a request, serve it, store it | [Schema to HttpApi to SQL](./recipes/schema-httpapi-sql-boundary.md) | [Schema — From External Input to Domain and Back](./deep-dives/schema-from-external-input-to-domain-and-back.md) |
| Bounded, resource-safe background work | [Resource-Safe Bounded Worker](./recipes/resource-safe-bounded-worker.md) | [Structured Concurrency Through a Bounded Worker](./deep-dives/structured-concurrency-through-a-bounded-worker.md) |
| Classified retry, proven with virtual time | [Typed Retry with TestClock](./recipes/retry-with-test-clock.md) | [Failure, Retry, Fallback, and Interruption](./deep-dives/failure-retry-fallback-and-interruption.md) |
| Logs, traces, and metrics wired for production | [Production Observability](./recipes/production-observability.md) | — |
| A process that starts, serves, and stops cleanly | [Graceful Node Entrypoint](./recipes/graceful-entrypoint-and-shutdown.md) | [Owning Lifetimes — Startup, Readiness, and Shutdown](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md) |
| Effect inside a framework you do not control | [ManagedRuntime at an Imperative Boundary](./recipes/managed-runtime-integration.md), [Request Cancellation Through a Host](./recipes/request-cancellation-through-a-host.md) | [Adopting Effect in an Existing TypeScript Codebase](./deep-dives/adopting-effect-in-an-existing-codebase.md) |
| A database write plus an external effect | [Transactional Write with an Outbox](./recipes/transactional-write-with-outbox.md) | [The Durability and Distribution Ladder](./deep-dives/durability-and-distribution-ladder.md) |
| Large imports and live feeds | — | [Streaming Ingestion Without Accidental Buffering](./deep-dives/streaming-ingestion-without-accidental-buffering.md) |
| A test strategy for a whole service | — | [Testing an Effect Application](./deep-dives/testing-an-effect-application.md) |
| Reactive UI state | — | [Reactivity — From Atoms to Mastery](./deep-dives/reactivity-from-atoms-to-mastery.md) |
| An LLM feature with tools and budgets | — | [Building a Production AI Capability](./deep-dives/building-a-production-ai-capability.md) |
| An MCP server other agents can call, with auth and approvals | [`McpServer`](./systems/mcp.md#mcpserver) | [Exposing an Effect Application over MCP](./deep-dives/exposing-an-effect-application-over-mcp.md) |

> **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](./index.md#stability-and-support) for the distinctions. Pin exact versions, read the changelog, and keep each unstable or experimental import [behind one app-owned capability](./interfaces/platform-runtime-hosts.md#keep-platform-and-unstable-imports-behind-a-capability).

# Using the Handbook from an Agent

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.

## The one rule: fetch Markdown, never HTML

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:

1. Read the installed version from `node_modules/effect/package.json`.
2. Take its `major.minor` and fetch that edition's `llms.txt`, for example `/4.0/llms.txt` for `effect@4.0.3`.
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.
4. State the edition and audited release you used when you answer.
5. Upgrading, or reading code written against an older pin? Read the [Release History](./reference/release-history.md) 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.

## Which artifact to fetch for which task

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. |
| Decide between two or three similar tools | [Choosing Effect Primitives](./reference/choosing-effect-primitives.md) | 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) | `effect-4-catalog.json`, `effect-4-examples.json`, `effect-4-modules.json` | Stable ids, task aliases, selection boundaries, and every example's disposition and hash. |
| Diagnose a compiler error or runtime symptom | [Troubleshooting](./troubleshooting/troubleshooting-and-anti-patterns.md); for code to search for, [Generated-Code Anti-Patterns](./troubleshooting/anti-patterns.md) | 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.

## Reading the capability catalog

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

## Reading the example inventory

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

## Citing and quoting

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.

## When the handbook is not enough

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:

1. **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.
2. **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/`.
3. **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.
4. **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.

## Drop-in instructions for your agent

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 reference

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

## What the generated artifacts are

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

# Release History

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](https://github.com/Effect-TS/effect) 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](./reference/agent-guide.md#match-the-edition-to-the-installed-effect-version)); a patch release updates its edition in place and gets its own entry here.

## `effect@4.1.4` — audited 2026-11-19

Edition **4.1** (patch update; full source audit). Tag [`effect@4.1.4`](https://github.com/Effect-TS/effect/tree/effect%404.1.4), commit [`289a53f7`](https://github.com/Effect-TS/effect/commit/289a53f7b1fc40049219c6e69022db2fb859c356), 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.

### Changes in Effect that matter to readers

**New public surfaces and stability**

- No existing module changed its module-level `@stability`. New modules and packages:
  - unstable: root `Rational`; `effect/encoding` `Json5` 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/ai` `AgUi`, `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](./index.md#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](https://github.com/Effect-TS/effect/pull/9883)). See [JOSE: tokens and keys](./interfaces/cryptography.md#jose-tokens-and-keys).
- **Exact fractions:** `Rational`, with `Schema.Rational`, `Schema.RationalFromString`, and `SchemaRepresentation.RationalReviver` ([#9990](https://github.com/Effect-TS/effect/pull/9990)). See [Rational](./data/functional-toolkit.md#rational).
- **Configuration formats:** `Json5.parse` and `Jsonc.parse` return `Result<unknown, EncodingError>` ([#9972](https://github.com/Effect-TS/effect/pull/9972)). See [Json5](./concurrency/streaming-channels.md#json5) and [Jsonc](./concurrency/streaming-channels.md#jsonc).
- **OpenRPC:** `OpenRpc.fromRpcGroup` generates an OpenRPC document from an RPC group ([#10173](https://github.com/Effect-TS/effect/pull/10173)). See [OpenRpc](./interfaces/rpc.md#openrpc).
- **CLI documentation specs:** `CommandSpec` projects a command path into plain data, and `Flag.annotate`, `Argument.annotate`, and `Param.annotate` attach metadata ([#10377](https://github.com/Effect-TS/effect/pull/10377)). See [CommandSpec](./tooling/cli-framework.md#commandspec).
- **Cloudflare cluster:** `@effect/platform-cloudflare` runs cluster entities, workflows, durable queues, and singletons on Durable Objects, with optional Alchemy deployment ([#7322](https://github.com/Effect-TS/effect/pull/7322)). See [Running on Cloudflare Durable Objects](./systems/cluster-sharding.md#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](https://github.com/Effect-TS/effect/pull/10267)). See [MessageRetention](./systems/cluster-sharding.md#messageretention).
- **AI providers and protocols:** `@effect/ai-amazon-bedrock` signs Converse requests with SigV4 or a Bedrock API key ([#9980](https://github.com/Effect-TS/effect/pull/9980)); `WorkloadIdentity` exchanges platform identity tokens for short-lived provider tokens ([#10512](https://github.com/Effect-TS/effect/pull/10512), [#10482](https://github.com/Effect-TS/effect/pull/10482)); AG-UI serves an agent to frontends with client-executed tools ([#9842](https://github.com/Effect-TS/effect/pull/9842)). See [Provider packages](./systems/ai-language-models.md#provider-packages), [WorkloadIdentity](./systems/ai-language-models.md#workloadidentity), and [AgUiServer](./systems/ai-language-models.md#aguiserver).

**Telemetry names and wire-visible behavior**

- **Span status:** `OtlpTracer` and `OtelTracer` leave a successful span's status Unset instead of OK ([#10440](https://github.com/Effect-TS/effect/pull/10440)). **Migration:** rules matching `status = OK` must match `status != ERROR`. See [What ends up on a span](./operations/observability.md#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](https://github.com/Effect-TS/effect/pull/10304)). See [Tracing](./systems/mcp.md#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](https://github.com/Effect-TS/effect/pull/10213)). See [Transactions](./interfaces/sql.md#transactions).
- **OTLP:** metrics without a unit export an empty unit instead of `"1"` ([#10385](https://github.com/Effect-TS/effect/pull/10385)); idle log and trace exporters no longer keep a Node process alive ([#10235](https://github.com/Effect-TS/effect/pull/10235)). See [OtlpMetrics](./operations/telemetry-export.md#otlpmetrics) and [OtlpExporter](./operations/telemetry-export.md#otlpexporter).
- **Span redaction:** `HttpApi.RedactedNames` declares query and header names to redact in client and server spans ([#9995](https://github.com/Effect-TS/effect/pull/9995)), and `HttpClientError` URLs use the redaction names active when the error is created ([#10006](https://github.com/Effect-TS/effect/pull/10006)). See [HttpApi](./interfaces/http-api.md#httpapi) and [HttpClientError](./interfaces/http-client.md#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](https://github.com/Effect-TS/effect/pull/10362), [#10243](https://github.com/Effect-TS/effect/pull/10243), [#10148](https://github.com/Effect-TS/effect/pull/10148)). See [Failure results and their wire format](./systems/ai-language-models.md#failure-results-and-their-wire-format) and [HttpApiSchema](./interfaces/http-api.md#httpapischema).
- **SSE framing:** `Sse.encoder` strips CR and LF from `id` and `event` and NUL from `id` ([#10182](https://github.com/Effect-TS/effect/pull/10182)). See [Sse](./concurrency/streaming-channels.md#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](https://github.com/Effect-TS/effect/pull/10475)). See [Runtime](./foundations/fibers-scopes-runtimes.md#runtime).
- **Bun and Deno:** servers answer `503` instead of `404` while no app is served ([#10289](https://github.com/Effect-TS/effect/pull/10289)), and enforce `MaxBodySize` on buffered reads ([#10192](https://github.com/Effect-TS/effect/pull/10192)). See [Own the listener](./interfaces/http-server.md#own-the-listener-acquire-late-bind-port-0-prove-release).

**Behavior, types, and security**

- **HTTP client:** `HttpClient.timeout` fails a request that receives no response in time with a retryable `TransportError` ([#10207](https://github.com/Effect-TS/effect/pull/10207)); `HttpClient.withScope` now owns every request sent during the execution, including redirects, retries, and middleware requests ([#10363](https://github.com/Effect-TS/effect/pull/10363)). See [Retries, time budgets, and cancellation](./interfaces/http-client.md#retries-time-budgets-and-cancellation) and [Response lifetimes and `withScope`](./interfaces/http-client.md#response-lifetimes-and-withscope).
- **HTTP server shutdown:** a transferred request scope closes only after both the request and its body finish ([#10366](https://github.com/Effect-TS/effect/pull/10366)); Node closes WebSockets with code 1001 at shutdown and destroys connections left at the graceful timeout ([#10405](https://github.com/Effect-TS/effect/pull/10405), [#10360](https://github.com/Effect-TS/effect/pull/10360), [#10300](https://github.com/Effect-TS/effect/pull/10300)). See [HttpEffect](./interfaces/http-server.md#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](https://github.com/Effect-TS/effect/pull/10433), [#10434](https://github.com/Effect-TS/effect/pull/10434)). See [Transactions](./interfaces/sql.md#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](https://github.com/Effect-TS/effect/pull/10387), [#10403](https://github.com/Effect-TS/effect/pull/10403)). **Migration:** provide the driver layer itself where a driver service is required. See [The driver packages](./interfaces/sql.md#the-driver-packages).
- **PostgreSQL values:** an unregistered value that cannot be decoded fails only that query, naming the column ([#10422](https://github.com/Effect-TS/effect/pull/10422)). See [Native client behavior](./interfaces/sql.md#native-client-behavior-codecs-json-and-listen).
- **Event log authentication:** the server verifies the session signature before binding a signing key; `authorizeIdentity` receives `signingPublicKey` ([#10185](https://github.com/Effect-TS/effect/pull/10185), [#10211](https://github.com/Effect-TS/effect/pull/10211)). See [EventLogServerUnencrypted](./systems/event-log-event-sourcing.md#eventlogserverunencrypted).
- **Resource limit:** BigDecimal parsing rejects scales outside ±10,000, and scale alignment beyond 20,000 throws `RangeError` ([#10188](https://github.com/Effect-TS/effect/pull/10188)). See [BigDecimal](./data/functional-toolkit.md#bigdecimal).
- **Ref equality:** the identity `Equal` for `Ref` and `MutableRef` was reverted, so distinct refs with equal contents are `Equal` ([#10247](https://github.com/Effect-TS/effect/pull/10247)). See [Ref](./concurrency/state-mutable-references.md#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](https://github.com/Effect-TS/effect/pull/10206), [#10260](https://github.com/Effect-TS/effect/pull/10260), [#10311](https://github.com/Effect-TS/effect/pull/10311), [#10356](https://github.com/Effect-TS/effect/pull/10356), [#10146](https://github.com/Effect-TS/effect/pull/10146), [#10226](https://github.com/Effect-TS/effect/pull/10226)); entity defect backoff is per entity ([#10261](https://github.com/Effect-TS/effect/pull/10261)). See [ClusterWorkflowEngine](./systems/cluster-sharding.md#clusterworkflowengine) and [Entity](./systems/cluster-sharding.md#entity).
- **Persistence:** `PersistedQueue` `offer` accepts `deduplicate: "untilExecuted"` ([#10316](https://github.com/Effect-TS/effect/pull/10316)); `RateLimiter` limits of 0 or less admit nothing and Redis keys are isolated ([#10103](https://github.com/Effect-TS/effect/pull/10103), [#10210](https://github.com/Effect-TS/effect/pull/10210)); `CircuitBreaker.execute` gains `onRejection` and classifiers receive `{ probe }` ([#10142](https://github.com/Effect-TS/effect/pull/10142), [#10169](https://github.com/Effect-TS/effect/pull/10169)); the `redis` peer minimum is 5.1.0 ([#10153](https://github.com/Effect-TS/effect/pull/10153)). See [PersistedQueue](./tooling/persistence.md#persistedqueue), [RateLimiter](./tooling/persistence.md#ratelimiter), and [CircuitBreaker](./tooling/persistence.md#circuitbreaker).
- **RPC:** handlers may fail with their server middleware's errors ([#10418](https://github.com/Effect-TS/effect/pull/10418)); discarded calls fail promptly on transport errors, and a custom client `Protocol` must reply to every accepted request ([#10121](https://github.com/Effect-TS/effect/pull/10121), [#10171](https://github.com/Effect-TS/effect/pull/10171)). See [RpcGroup](./interfaces/rpc.md#rpcgroup) and [RpcClient](./interfaces/rpc.md#rpcclient).
- **GraphQL:** calls never succeed on a non-2xx response ([#10208](https://github.com/Effect-TS/effect/pull/10208)). See [GraphQLClientError](./interfaces/graphql.md#graphqlclienterror).
- **AI and MCP:** `generateObject` accepts `allowEmpty` ([#10527](https://github.com/Effect-TS/effect/pull/10527)); MCP Skills are served on every supported protocol revision ([#10082](https://github.com/Effect-TS/effect/pull/10082), [#10540](https://github.com/Effect-TS/effect/pull/10540)); `McpClient` gains capabilities, discovery limits, and toolkit options ([#10049](https://github.com/Effect-TS/effect/pull/10049)). See [LanguageModel](./systems/ai-language-models.md#languagemodel), [Skills](./systems/mcp.md#skills), and [McpClient](./systems/mcp.md#mcpclient).
- **CLI:** `Command.validate` can fail with your own errors, which `Command.run` reports like handler failures ([#10376](https://github.com/Effect-TS/effect/pull/10376)). See [Validating input across flags](./tooling/cli-framework.md#validating-input-across-flags).
- **Schema:** fields named after `Object.prototype` members match only own properties ([#9612](https://github.com/Effect-TS/effect/pull/9612)); `isAnyOf` accepts only union tags ([#10355](https://github.com/Effect-TS/effect/pull/10355)); `SchemaBinary` adds fixed-width integers and rejects non-numbers in number arrays ([#10230](https://github.com/Effect-TS/effect/pull/10230), [#10288](https://github.com/Effect-TS/effect/pull/10288)); JSON Schema import adds experimental `closeObjects` ([#10521](https://github.com/Effect-TS/effect/pull/10521)). See [Structs](./data/schema.md#3-structs-the-workhorse), [SchemaBinary](./concurrency/streaming-channels.md#schemabinary), and [JsonSchema](./data/schema-tooling.md#jsonschema).
- **Time zones:** named zones keep the supplied identifier, aliases included ([#10439](https://github.com/Effect-TS/effect/pull/10439)). See [Time zones](./concurrency/scheduling-time.md#time-zones-iana).

### Changes in the handbook

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

## `effect@4.1.3` — audited 2026-11-10

Edition **4.1** (patch update). Tag [`effect@4.1.3`](https://github.com/Effect-TS/effect/tree/effect%404.1.3), commit [`7865dbbb`](https://github.com/Effect-TS/effect/commit/7865dbbb7b6a91691921dbb4febedf3ab94a348b), published 2026-11-10. Baseline: `effect@4.1.2`.

### Changes in Effect that matter to readers

This entry records a dependency and example-validation refresh, not a complete release-delta or source audit. Consult the [upstream changelog](https://github.com/Effect-TS/effect/blob/effect%404.1.3/packages/effect/CHANGELOG.md) 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](https://github.com/Effect-TS/effect/pull/10332)). Decode `Schema.toCodecJson(tool.parametersSchema)` before typed policy checks, but pass the original JSON to `handle`. See [Tool-call resolution](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch) and [Mutation gates](./deep-dives/building-a-production-ai-capability.md#keep-the-framework-from-executing-a-mutation-before-your-gates-run).

### Changes in the handbook

- 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](./index.md#version-and-validation-scope).

## `effect@4.1.2` — audited 2026-11-02

Edition **4.1** (patch update). Tag [`effect@4.1.2`](https://github.com/Effect-TS/effect/tree/effect%404.1.2), commit [`506eef14`](https://github.com/Effect-TS/effect/commit/506eef143bcc1750ce58920aac1e45da7265d103), published 2026-11-02. Baseline: `effect@4.1.0`.

### Changes in Effect that matter to readers

This entry records a dependency-only refresh, not a complete release-delta or source audit. Consult the [upstream changelog](https://github.com/Effect-TS/effect/blob/effect%404.1.2/packages/effect/CHANGELOG.md) for changes since 4.1.0; coverage of newly added APIs remains outside this update.

### Changes in the handbook

- 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](./index.md#version-and-validation-scope).

## `effect@4.1.0` — audited 2026-10-29

Edition **4.1** (new edition; the 4.0 edition is frozen at `effect@4.0.5`). Tag [`effect@4.1.0`](https://github.com/Effect-TS/effect/tree/effect%404.1.0), commit [`9a91b192`](https://github.com/Effect-TS/effect/commit/9a91b1926a5fbfaffd302a7a41a94d4d53a1154e), 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.

### Changes in Effect that matter to readers

**New public surfaces and stability**

- No module present in 4.0.5 changed its module-level `@stability`. New modules:
  - unstable: root `Bytes`, `SemVer`, `SemVerRange`; `effect/encoding` `Csv`, `JsonArray`, `Tar`; `EventRow`, `ProblemDetails`, `OtlpProxy`, `UserDirectories`, `CommandLine`, `MigratorFileSystem`, `TerminalCapabilities`, `McpTest`, and the new `effect/crypto` family;
  - experimental: `Glob`, `TextDiff`, `Xml`, `Zip`, `persistence/CircuitBreaker`, `McpClient`, `McpClientError`.

  Sources: [#9441](https://github.com/Effect-TS/effect/pull/9441), [#9243](https://github.com/Effect-TS/effect/pull/9243), [#9291](https://github.com/Effect-TS/effect/pull/9291), [#9431](https://github.com/Effect-TS/effect/pull/9431), [#9148](https://github.com/Effect-TS/effect/pull/9148), [#9420](https://github.com/Effect-TS/effect/pull/9420), [#9419](https://github.com/Effect-TS/effect/pull/9419), [#9434](https://github.com/Effect-TS/effect/pull/9434), [#9438](https://github.com/Effect-TS/effect/pull/9438), [#9646](https://github.com/Effect-TS/effect/pull/9646), [#8862](https://github.com/Effect-TS/effect/pull/8862). Stable modules gain a few unstable exports: `Match.literals`/`literalsExhaustive`, `Metric.remove`/`registerUnsafe`, `Pool.stats` ([#9824](https://github.com/Effect-TS/effect/pull/9824), [#9572](https://github.com/Effect-TS/effect/pull/9572), [#9090](https://github.com/Effect-TS/effect/pull/9090)). See [Stability and support](./index.md#stability-and-support).
- Deep imports of nested `internal` modules are blocked by the package `exports` map ([#9326](https://github.com/Effect-TS/effect/pull/9326)). **Migration:** import only public entry points. See [Getting Started](./foundations/getting-started.md).
- **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](https://github.com/Effect-TS/effect/pull/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.

  See [Cryptography](./interfaces/cryptography.md), [Deterministic crypto in tests](./tooling/testing-dev-tooling.md#deterministic-crypto-in-tests).

**Runtime, errors, and layers**

- 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](https://github.com/Effect-TS/effect/pull/9516), [#9433](https://github.com/Effect-TS/effect/pull/9433)). Use `catchCause` or `catchDefect` to handle such causes. See [Recovery and mixed causes](./foundations/errors-option-result.md#recovery-and-mixed-causes), [Typed recovery and mixed causes](./deep-dives/failure-retry-fallback-and-interruption.md#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](https://github.com/Effect-TS/effect/pull/9634)). Wrap the composed layer itself in `Layer.fresh` for a separate copy. See [What is shared and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt).
- `Ref` and `MutableRef` compare by reference ([#9768](https://github.com/Effect-TS/effect/pull/9768)). `ArrayBuffer`s compare and hash by bytes ([#9769](https://github.com/Effect-TS/effect/pull/9769)). **Migration:** `Exit.hasFails`/`hasDies`/`hasInterrupts` and `AsyncResult.isInterrupted` are no longer type guards; narrow with `Exit.isFailure` ([#9799](https://github.com/Effect-TS/effect/pull/9799)). See [Ref](./concurrency/state-mutable-references.md#ref), [Exit](./foundations/fibers-scopes-runtimes.md#exit).
- New small runtime APIs:
  - `Effect.ignore({ log: "Unhandled" })` and its Stream/Channel variants ([#9510](https://github.com/Effect-TS/effect/pull/9510));
  - `Semaphore.takeScoped` ([#9962](https://github.com/Effect-TS/effect/pull/9962));
  - `Effect.fnUntraced` accepting `{ self }` ([#9713](https://github.com/Effect-TS/effect/pull/9713)).

  Release failures nobody observes (RcMap/RcRef idle expiry, ScopedCache scans) are logged at `UnhandledLogLevel` ([#9388](https://github.com/Effect-TS/effect/pull/9388)). See [Semaphore](./concurrency/concurrency-coordination.md#semaphore), [RcMap](./concurrency/concurrency-coordination.md#rcmap).
- `Schedule.fibonacci` now repeats the initial delay (100, 100, 200, 300 ms…), so later retries come sooner ([#9917](https://github.com/Effect-TS/effect/pull/9917)). `Cron`/`Schedule.cron` gain `onDstOverlap` for repeated local times ([#9905](https://github.com/Effect-TS/effect/pull/9905)). `Duration` gains `formatIso`/`fromIso` (exact units only) and `toMicros` ([#9891](https://github.com/Effect-TS/effect/pull/9891), [#9973](https://github.com/Effect-TS/effect/pull/9973)). See [Cron](./concurrency/scheduling-time.md#cron), [Duration](./concurrency/scheduling-time.md#duration).
- Upstream stream failures in `Stream.run`, `peel` and `aggregate*` bypass `Sink.mapError`/`catch*`/`orElse` and reach the caller unchanged ([#9803](https://github.com/Effect-TS/effect/pull/9803)). See [Sink](./concurrency/streaming-channels.md#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](https://github.com/Effect-TS/effect/pull/9701)). Node `originalUrl` is absolute when a Host header is present; read paths from `url` ([#9415](https://github.com/Effect-TS/effect/pull/9415)). See [HttpMiddleware](./interfaces/http-server.md#httpmiddleware).
- Request data leaks less:
  - `HttpClientError` `toJSON` shows only the method and redacted URL ([#9855](https://github.com/Effect-TS/effect/pull/9855));
  - `HttpServerError` messages carry only the path ([#10011](https://github.com/Effect-TS/effect/pull/10011));
  - AWS SigV4 query parameters are redacted by default ([#9903](https://github.com/Effect-TS/effect/pull/9903)).

  **Migration:** `AiError.HttpRequestDetails` and `Response.HttpRequestDetails` are removed, and `NetworkError` exposes `method` and `url` instead of `request` ([#10010](https://github.com/Effect-TS/effect/pull/10010)). See [HttpClientError](./interfaces/http-client.md#httpclienterror), [AiError](./systems/ai-language-models.md#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](https://github.com/Effect-TS/effect/pull/9614)). **Migration:** received request methods are typed `string`; exhaustive switches need a default or `HttpMethod.isHttpMethod` ([#8766](https://github.com/Effect-TS/effect/pull/8766)). See [HttpClient](./interfaces/http-client.md#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](https://github.com/Effect-TS/effect/pull/9709)). Other additions:
  - `HttpClient.isTransientError`/`isTransientResponse` ([#9059](https://github.com/Effect-TS/effect/pull/9059));
  - experimental `HttpClient.withCircuitBreaker` ([#9646](https://github.com/Effect-TS/effect/pull/9646));
  - `HttpClientResponse.toWeb` ([#9673](https://github.com/Effect-TS/effect/pull/9673)).

  `FetchHttpClient` fails with `EncodeError` on runtimes without streaming request bodies unless `StreamBodyFallback` is `"buffer"` ([#9567](https://github.com/Effect-TS/effect/pull/9567)). See [HttpClient](./interfaces/http-client.md#httpclient).
- Raw HTTP/1.1 upgrades (`HttpClientRequest.upgrade`, `HttpApiSchema.Upgrade`) arrive. Custom `HttpClientResponse` implementations must add `upgrade` ([#9339](https://github.com/Effect-TS/effect/pull/9339)). Upgrade endpoints can declare `101` headers and buffered payloads, and can sit alongside ordinary success responses ([#9751](https://github.com/Effect-TS/effect/pull/9751), [#9945](https://github.com/Effect-TS/effect/pull/9945)). **Migration:** hand-built `HttpApiClient.Upgraded` mocks need the `UpgradedTypeId` brand; narrow with `HttpApiClient.isUpgraded`. See [Upgrades](./interfaces/http-api.md#upgrades).
- New `HttpApi` features:
  - streaming request payloads via `StreamUint8Array`/`StreamNdjson`, with `maxBytes` limits and `HttpApiPayloadTooLarge` (413) ([#9575](https://github.com/Effect-TS/effect/pull/9575));
  - opt-in RFC 9457 Problem Details via `HttpApiError.Problem` and `HttpApiMiddleware.layerProblemDetails` ([#9706](https://github.com/Effect-TS/effect/pull/9706));
  - `HttpApiClient.decodeResponse` ([#9944](https://github.com/Effect-TS/effect/pull/9944)).

  Oversized bodies return 413, and web/Bun/Deno servers now enforce `MaxBodySize` on buffered reads ([#9835](https://github.com/Effect-TS/effect/pull/9835)). See [Problem Details](./interfaces/http-api.md#problem-details-rfc-9457), [Streaming request payloads](./interfaces/http-api.md#streaming-request-payloads).
- **Migration (deployment):** `@effect/platform-node`, `platform-node-shared`, `opentelemetry` and `docgen` require Node ≥ 22.19.0 ([#10084](https://github.com/Effect-TS/effect/pull/10084)), and `@effect/platform-deno` requires Deno ≥ 2.9.3 ([#9702](https://github.com/Effect-TS/effect/pull/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.
  - `NodeHttpServer` accepts HTTP/2 servers ([#9710](https://github.com/Effect-TS/effect/pull/9710)).
  - `BunHttpServer` disables Bun's 10 s `idleTimeout` unless set ([#9705](https://github.com/Effect-TS/effect/pull/9705)).
  - Node stream pulls are bounded by `chunkSize` chunks; use the new `readSize` for byte read sizes ([#9327](https://github.com/Effect-TS/effect/pull/9327)).

  See [Platform packages](./interfaces/platform-runtime-hosts.md#platform-packages), [Socket](./interfaces/platform-runtime-hosts.md#socket).

**Processes, file systems, terminals, and CLI**

- **Migration:** `ChildProcess.make` templates now parse as a command line ([#9752](https://github.com/Effect-TS/effect/pull/9752), [#9863](https://github.com/Effect-TS/effect/pull/9863)).
  - Quoted words stay together, and unquoted shell syntax (`|`, `$HOME`, `*`, `FOO+=x`) throws `CommandLineError`. Quote such text or interpolate it with `${}`.
  - With `shell`, build the script with `CommandLine.join`.
  - `ChildProcess.TemplateExpression*` moves to `CommandLine`.
  - Arguments and `env` accept `Redacted`.

  `exitCode`/`string`/`lines` drain unread pipes instead of hanging ([#9846](https://github.com/Effect-TS/effect/pull/9846)). See [ChildProcess](./interfaces/platform-runtime-hosts.md#childprocess), [CommandLine](./interfaces/platform-runtime-hosts.md#commandline).
- **Migration (custom implementations):** `FileSystem.make` inputs must provide `lstat` and `readDirectoryEntries`, and `glob` is now derived ([#6428](https://github.com/Effect-TS/effect/pull/6428), [#9438](https://github.com/Effect-TS/effect/pull/9438)). `Terminal.make` inputs must provide `size`, a resize queue ([#9639](https://github.com/Effect-TS/effect/pull/9639)). `FileSystem.glob` is experimental, uses `/` separators, and no longer expands Node extglobs. See [FileSystem](./interfaces/platform-runtime-hosts.md#filesystem), [Glob](./interfaces/platform-runtime-hosts.md#glob), [Terminal](./interfaces/platform-runtime-hosts.md#terminal).
- **Migration:** a single-valued CLI flag given twice now fails; use `Flag.atLeast`/`atMost`/`between` ([#9872](https://github.com/Effect-TS/effect/pull/9872)). `-num=3` lexes as short flags; use `--num=3` ([#9287](https://github.com/Effect-TS/effect/pull/9287)). New CLI APIs:
  - `Command.validate` ([#9655](https://github.com/Effect-TS/effect/pull/9655)) and `Flag.withNegation` ([#9650](https://github.com/Effect-TS/effect/pull/9650));
  - `CliOutput.Presenter` ([#6743](https://github.com/Effect-TS/effect/pull/6743)) and `TerminalCapabilities`, which honours `FORCE_COLOR`/`TERM=dumb` ([#8350](https://github.com/Effect-TS/effect/pull/8350));
  - `Completions.fromCommand` ([#9976](https://github.com/Effect-TS/effect/pull/9976)) and the `CliError.userMessage` annotation ([#8349](https://github.com/Effect-TS/effect/pull/8349)).

  Help shows an `INHERITED FLAGS` section, and custom formatters must read `HelpDoc.inheritedFlags` ([#9276](https://github.com/Effect-TS/effect/pull/9276)). See [CliOutput](./tooling/cli-framework.md#clioutput), [TerminalCapabilities](./tooling/cli-framework.md#terminalcapabilities).

**SQL, persistence, event log, cluster, and RPC**

- **Migration:** `sql.insert` and `sql.updateValues` require a non-empty array at the type level ([#9453](https://github.com/Effect-TS/effect/pull/9453)). The `updateValues` alias is escaped as an identifier, so pass it bare ([#9759](https://github.com/Effect-TS/effect/pull/9759)). `fromFileSystem` moves to `effect/sql/MigratorFileSystem`; adapter `*Migrator` modules still re-export it ([#9157](https://github.com/Effect-TS/effect/pull/9157)).
  - Migrations fail with a typed `MigrationError` ([#9598](https://github.com/Effect-TS/effect/pull/9598)).
  - Third-party drivers must set `SqlClient.make({ driver })` ([#9222](https://github.com/Effect-TS/effect/pull/9222)).
  - New: `SqlClient.afterCommit` and `BeginTransaction` ([#9289](https://github.com/Effect-TS/effect/pull/9289), [#9576](https://github.com/Effect-TS/effect/pull/9576)); `sql.in([])` now compiles to an always-false (`IN`) or always-true (`NOT IN`) predicate ([#9758](https://github.com/Effect-TS/effect/pull/9758)); PostgreSQL `acquireTimeout`, `onAcquire` and `poolStats` ([#9641](https://github.com/Effect-TS/effect/pull/9641), [#9738](https://github.com/Effect-TS/effect/pull/9738), [#9090](https://github.com/Effect-TS/effect/pull/9090)).

  See [MigratorFileSystem](./interfaces/sql.md#migratorfilesystem), [Transactions](./interfaces/sql.md#transactions).
- **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](https://github.com/Effect-TS/effect/pull/9223)).
  - Custom `KeyValueStore.make` stores must implement `keys`, and `prefix(...)` scopes `size`/`isEmpty`/`clear` ([#9844](https://github.com/Effect-TS/effect/pull/9844)).
  - The Redis `PersistedQueue` lock format changed: drain old workers and let their locks expire before starting upgraded ones ([#9229](https://github.com/Effect-TS/effect/pull/9229)).
  - `Redis.make` requires `connect`, and `Redis.reserve` leases dedicated connections for blocking commands ([#9828](https://github.com/Effect-TS/effect/pull/9828)).

  See [Backing layers](./tooling/persistence.md#backing-layers), [Redis](./tooling/persistence.md#redis), [PersistedQueue](./tooling/persistence.md#persistedqueue).
- **Migration (wire):** event-log writes are now acknowledged instead of echoed, and encrypted replication batches entries ([#9477](https://github.com/Effect-TS/effect/pull/9477), [#9479](https://github.com/Effect-TS/effect/pull/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](https://github.com/Effect-TS/effect/pull/9482)). New: encrypted remote compaction ([#9571](https://github.com/Effect-TS/effect/pull/9571)), `EventRow` ([#9523](https://github.com/Effect-TS/effect/pull/9523)), `EventLog.writeMany` ([#9452](https://github.com/Effect-TS/effect/pull/9452)). See [EventLogRemote](./systems/event-log-event-sourcing.md#eventlogremote), [EventRow](./systems/event-log-event-sourcing.md#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](https://github.com/Effect-TS/effect/pull/9677)).
  - Frozen runners lose PostgreSQL/MySQL shard locks after `shardLockExpiration` ([#10037](https://github.com/Effect-TS/effect/pull/10037), [#10093](https://github.com/Effect-TS/effect/pull/10093)).
  - `ShardingConfig.runnerJoinDebounce` batches handoffs during surge deploys ([#10073](https://github.com/Effect-TS/effect/pull/10073)).
  - New `ClusterMetrics` series: `shardReleaseDuration`, `shardsReleasing`, `entityMailboxSize[Max]` ([#9256](https://github.com/Effect-TS/effect/pull/9256), [#9513](https://github.com/Effect-TS/effect/pull/9513), [#9578](https://github.com/Effect-TS/effect/pull/9578), [#9572](https://github.com/Effect-TS/effect/pull/9572)).
  - `SqlMessageStorage.makeEncodedStorage` skips migrations ([#9330](https://github.com/Effect-TS/effect/pull/9330)).

  See [ClusterCron](./systems/cluster-sharding.md#clustercron), [SqlRunnerStorage](./systems/cluster-sharding.md#sqlrunnerstorage).
- **Migration (wire):** RPC calls with `discard: true` complete when the server acknowledges them. The `SchemaBinary` envelope fingerprint changed, so upgrade those peers together ([#9182](https://github.com/Effect-TS/effect/pull/9182)). The RPC NDJSON content type is `application/x-ndjson`; existing RPC HTTP peers stay compatible ([#9562](https://github.com/Effect-TS/effect/pull/9562)). New: `RpcServer` `onDisconnect` ([#9688](https://github.com/Effect-TS/effect/pull/9688)) and opt-in HTTP request `batch`ing ([#9656](https://github.com/Effect-TS/effect/pull/9656)). With `disableFatalDefects`, a synchronous handler throw fails only its own request ([#9899](https://github.com/Effect-TS/effect/pull/9899)). See [RpcSerialization](./interfaces/rpc.md#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](https://github.com/Effect-TS/effect/pull/9177)). `DecisionModel.decideSettled` keeps valid answers alongside per-decision failures ([#9437](https://github.com/Effect-TS/effect/pull/9437)).
  - **Migration:** the new non-retryable `AiError.InvalidResponseError` needs a case in exhaustive `AiErrorReason` matches ([#9430](https://github.com/Effect-TS/effect/pull/9430)).
  - `NetworkError.cause` keeps the `HttpClientError` ([#9984](https://github.com/Effect-TS/effect/pull/9984)).
  - `Tool.make({ toModelOutput })` sends rich tool results ([#9861](https://github.com/Effect-TS/effect/pull/9861)).
  - `Response.AllParts` requires tool parameter schema services ([#9873](https://github.com/Effect-TS/effect/pull/9873)).

  See [Decision](./systems/ai-language-models.md#decision), [Tool](./systems/ai-language-models.md#tool).
- **Migration:** pass `McpServer` registration layers through the transport's `registrations` option, and capture construction-time services with `Layer.unwrap` ([#9154](https://github.com/Effect-TS/effect/pull/9154)). Unmet per-request services surface as `McpRequest<"Requires", S>` ([#9856](https://github.com/Effect-TS/effect/pull/9856)). New: `McpServer.visibility` ([#9661](https://github.com/Effect-TS/effect/pull/9661)), `cacheHints` ([#9939](https://github.com/Effect-TS/effect/pull/9939)), the in-memory `McpTest.makeClient` ([#9657](https://github.com/Effect-TS/effect/pull/9657)), and the experimental `McpClient` ([#8862](https://github.com/Effect-TS/effect/pull/8862)). See [McpServer](./systems/mcp.md#mcpserver), [McpClient](./systems/mcp.md#mcpclient).
- Provider changes ([#9509](https://github.com/Effect-TS/effect/pull/9509), [#9421](https://github.com/Effect-TS/effect/pull/9421), [#9263](https://github.com/Effect-TS/effect/pull/9263), [#9920](https://github.com/Effect-TS/effect/pull/9920)) See [Provider packages](./systems/ai-language-models.md#provider-packages).:
  - **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.
  - Truncated responses report `finishReason: "length"`.

**Data, encoding, telemetry, and testing**

- **Migration:** drop explicit output type arguments from `Schema.TaggedUnion.match`/`matchOrElse` ([#10061](https://github.com/Effect-TS/effect/pull/10061)). `Schema.Record` rejects optional index-signature values; use `Schema.UndefinedOr` ([#9864](https://github.com/Effect-TS/effect/pull/9864)). Checks keep `httpApiStatus` annotations ([#9775](https://github.com/Effect-TS/effect/pull/9775)). New Schema APIs: crypto key schemas, `isAscii`, `DurationFromIsoString`, `DateTimeUtcFromHttpDate`, and the unstable `toCodecGoJson` ([#9245](https://github.com/Effect-TS/effect/pull/9245)). See [Schema unions and records](./data/schema.md#4-unions-literals-records-tuples).
- **Migration:** `Toml.parse` returns a `Result` with an `EncodingError` instead of throwing ([#9537](https://github.com/Effect-TS/effect/pull/9537)). `Base64Url.decode` rejects partial padding ([#10076](https://github.com/Effect-TS/effect/pull/10076)), and `Yaml.parse` supports `<<` merge keys ([#10051](https://github.com/Effect-TS/effect/pull/10051)). `NdjsonError` gains a `reason` ([#9575](https://github.com/Effect-TS/effect/pull/9575)). Libraries exporting generic `Data.taggedEnum`s now emit declarations that need `effect` ≥ 4.0.7 ([#9834](https://github.com/Effect-TS/effect/pull/9834)). See [Toml](./concurrency/streaming-channels.md#toml), [Yaml](./concurrency/streaming-channels.md#yaml).
- **Migration:** import `NodeSdk`/`WebSdk` from `@effect/opentelemetry/NodeSdk` and `/WebSdk`; the package root no longer re-exports them ([#9689](https://github.com/Effect-TS/effect/pull/9689)). Other telemetry changes:
  - `OTEL_RESOURCE_ATTRIBUTES` is percent-decoded and trimmed ([#9997](https://github.com/Effect-TS/effect/pull/9997)).
  - Calls on ended spans are ignored, so spans are not exported twice ([#9815](https://github.com/Effect-TS/effect/pull/9815)).
  - `traceparent`/`b3` parsing rejects uppercase hex and malformed flags ([#10086](https://github.com/Effect-TS/effect/pull/10086), [#10085](https://github.com/Effect-TS/effect/pull/10085)).
  - The new `OtlpProxy` forwards browser telemetry without exposing credentials ([#9829](https://github.com/Effect-TS/effect/pull/9829)).

  See [OtelNodeSdk](./operations/telemetry-export.md#otelnodesdk), [OtlpProxy](./operations/telemetry-export.md#otlpproxy).
- Atoms gain `skipInitialRun` for hydrated or seeded atoms ([#9522](https://github.com/Effect-TS/effect/pull/9522)) and opt-in typed `Reactivity.Keys` ([#9560](https://github.com/Effect-TS/effect/pull/9560)). `Atom.Serializable` encodes to `Schema.Json` ([#8763](https://github.com/Effect-TS/effect/pull/8763)). See [Hydration](./systems/reactivity-atom.md#hydration).
- `@effect/vitest` changes:
  - `beforeAll`/`beforeEach` run returned Effects with a scope ([#9675](https://github.com/Effect-TS/effect/pull/9675));
  - `layer(..., { buildPerTest })` rebuilds selected services for each test ([#9832](https://github.com/Effect-TS/effect/pull/9832));
  - **Migration:** `it.prop` rejects Effect/Promise returns; use `it.effect.prop` ([#9384](https://github.com/Effect-TS/effect/pull/9384)).

  `Arbitrary.checkEffect` accepts `concurrency` ([#9377](https://github.com/Effect-TS/effect/pull/9377)). See [@effect/vitest](./tooling/testing-dev-tooling.md#effect-vitest).

### Changes in the handbook

- 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](./interfaces/cryptography.md) 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.

## `effect@4.0.5` — audited 2026-10-22

Edition **4.0** (updated in place). Tag [`effect@4.0.5`](https://github.com/Effect-TS/effect/tree/effect%404.0.5), commit [`7f524e25`](https://github.com/Effect-TS/effect/commit/7f524e25cfb49a71ac39b0f44278d08d40dda5de), 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.

### Changes in Effect that matter to readers

**New public surfaces and stability**

- Experimental [`effect/graphql`](./interfaces/graphql.md) adds seven modules for typed client operations, middleware, HTTP/SSE and WebSocket subscriptions, partial results, pagination, and batching ([#8979](https://github.com/Effect-TS/effect/pull/8979)). It is not a GraphQL server executor. [`@effect/graphql-generator`](./interfaces/graphql.md#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](https://github.com/Effect-TS/effect/pull/9171)). HTTP endpoints can be resolved per request, with resolver batches partitioned by URL ([#9150](https://github.com/Effect-TS/effect/pull/9150)); identity-aware `batchKey`s are still required.
- Experimental [`Host`, `Dns`, and `AddressResolver`](./interfaces/platform-runtime-hosts.md#host) add host parsing, DNS queries, and endpoint resolution, with Node/Bun/Deno services ([#8880](https://github.com/Effect-TS/effect/pull/8880)). TLSA records and input constructors follow ([#8953](https://github.com/Effect-TS/effect/pull/8953), [#8970](https://github.com/Effect-TS/effect/pull/8970), [#8973](https://github.com/Effect-TS/effect/pull/8973)); host-file parsing and relative/FQDN conversion are available ([#8992](https://github.com/Effect-TS/effect/pull/8992)). [`DatagramSocket`](./interfaces/platform-runtime-hosts.md#datagramsocket) adds experimental UDP on those hosts ([#8409](https://github.com/Effect-TS/effect/pull/8409)). Experimental APIs may change in a patch release; see [Stability and support](./index.md#stability-and-support).
- `TestCrypto.layer` (removed in 4.1.0; see [Deterministic crypto in tests](./tooling/testing-dev-tooling.md#deterministic-crypto-in-tests)) seeds random operations while delegating digests to the underlying platform `Crypto` ([#8487](https://github.com/Effect-TS/effect/pull/8487)). **Migration:** `Crypto.randomUUIDv4` and `randomUUIDv7` are now functions: call `()` for strings or `({ format: "bytes" })` for bytes ([#8935](https://github.com/Effect-TS/effect/pull/8935)).
- [`Effect.Transaction`](./concurrency/software-transactional-memory.md#inspecting-transaction-attempts) exposes attempt number, retry reason, and timing metadata from inside a transaction body ([#8166](https://github.com/Effect-TS/effect/pull/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](https://github.com/Effect-TS/effect/pull/9136)). `UrlParams` also accepts `Redacted` values, widening its public parameter and iterator types ([#9160](https://github.com/Effect-TS/effect/pull/9160)). See [HTTP Client](./interfaces/http-client.md).
- [`HttpClientRequest.compressBody`](./interfaces/http-client.md#httpclientrequest) supports gzip/deflate ([#9137](https://github.com/Effect-TS/effect/pull/9137)); [`HttpMiddleware.decompression`](./interfaces/http-server.md#httpmiddleware) bounds decompressed request bodies and rejects unsupported codings with `415` ([#9138](https://github.com/Effect-TS/effect/pull/9138)). `retryTransient` honors `Retry-After` ([#9053](https://github.com/Effect-TS/effect/pull/9053)); Node clients have typed Unix-socket/mTLS connection options ([#9158](https://github.com/Effect-TS/effect/pull/9158)).
- [`FileSystem.File.Info`](./interfaces/platform-runtime-hosts.md#filesystem) uses `bigint` for `dev` and `Option<bigint>` for `ino`, `rdev`, `nlink`, and `blocks`; account for this in serialization ([#9112](https://github.com/Effect-TS/effect/pull/9112)). File opens accept `noFollow` on supported POSIX hosts, and reads/writes accept explicit positions ([#8900](https://github.com/Effect-TS/effect/pull/8900)). [`Path.resolveWithin`](./interfaces/platform-runtime-hosts.md#path) rejects rooted paths and lexical traversal escapes; it does not prevent symlink escapes ([#9127](https://github.com/Effect-TS/effect/pull/9127)).
- WebSocket clients on Node/Bun accept handshake headers ([#8978](https://github.com/Effect-TS/effect/pull/8978)); TLS upgrades accept an explicit `servername` ([#9010](https://github.com/Effect-TS/effect/pull/9010)). See [Sockets](./interfaces/platform-runtime-hosts.md#socket). [`Stdio.stderrIsTerminal`](./interfaces/platform-runtime-hosts.md#stdio) detects stderr separately ([#8938](https://github.com/Effect-TS/effect/pull/8938)); Esc now cancels default Node/Bun/Deno terminal input unless `shouldQuit` overrides it ([#8934](https://github.com/Effect-TS/effect/pull/8934)).
- SQL COMMIT failures propagate as typed `SqlError` when cleanup succeeds; failed cleanup preserves both failures as defects ([#8892](https://github.com/Effect-TS/effect/pull/8892)). Single-connection clients exclude competing statements for the whole statement/stream lifetime ([#8927](https://github.com/Effect-TS/effect/pull/8927)). PostgreSQL adds TCP `keepAlive` ([#9120](https://github.com/Effect-TS/effect/pull/9120)). See [SQL](./interfaces/sql.md).
- RPC socket clients expose `onPingTimeout`, distinct from other disconnects ([#8976](https://github.com/Effect-TS/effect/pull/8976)); response-encoding failures reach `ErrorReporter` ([#8943](https://github.com/Effect-TS/effect/pull/8943)). See [RPC](./interfaces/rpc.md).

**MCP, AI, and durable execution**

- [`McpServer.layerHttpRequestScoped`](./systems/mcp.md#request-scoped-http-and-typed-requirements) owns all server work within each POST for serverless hosts. It accepts only stateless adapters and has no sessions, subscriptions, or session termination ([#9031](https://github.com/Effect-TS/effect/pull/9031)). Long-lived `layerHttp` gains `allowSubscriptions: false` ([#8924](https://github.com/Effect-TS/effect/pull/8924)). Resource-template and prompt-completion schema services now appear in Layer requirements, so previously incomplete compositions can fail type checking ([#9151](https://github.com/Effect-TS/effect/pull/9151), [#9135](https://github.com/Effect-TS/effect/pull/9135)).
- With manual tool resolution, [`toolCallValidation: "deferred"`](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch) returns model-generated calls with `unknown` parameters and possibly undeclared names. Strict validation remains the default; validate before authorizing or dispatching ([#9008](https://github.com/Effect-TS/effect/pull/9008)).
- [Decisions](./systems/ai-language-models.md#decision) accept structured descriptions and score legends. **Migration:** `Rate.criteria` entries are `{ label, description }` objects, not strings ([#9124](https://github.com/Effect-TS/effect/pull/9124)). OpenAI adds a Decisions provider; OpenAI-compatible response augmentation moves to the `openai-compat` metadata key ([#9140](https://github.com/Effect-TS/effect/pull/9140)). Regenerated OpenAI bindings also change public provider types ([#9067](https://github.com/Effect-TS/effect/pull/9067)); review the [provider migration notes](./systems/ai-language-models.md#provider-packages).
- OpenAI treats unknown model names as reasoning models by default; set `reasoningModel: false` for custom non-reasoning names ([#8980](https://github.com/Effect-TS/effect/pull/8980)). OpenAI-compatible configuration removes unsupported `store` and `conversation` fields ([#9011](https://github.com/Effect-TS/effect/pull/9011)); provider-specific tool-call fields survive replay ([#8916](https://github.com/Effect-TS/effect/pull/8916)). See [Provider packages](./systems/ai-language-models.md#provider-packages).
- [`Workflow.execute({ discard: true, detached: true })`](./systems/workflows-durable-execution.md#detached-children-and-failure-suspended-recovery) starts a child that neither wakes nor inherits interruption from its parent ([#9092](https://github.com/Effect-TS/effect/pull/9092)). Failure-suspended workflows require explicit resume before failed activities retry ([#9091](https://github.com/Effect-TS/effect/pull/9091)). [`PersistedQueue.offer({ delay })`](./tooling/persistence.md#persistedqueue) postpones first delivery, not retries ([#8907](https://github.com/Effect-TS/effect/pull/8907)).
- Cluster SQL storage separates owner-connection migrations from application storage Layers ([#8897](https://github.com/Effect-TS/effect/pull/8897)). `InterruptOnTermination` opts RPCs into early entity interruption ([#8963](https://github.com/Effect-TS/effect/pull/8963)); shutdown hands shards off individually with bounded waits ([#8941](https://github.com/Effect-TS/effect/pull/8941)). Transactional replies publish only after commit or clean rollback, with local replies recoverable from storage ([#8891](https://github.com/Effect-TS/effect/pull/8891), [#9176](https://github.com/Effect-TS/effect/pull/9176)). See [Cluster](./systems/cluster-sharding.md).

**Telemetry, data, time, and tooling**

- Cluster entity RPC spans now use only the entity type in their names; `entity.id` remains an attribute ([#9094](https://github.com/Effect-TS/effect/pull/9094)). Update name-based dashboards. See [ClusterMetrics](./systems/cluster-sharding.md#clustermetrics).
- Built-in OTLP exporters accept opt-in gzip configuration, including per-signal environment overrides ([#9139](https://github.com/Effect-TS/effect/pull/9139)). Subsequent delta histograms omit cumulative extrema ([#8987](https://github.com/Effect-TS/effect/pull/8987)); 64-bit trace IDs are padded to 128 bits ([#9117](https://github.com/Effect-TS/effect/pull/9117)). OTel log records carry the active Effect span context ([#9125](https://github.com/Effect-TS/effect/pull/9125)). See [Telemetry Export](./operations/telemetry-export.md).
- JSON Schema output for [`Schema.Int`](./data/schema-tooling.md#jsonschema) includes safe-integer bounds, and colliding bounds compact to the tighter one ([#8956](https://github.com/Effect-TS/effect/pull/8956), [#9081](https://github.com/Effect-TS/effect/pull/9081)). Refresh snapshots rather than removing those constraints. `SchemaError` serializes compactly ([#8895](https://github.com/Effect-TS/effect/pull/8895)); tagged unions reject duplicate discriminator keys at compile time ([#9103](https://github.com/Effect-TS/effect/pull/9103)). `StructWithRest` accepts optional fields ([#9020](https://github.com/Effect-TS/effect/pull/9020)); see [Schema unions and records](./data/schema.md#4-unions-literals-records-tuples).
- Zoned `DateTime.add`/`subtract` apply hours and smaller units as elapsed time across DST; calendar units remain wall-clock operations ([#9048](https://github.com/Effect-TS/effect/pull/9048)). Duration conversions handle very large milliseconds and nanosecond scaling without the earlier precision/overflow failures ([#9109](https://github.com/Effect-TS/effect/pull/9109), [#9161](https://github.com/Effect-TS/effect/pull/9161), [#8972](https://github.com/Effect-TS/effect/pull/8972)). See [Time](./concurrency/scheduling-time.md).
- [`TestClock.adjust`/`setTime`](./tooling/testing-dev-tooling.md#testclock) track woken fibers across yields and child joins, so newly registered sleeps within the target interval are not skipped ([#9172](https://github.com/Effect-TS/effect/pull/9172)). Establish initial readiness explicitly; virtual time is not a general startup barrier.
- [`Sse`](./concurrency/streaming-channels.md#sse) can dispatch empty named events for protocols such as GraphQL SSE ([#8979](https://github.com/Effect-TS/effect/pull/8979)); its encoder handles CR/CRLF data lines ([#9096](https://github.com/Effect-TS/effect/pull/9096)). Async-iterator stream timeouts stop even when `next()` never settles ([#9106](https://github.com/Effect-TS/effect/pull/9106)).
- [`Match`](./data/functional-toolkit.md#match) narrows only a matched array prefix and rejects unknown object-pattern keys ([#9088](https://github.com/Effect-TS/effect/pull/9088), [#9098](https://github.com/Effect-TS/effect/pull/9098)). Mutable `Array.match` callbacks retain mutable non-empty array types ([#9055](https://github.com/Effect-TS/effect/pull/9055)).
- The CLI gains [`Flag.withOptionalValue`](./tooling/cli-framework.md#gnu-style-optional-flag-values) for `--flag[=VALUE]` ([#9145](https://github.com/Effect-TS/effect/pull/9145)), PowerShell completions ([#8904](https://github.com/Effect-TS/effect/pull/8904)), and `CliOutput.displayWidth` ([#8982](https://github.com/Effect-TS/effect/pull/8982)). Prompts honor `NO_COLOR` and acquire stdin only when needed ([#8933](https://github.com/Effect-TS/effect/pull/8933), [#8932](https://github.com/Effect-TS/effect/pull/8932)).

### Changes in the handbook

- Added [GraphQL](./interfaces/graphql.md) 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](./index.md#version-and-validation-scope); 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.

## `effect@4.0.2` — audited 2026-10-09

Edition **4.0** (updated in place). Tag [`effect@4.0.2`](https://github.com/Effect-TS/effect/tree/effect%404.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.

### Changes in Effect that matter to readers

**Stability**

- Every module and directly importable export now carries an explicit `@stability` tag ([#8770](https://github.com/Effect-TS/effect/pull/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](./index.md#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](https://github.com/Effect-TS/effect/pull/8799)). See [Failure, Retry, Fallback, and Interruption](./deep-dives/failure-retry-fallback-and-interruption.md).
- 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](https://github.com/Effect-TS/effect/pull/8652)). See [Fiber](./foundations/fibers-scopes-runtimes.md#fiber).
- `Config.orElse` recovers only a pure `ConfigError`; a cause that mixes it with a defect or interruption propagates ([#8808](https://github.com/Effect-TS/effect/pull/8808)). See [Configuration & Secrets](./foundations/configuration-secrets.md).
- `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](https://github.com/Effect-TS/effect/pull/8719)). `cachedInvalidateWithTTL` accepts a TTL computed from the `Exit` ([#8734](https://github.com/Effect-TS/effect/pull/8734)). See [Caching & Batching](./operations/caching-batching.md).

**Streams and STM**

- `Stream.scan` emits its seed for an empty stream ([#8704](https://github.com/Effect-TS/effect/pull/8704)). `groupedWithin`, `aggregateWithin`, and `aggregate` pause their schedule while idle ([#8718](https://github.com/Effect-TS/effect/pull/8718)). `groupBy` and `partition` substreams shut down their queue when the consumer stops early ([#8857](https://github.com/Effect-TS/effect/pull/8857)). See [Streaming & Channels](./concurrency/streaming-channels.md).
- Waiting on `TxSemaphore` and `TxReentrantLock` is interruptible ([#8805](https://github.com/Effect-TS/effect/pull/8805)); PubSub rejects `NaN` and fractional capacities ([#8790](https://github.com/Effect-TS/effect/pull/8790)).

**Telemetry names (update dashboards and alerts)**

- Interrupt-only spans end with status `Unset` and `effect.fiber.interrupted: true` instead of `Ok` ([#8864](https://github.com/Effect-TS/effect/pull/8864)).
- `OtlpMetrics` exports a summary as one OTLP `Summary` metric named by its id instead of `<id>_quantiles` / `_count` / `_sum` ([#8869](https://github.com/Effect-TS/effect/pull/8869)).
- With `@effect/opentelemetry`, a span without an Effect parent inherits the active OpenTelemetry span ([#8586](https://github.com/Effect-TS/effect/pull/8586)). See [Observability](./operations/observability.md).
- 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](https://github.com/Effect-TS/effect/pull/8866)). See [SQL](./interfaces/sql.md).
- 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](https://github.com/Effect-TS/effect/pull/8867)). See [RPC](./interfaces/rpc.md).
- HTTP server spans capture no request or response headers unless `HttpMiddleware.TracerHeaderFilter` opts them in ([#8873](https://github.com/Effect-TS/effect/pull/8873)). See [HTTP Server](./interfaces/http-server.md).
- GenAI telemetry follows the current OpenTelemetry conventions: `addGenAIAnnotations` takes `provider: { name }` (the `system` option is removed), and Anthropic usage includes cached tokens ([#8870](https://github.com/Effect-TS/effect/pull/8870)). See [AI & Language Models](./systems/ai-language-models.md).

**Interfaces and AI**

- HttpApi answers a response-encoding failure with `500` and reports it to `ErrorReporter`; request-decoding failures stay `400` and unreported ([#8834](https://github.com/Effect-TS/effect/pull/8834)). See [HttpApi](./interfaces/http-api.md).
- RPC socket clients accept `pingInterval` and `pingTimeout` ([#8825](https://github.com/Effect-TS/effect/pull/8825)).
- `McpServer.layerHttp` gains opt-in `allowSessionTermination` ([#8773](https://github.com/Effect-TS/effect/pull/8773)). See [Exposing an Effect Application over MCP](./deep-dives/exposing-an-effect-application-over-mcp.md).
- `DecisionModel.decide` accepts images for providers that opt in ([#8832](https://github.com/Effect-TS/effect/pull/8832)); Anthropic preserves multiple system instructions ([#8603](https://github.com/Effect-TS/effect/pull/8603)).
- PostgreSQL `SqlEventJournal` stores entry and remote ids as `BYTEA`; existing tables need a migration ([#8756](https://github.com/Effect-TS/effect/pull/8756)). See [Event Log & Event Sourcing](./systems/event-log-event-sourcing.md).
- `Schema.toTaggedUnion` and `Schema.TaggedUnion` expose the discriminator key as `.tag` ([#8748](https://github.com/Effect-TS/effect/pull/8748)). See [Schema](./data/schema.md).

**New public surfaces**

- `effect/Version` (unstable): the `effect` version reported in telemetry. See [Version](./foundations/fibers-scopes-runtimes.md#version).
- `@effect/ai-cloudflare`: a Cloudflare Workers AI `DecisionModel` provider. See [AI & Language Models](./systems/ai-language-models.md).

### Changes in the handbook

- 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](https://effect.website/docs/v4/scheduling/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.
- Split the five largest pages: Schema into [Schema](./data/schema.md), [Schema in Depth](./data/schema-in-depth.md), and [Schema Tooling & Internals](./data/schema-tooling.md); [Fibers, Scopes & Runtimes](./foundations/fibers-scopes-runtimes.md) out of Core Runtime; [Generated-Code Anti-Patterns](./troubleshooting/anti-patterns.md) out of Troubleshooting; [MCP Servers](./systems/mcp.md) out of AI; and [Telemetry Export](./operations/telemetry-export.md) out of Observability. Old deep links to moved sections redirect to their new pages.
- 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](./operations/telemetry-export.md) 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](./troubleshooting/anti-patterns.md#effect-3-names-that-do-not-exist-in-effect-4) 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.

## `effect@4.0.0` — audited 2026-10-01

Edition **4.0** (first edition). Tag [`effect@4.0.0`](https://github.com/Effect-TS/effect/tree/effect%404.0.0), commit `67ba4e46`, published 2026-10-01: the first stable release of Effect 4 and the baseline for every later entry.

### Changes in the handbook

- Audited every page and example against the tagged source; Getting Started covers installation, compiler settings, and the `@stability` model ([PR #2](https://github.com/eugene1g/effect-handbook/pull/2)).
- Added the long-form [MCP deep dive](./deep-dives/exposing-an-effect-application-over-mcp.md), Markdown twins for every page, `llms.txt`, and the [agent reading protocol](./reference/agent-guide.md) ([PR #2](https://github.com/eugene1g/effect-handbook/pull/2)).
- Routed web-framework intents (Express, Hono, Fastify) to `ManagedRuntime` in the capability catalog ([PR #3](https://github.com/eugene1g/effect-handbook/pull/3)).
- Introduced editions: one handbook per Effect `major.minor`, served at `/<major.minor>/`, with an edition switcher and `versions.json` ([PR #4](https://github.com/eugene1g/effect-handbook/pull/4)).

# Deep-Dive Architecture Summaries

These compact maps preserve the composition model in agent context. Fetch a linked long-form page only when the task needs its connected tutorial.

## Reactivity — From Atoms to Mastery

Architecture: AtomRegistry owns the reactive graph and lifecycle; Atom.runtime supplies Effect services; Reactivity keys drive targeted invalidation; Hydration crosses the SSR boundary; framework bindings consume AsyncResult without hiding typed failures.

Human deep dive: [deep-dives/reactivity-from-atoms-to-mastery.md](./deep-dives/reactivity-from-atoms-to-mastery.md)

## Adopting Effect in an Existing TypeScript Codebase

Architecture: audit each function for hidden failure, dependency, lifetime, and cancellation behavior; pin current behavior with characterization tests; migrate leaf-first behind an unchanged external contract; keep exactly one seam where Promise meets Effect; make adapters cancellable before adding retry or timeout policy; take early test wins with provideService.

Human deep dive: [deep-dives/adopting-effect-in-an-existing-codebase.md](./deep-dives/adopting-effect-in-an-existing-codebase.md)

## Anatomy of a Real Effect Application

Architecture: schemas and tagged errors define domain boundaries; Context services separate policy from infrastructure; live and test Layers compose Config, SQL/HTTP resources, and observability; one scoped entrypoint owns startup, interruption, finalizers, and shutdown.

Human deep dive: [deep-dives/anatomy-of-a-real-effect-application.md](./deep-dives/anatomy-of-a-real-effect-application.md)

## Owning Lifetimes — Startup, Readiness, and Shutdown

Architecture: every resource and fiber has one named owner scope; startup is a transaction that either completes or releases what it acquired; readiness and draining are explicit states separate from liveness; one shutdown operation closes intake, drains, then releases in reverse order; callback bridges into host frameworks carry cancellation and never outlive their owner.

Human deep dive: [deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md](./deep-dives/owning-lifetimes-startup-readiness-and-shutdown.md)

## Schema — From External Input to Domain and Back

Architecture: decode unknown encoded input once at each boundary, operate on validated Type values internally, and encode deliberately for HTTP, RPC, SQL, or persistence; transformations, classes, versioned representations, and property tests preserve the contract.

Human deep dive: [deep-dives/schema-from-external-input-to-domain-and-back.md](./deep-dives/schema-from-external-input-to-domain-and-back.md)

## Failure, Retry, Fallback, and Interruption

Architecture: model expected failures in E, retain defects and interruption in Cause, classify before retrying, constrain Schedule policies, keep fallback semantics explicit, and acquire resources in Scope so interruption cannot skip cleanup.

Human deep dive: [deep-dives/failure-retry-fallback-and-interruption.md](./deep-dives/failure-retry-fallback-and-interruption.md)

## Structured Concurrency Through a Bounded Worker

Architecture: a bounded Queue owns backpressure, scoped child fibers own worker lifetime, concurrency is explicit, shutdown closes intake and joins/interrupts workers, and tests assert capacity, cleanup, and interruption rather than timing by sleep.

Human deep dive: [deep-dives/structured-concurrency-through-a-bounded-worker.md](./deep-dives/structured-concurrency-through-a-bounded-worker.md)

## Testing an Effect Application

Architecture: substitute services with test Layers, inspect typed errors and Exit values, virtualize time, verify resource finalizers and fiber behavior, and reserve live integration Layers for the boundary behavior a unit test cannot prove.

Human deep dive: [deep-dives/testing-an-effect-application.md](./deep-dives/testing-an-effect-application.md)

## Streaming Ingestion Without Accidental Buffering

Architecture: Stream pulls incrementally, transformations preserve backpressure, Sink/Channel handle consumption and protocol seams, bounded batching limits memory, and Scope owns sources and destinations; restart recovery requires explicit record identity, checkpoints, idempotent writes, or a durable job boundary.

Human deep dive: [deep-dives/streaming-ingestion-without-accidental-buffering.md](./deep-dives/streaming-ingestion-without-accidental-buffering.md)

## The Durability and Distribution Ladder

Architecture: choose the lowest rung that meets the guarantee—Persistence for current state/results, EventLog for replayable history, Workflow for restartable orchestration, and Cluster entities for distributed identity and ownership—while designing external effects for at-least-once delivery.

Human deep dive: [deep-dives/durability-and-distribution-ladder.md](./deep-dives/durability-and-distribution-ladder.md)

## Building a Production AI Capability

Architecture: provider-neutral LanguageModel services sit behind Layers; Schema constrains structured outputs and tools; Toolkit/Chat controls tool execution; retry and observability wrap provider calls; MCP is an explicit external protocol boundary with transport security and lifecycle requirements.

Human deep dive: [deep-dives/building-a-production-ai-capability.md](./deep-dives/building-a-production-ai-capability.md)

## Exposing an Effect Application over MCP

Architecture: McpServer is an external boundary over an existing Toolkit, not the agent loop; one server declares its protocol eras and serves stateless and session clients alike; the catalog is shaped with annotations, Tool.Strict, and EnabledWhen; HttpRouter middleware makes the server an OAuth resource server that derives tenant and scopes from token claims; human approval uses elicit on session eras and an HMAC-sealed InputRequired round trip on the stateless era; retried calls are idempotent; the server is tested in-process through HttpRouter.toWebHandler.

Human deep dive: [deep-dives/exposing-an-effect-application-over-mcp.md](./deep-dives/exposing-an-effect-application-over-mcp.md)
