Effect-TS
Effect is a TypeScript library for building production-grade software with typed errors, structured concurrency, dependency injection, and built-in observability.
Version Detection
Before writing Effect code, detect which version the user is on:
# Check installed version
cat package.json | grep '"effect"'
- v4.x (recommended, the direction Effect is heading):
Context.Service, Effect.catch, Effect.forkChild, Schema.TaggedErrorClass
- v3.x (stable, still common in production):
Context.Tag, Effect.catchAll, Effect.fork, Data.TaggedError
Note: v4 beta briefly used a ServiceMap module, renamed back to Context on 2026-04-07 (PR #1961). If you see ServiceMap.* in any doc or older beta code, it is the current Context.*. Both v3 and v4 import Context from "effect"; the exports inside differ (Context.Service in v4 vs Context.Tag in v3).
Prefer v4 for new projects - it's where Effect is going. In an existing codebase, match the installed version: don't rewrite v3 code in v4 syntax unless asked. If the version is genuinely unclear, default to v4 and say so. v4 is still in beta, so pin an exact version (4.0.0-beta.x) and expect occasional API churn.
Primary Documentation Sources
v4 (primary):
v3 (for existing codebases):
Both versions:
AI Guardrails: Critical Corrections
LLM outputs frequently contain incorrect Effect APIs. Verify every API against the reference docs before using it.
Common hallucinations (both versions):
| Wrong (AI often generates) |
Correct |
Effect.cachedWithTTL(...) |
Cache.make({ capacity, timeToLive, lookup }) |
Effect.cachedInvalidateWithTTL(...) |
cache.invalidate(key) / cache.invalidateAll() |
Effect.mapError(effect, fn) |
Effect.mapError(fn) in pipe, or use Effect.catchTag |
import { Schema } from "@effect/schema" |
import { Schema } from "effect" (v3.10+ and all v4) |
import { JSONSchema } from "@effect/schema" |
import { JSONSchema } from "effect" (v3.10+) |
| JSON Schema Draft 2020-12 |
Effect Schema generates Draft-07 |
| "thread-local storage" |
"fiber-local storage" via FiberRef (v3) / Context.Reference (v4) |
| fibers are "cancelled" |
fibers are "interrupted" |
| all queues have back-pressure |
only bounded queues; sliding/dropping do not |
new MyError("message") |
new MyError({ message: "..." }) (Schema errors take objects) |
v3-specific hallucinations:
| Wrong |
Correct (v3) |
Effect.Service (function call) |
class Foo extends Effect.Service<Foo>()("id", {}) |
Effect.match(effect, { ... }) |
Effect.match(effect, { onSuccess, onFailure }) |
Effect.provide(layer1, layer2) |
Effect.provide(Layer.merge(layer1, layer2)) |
v4-specific hallucinations (AI may mix v3/v4):
| Wrong (v3 API used in v4 code) |
Correct (v4) |
Context.Tag("X") (v3 shape) |
Context.Service<X>(id) or class syntax |
ServiceMap.Service / ServiceMap.Reference |
Renamed back to Context.Service / Context.Reference on 2026-04-07 |
Effect.catchAll(fn) |
Effect.catch(fn) |
Effect.fork(effect) |
Effect.forkChild(effect) |
Effect.forkDaemon(effect) |
Effect.forkDetach(effect) |
Data.TaggedError |
Schema.TaggedErrorClass |
FiberRef.get(ref) |
yield* References.X (a Context.Reference) |
yield* ref (Ref as Effect) |
yield* Ref.get(ref) (Ref is no longer an Effect) |
yield* fiber (Fiber as Effect) |
yield* Fiber.join(fiber) (Fiber is no longer Effect) |
Logger.Default / Logger.Live |
Logger.layer (v4 naming convention) |
Schema.TaggedError |
Schema.TaggedErrorClass |
Schema.makeUnsafe(input) |
Schema.make(input) (throws SchemaError); also instance methods schema.makeOption(...), schema.makeEffect(...) |
ParseResult (from "effect") |
SchemaIssue module + SchemaError class; narrow with Schema.isSchemaError |
HttpApiEndpoint.get(n, p).pipe(HttpApiEndpoint.setPath(...), setPayload(...), setSuccess(...)) |
HttpApiEndpoint.get(n, p, { params, query, payload, success, error }) (object-option form) |
Otlp.layer({ url, serviceName }) |
OtlpTracer.layer({ url, resource: { serviceName } }) + OtlpSerialization.layerJson + FetchHttpClient.layer |
import { HttpApi } from "@effect/platform" (v4) |
import { HttpApi } from "effect/unstable/httpapi" |
| HttpApi endpoint schema errors are typed errors by default |
In current v4 betas they default to defects unless transformed |
Read references/llm-corrections.md for the exhaustive corrections table.
Progressive Disclosure
Read only the reference files relevant to your task:
- Error modeling or typed failures →
references/error-modeling.md
- Services, DI, or Layer wiring →
references/dependency-injection.md
- Per-key dynamic layers (per-tenant resources,
LayerMap) → references/dependency-injection.md
- Bridging Effect into non-Effect frameworks (Hono/Express,
ManagedRuntime) → references/dependency-injection.md
- Retries, timeouts, or backoff →
references/retry-scheduling.md
- Fibers, forking, or parallel work →
references/concurrency.md
- Request batching, N+1 elimination, DataLoader pattern →
references/concurrency.md
- Multi-provider fallback (
ExecutionPlan) → references/effect-ai.md / references/retry-scheduling.md
- Streams, queues, or SSE →
references/streams.md
- Framing streams (NDJSON / MessagePack encode-decode) →
references/streams.md
- Running child processes / shelling out →
references/concurrency.md
- Resource lifecycle or cleanup →
references/resource-management.md
- Refreshable values (rotating credentials, polled config) →
references/resource-management.md
- Reference-counted shared resources (
RcRef/RcMap) → references/resource-management.md
- Schema validation or decoding →
references/schema.md
- Branded / nominal types (
Brand) → references/schema.md
- Logging, metrics, or tracing →
references/observability.md
- HTTP clients or API calls →
references/http.md
- HTTP API servers →
references/http.md (covers both client and server)
- File uploads / multipart form-data →
references/http.md
- LLM/AI integration →
references/effect-ai.md
- Configuration, env vars, secrets →
references/configuration.md
- SQL / database access →
references/sql.md
- Command-line apps →
references/cli.md
- Typed client/server RPC →
references/rpc.md
- Sharded entities, durable workflows, event sourcing →
references/distributed.md
- Transactional state (STM,
Tx*) → references/stm.md
- Date/time handling →
references/datetime.md
- Immutable nested updates (optics) →
references/optics.md
- Graphs, dependency ordering, shortest paths, cycle detection →
references/graph.md
- Pattern matching (
Match) → references/core-patterns.md
- Pooling resources (
Pool) → references/resource-management.md
- Fiber sets, SubscriptionRef, worker threads →
references/concurrency.md
- Testing Effect code →
references/testing.md
- Property-based testing / generating data from schemas →
references/testing.md
- Migrating from async/await →
references/migration-async.md
- Migrating from v3 to v4 →
references/migration-v4.md
- Core types, gen, pipe, running →
references/core-patterns.md
- Full wrong-vs-correct API table →
references/llm-corrections.md
Core Workflow
- Detect version from
package.json before writing any code
- Clarify boundaries: identify where IO happens, keep core logic as
Effect values
- Choose style: use
Effect.gen for sequential logic, pipelines for simple transforms. In v4, prefer Effect.fn("name") for named functions
- Model errors explicitly: type expected errors in the
E channel; treat bugs as defects
- Model dependencies with services and layers; keep interfaces free of construction logic
- Manage resources with
Scope when opening/closing things (files, connections, etc.)
- Provide layers and run effects only at program edges (
NodeRuntime.runMain or ManagedRuntime)
- Verify APIs exist before using them - consult https://tim-smart.github.io/effect-io-ai/ or source docs
Starter Function Set
Start with these ~20 functions (the official recommended set):
Creating effects: Effect.succeed, Effect.fail, Effect.sync, Effect.tryPromise
Composition: Effect.gen (+ Effect.fn in v4), Effect.andThen, Effect.map, Effect.tap, Effect.all
Running: Effect.runPromise, NodeRuntime.runMain (preferred for entry points)
Error handling: Effect.catchTag, Effect.catch (v4) / Effect.catchAll (v3), Effect.orDie
Resources: Effect.acquireRelease, Effect.acquireUseRelease, Effect.scoped
Dependencies: Effect.provide, Effect.provideService
Key modules: Effect, Schema, Layer, Option, Result (v4) / Either (v3), Array, Match
DI (v4): Context.Service, Context.Reference, Layer.effect, Effect.fn("name")
DI (v3): Context.Tag, Context.Reference
Import Patterns
Always use barrel imports from "effect":
import { Context, Effect, Schema, Layer, Option, Stream } from "effect"
For companion packages, import from the package name. v3 and v4 differ here:
// v4 (recommended) - platform transports still separate, but HttpApi / observability
// moved under effect/unstable/*
import { NodeRuntime } from "@effect/platform-node"
import { FetchHttpClient } from "effect/unstable/http"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiBuilder, HttpApiScalar } from "effect/unstable/httpapi"
import { OtlpLogger, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"
// v3 (stable) companion packages
import { NodeRuntime } from "@effect/platform-node"
import { HttpClient } from "@effect/platform"
import { NodeSdk } from "@effect/opentelemetry"
Avoid deep module imports (effect/Effect) unless your bundler requires it for tree-shaking.
Output Standards
- Show imports in every code example
- Prefer
Effect.gen (imperative) for multi-step logic; pipelines for transforms
- In v4, use
Effect.fn("name") instead of bare Effect.gen for named functions; use Effect.fnUntraced for internal helpers that don't need a span/stack-frame
- Never call
Effect.runPromise / Effect.runSync inside library code - only at program edges
- Use
NodeRuntime.runMain for CLI/server entry points (handles SIGINT gracefully)
- Use
ManagedRuntime when integrating Effect into non-Effect frameworks (Hono, Express, etc.)
- Always
return yield* when raising an error in a generator (ensures TS understands control flow)
- Avoid point-free/tacit usage: write
Effect.map((x) => fn(x)) not Effect.map(fn) (generics get erased)
- Keep dependency graphs explicit (services, layers, tags)
- State the
Effect<A, E, R> shape when it helps design decisions
Agent Quality Checklist
Before outputting Effect code, verify:
1---2name: effect-ts3description: Effect-TS guide for TypeScript, v4 default with v3 support. Use when writing, debugging, or reviewing Effect code across errors, concurrency, services, streams, and schema, or when code imports from 'effect' or any '@effect/*' package.4---56# Effect-TS78Effect is a TypeScript library for building production-grade software with typed errors, structured concurrency, dependency injection, and built-in observability.910## Version Detection1112Before writing Effect code, detect which version the user is on:1314```bash15# Check installed version16cat package.json | grep '"effect"'17```1819- **v4.x** (recommended, the direction Effect is heading): `Context.Service`, `Effect.catch`, `Effect.forkChild`, `Schema.TaggedErrorClass`20- **v3.x** (stable, still common in production): `Context.Tag`, `Effect.catchAll`, `Effect.fork`, `Data.TaggedError`2122> Note: v4 beta briefly used a `ServiceMap` module, renamed back to `Context` on 2026-04-07 (PR #1961). If you see `ServiceMap.*` in any doc or older beta code, it is the current `Context.*`. Both v3 and v4 import `Context` from `"effect"`; the exports inside differ (`Context.Service` in v4 vs `Context.Tag` in v3).2324**Prefer v4 for new projects** - it's where Effect is going. In an existing codebase, match the installed version: don't rewrite v3 code in v4 syntax unless asked. If the version is genuinely unclear, default to v4 and say so. v4 is still in beta, so pin an exact version (`4.0.0-beta.x`) and expect occasional API churn.2526## Primary Documentation Sources2728**v4 (primary):**29- https://github.com/Effect-TS/effect-smol (v4 source + migration guides)30- https://github.com/Effect-TS/effect-smol/blob/main/LLMS.md (v4 LLM guide)3132**v3 (for existing codebases):**33- https://effect.website/docs (v3 stable docs)34- https://effect.website/llms.txt (LLM topic index)35- https://effect.website/llms-full.txt (full docs for large context)3637**Both versions:**38- https://tim-smart.github.io/effect-io-ai/ (concise API list)3940## AI Guardrails: Critical Corrections4142LLM outputs frequently contain incorrect Effect APIs. Verify every API against the reference docs before using it.4344**Common hallucinations (both versions):**4546| Wrong (AI often generates) | Correct |47|----------------------------------------------|---------------------------------------------------------------|48| `Effect.cachedWithTTL(...)` | `Cache.make({ capacity, timeToLive, lookup })` |49| `Effect.cachedInvalidateWithTTL(...)` | `cache.invalidate(key)` / `cache.invalidateAll()` |50| `Effect.mapError(effect, fn)` | `Effect.mapError(fn)` in pipe, or use `Effect.catchTag` |51| `import { Schema } from "@effect/schema"` | `import { Schema } from "effect"` (v3.10+ and all v4) |52| `import { JSONSchema } from "@effect/schema"`| `import { JSONSchema } from "effect"` (v3.10+) |53| JSON Schema Draft 2020-12 | Effect Schema generates **Draft-07** |54| "thread-local storage" | "fiber-local storage" via `FiberRef` (v3) / `Context.Reference` (v4) |55| fibers are "cancelled" | fibers are "interrupted" |56| all queues have back-pressure | only **bounded** queues; sliding/dropping do not |57| `new MyError("message")` | `new MyError({ message: "..." })` (Schema errors take objects) |5859**v3-specific hallucinations:**6061| Wrong | Correct (v3) |62|------------------------------------|-----------------------------------------------------|63| `Effect.Service` (function call) | `class Foo extends Effect.Service<Foo>()("id", {})` |64| `Effect.match(effect, { ... })` | `Effect.match(effect, { onSuccess, onFailure })` |65| `Effect.provide(layer1, layer2)` | `Effect.provide(Layer.merge(layer1, layer2))` |6667**v4-specific hallucinations (AI may mix v3/v4):**6869| Wrong (v3 API used in v4 code) | Correct (v4) |70|-----------------------------------|------------------------------------------------------|71| `Context.Tag("X")` (v3 shape) | `Context.Service<X>(id)` or class syntax |72| `ServiceMap.Service` / `ServiceMap.Reference` | Renamed back to `Context.Service` / `Context.Reference` on 2026-04-07 |73| `Effect.catchAll(fn)` | `Effect.catch(fn)` |74| `Effect.fork(effect)` | `Effect.forkChild(effect)` |75| `Effect.forkDaemon(effect)` | `Effect.forkDetach(effect)` |76| `Data.TaggedError` | `Schema.TaggedErrorClass` |77| `FiberRef.get(ref)` | `yield* References.X` (a `Context.Reference`) |78| `yield* ref` (Ref as Effect) | `yield* Ref.get(ref)` (Ref is no longer an Effect) |79| `yield* fiber` (Fiber as Effect) | `yield* Fiber.join(fiber)` (Fiber is no longer Effect) |80| `Logger.Default` / `Logger.Live` | `Logger.layer` (v4 naming convention) |81| `Schema.TaggedError` | `Schema.TaggedErrorClass` |82| `Schema.makeUnsafe(input)` | `Schema.make(input)` (throws `SchemaError`); also instance methods `schema.makeOption(...)`, `schema.makeEffect(...)` |83| `ParseResult` (from `"effect"`) | `SchemaIssue` module + `SchemaError` class; narrow with `Schema.isSchemaError` |84| `HttpApiEndpoint.get(n, p).pipe(HttpApiEndpoint.setPath(...), setPayload(...), setSuccess(...))` | `HttpApiEndpoint.get(n, p, { params, query, payload, success, error })` (object-option form) |85| `Otlp.layer({ url, serviceName })` | `OtlpTracer.layer({ url, resource: { serviceName } })` + `OtlpSerialization.layerJson` + `FetchHttpClient.layer` |86| `import { HttpApi } from "@effect/platform"` (v4) | `import { HttpApi } from "effect/unstable/httpapi"` |87| HttpApi endpoint schema errors are typed errors by default | In current v4 betas they default to **defects** unless transformed |8889**Read `references/llm-corrections.md` for the exhaustive corrections table.**9091## Progressive Disclosure9293Read only the reference files relevant to your task:9495- Error modeling or typed failures → `references/error-modeling.md`96- Services, DI, or Layer wiring → `references/dependency-injection.md`97- Per-key dynamic layers (per-tenant resources, `LayerMap`) → `references/dependency-injection.md`98- Bridging Effect into non-Effect frameworks (Hono/Express, `ManagedRuntime`) → `references/dependency-injection.md`99- Retries, timeouts, or backoff → `references/retry-scheduling.md`100- Fibers, forking, or parallel work → `references/concurrency.md`101- Request batching, N+1 elimination, DataLoader pattern → `references/concurrency.md`102- Multi-provider fallback (`ExecutionPlan`) → `references/effect-ai.md` / `references/retry-scheduling.md`103- Streams, queues, or SSE → `references/streams.md`104- Framing streams (NDJSON / MessagePack encode-decode) → `references/streams.md`105- Running child processes / shelling out → `references/concurrency.md`106- Resource lifecycle or cleanup → `references/resource-management.md`107- Refreshable values (rotating credentials, polled config) → `references/resource-management.md`108- Reference-counted shared resources (`RcRef`/`RcMap`) → `references/resource-management.md`109- Schema validation or decoding → `references/schema.md`110- Branded / nominal types (`Brand`) → `references/schema.md`111- Logging, metrics, or tracing → `references/observability.md`112- HTTP clients or API calls → `references/http.md`113- HTTP API servers → `references/http.md` (covers both client and server)114- File uploads / multipart form-data → `references/http.md`115- LLM/AI integration → `references/effect-ai.md`116- Configuration, env vars, secrets → `references/configuration.md`117- SQL / database access → `references/sql.md`118- Command-line apps → `references/cli.md`119- Typed client/server RPC → `references/rpc.md`120- Sharded entities, durable workflows, event sourcing → `references/distributed.md`121- Transactional state (STM, `Tx*`) → `references/stm.md`122- Date/time handling → `references/datetime.md`123- Immutable nested updates (optics) → `references/optics.md`124- Graphs, dependency ordering, shortest paths, cycle detection → `references/graph.md`125- Pattern matching (`Match`) → `references/core-patterns.md`126- Pooling resources (`Pool`) → `references/resource-management.md`127- Fiber sets, SubscriptionRef, worker threads → `references/concurrency.md`128- Testing Effect code → `references/testing.md`129- Property-based testing / generating data from schemas → `references/testing.md`130- Migrating from async/await → `references/migration-async.md`131- Migrating from v3 to v4 → `references/migration-v4.md`132- Core types, gen, pipe, running → `references/core-patterns.md`133- Full wrong-vs-correct API table → `references/llm-corrections.md`134135## Core Workflow1361371. **Detect version** from `package.json` before writing any code1382. **Clarify boundaries**: identify where IO happens, keep core logic as `Effect` values1393. **Choose style**: use `Effect.gen` for sequential logic, pipelines for simple transforms. In v4, prefer `Effect.fn("name")` for named functions1404. **Model errors explicitly**: type expected errors in the `E` channel; treat bugs as defects1415. **Model dependencies** with services and layers; keep interfaces free of construction logic1426. **Manage resources** with `Scope` when opening/closing things (files, connections, etc.)1437. **Provide layers** and run effects only at program edges (`NodeRuntime.runMain` or `ManagedRuntime`)1448. **Verify APIs exist** before using them - consult https://tim-smart.github.io/effect-io-ai/ or source docs145146## Starter Function Set147148Start with these ~20 functions (the official recommended set):149150**Creating effects:** `Effect.succeed`, `Effect.fail`, `Effect.sync`, `Effect.tryPromise`151152**Composition:** `Effect.gen` (+ `Effect.fn` in v4), `Effect.andThen`, `Effect.map`, `Effect.tap`, `Effect.all`153154**Running:** `Effect.runPromise`, `NodeRuntime.runMain` (preferred for entry points)155156**Error handling:** `Effect.catchTag`, `Effect.catch` (v4) / `Effect.catchAll` (v3), `Effect.orDie`157158**Resources:** `Effect.acquireRelease`, `Effect.acquireUseRelease`, `Effect.scoped`159160**Dependencies:** `Effect.provide`, `Effect.provideService`161162**Key modules:** `Effect`, `Schema`, `Layer`, `Option`, `Result` (v4) / `Either` (v3), `Array`, `Match`163164**DI (v4):** `Context.Service`, `Context.Reference`, `Layer.effect`, `Effect.fn("name")`165**DI (v3):** `Context.Tag`, `Context.Reference`166167## Import Patterns168169Always use barrel imports from `"effect"`:170171```typescript172import { Context, Effect, Schema, Layer, Option, Stream } from "effect"173```174175For companion packages, import from the package name. v3 and v4 differ here:176177```typescript178// v4 (recommended) - platform transports still separate, but HttpApi / observability179// moved under effect/unstable/*180import { NodeRuntime } from "@effect/platform-node"181import { FetchHttpClient } from "effect/unstable/http"182import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiBuilder, HttpApiScalar } from "effect/unstable/httpapi"183import { OtlpLogger, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"184185// v3 (stable) companion packages186import { NodeRuntime } from "@effect/platform-node"187import { HttpClient } from "@effect/platform"188import { NodeSdk } from "@effect/opentelemetry"189```190191Avoid deep module imports (`effect/Effect`) unless your bundler requires it for tree-shaking.192193## Output Standards194195- Show imports in every code example196- Prefer `Effect.gen` (imperative) for multi-step logic; pipelines for transforms197- In v4, use `Effect.fn("name")` instead of bare `Effect.gen` for named functions; use `Effect.fnUntraced` for internal helpers that don't need a span/stack-frame198- Never call `Effect.runPromise` / `Effect.runSync` inside library code - only at program edges199- Use `NodeRuntime.runMain` for CLI/server entry points (handles SIGINT gracefully)200- Use `ManagedRuntime` when integrating Effect into non-Effect frameworks (Hono, Express, etc.)201- Always `return yield*` when raising an error in a generator (ensures TS understands control flow)202- Avoid point-free/tacit usage: write `Effect.map((x) => fn(x))` not `Effect.map(fn)` (generics get erased)203- Keep dependency graphs explicit (services, layers, tags)204- State the `Effect<A, E, R>` shape when it helps design decisions205206## Agent Quality Checklist207208Before outputting Effect code, verify:209210- [ ] Every API exists (check against tim-smart API list or source docs)211- [ ] Imports are from `"effect"` (not `@effect/schema`, `@effect/io`, etc.)212- [ ] Version matches the user's codebase (v3 vs v4 syntax)213- [ ] Expected errors are typed in `E`; unexpected failures are defects214- [ ] `run*` is called only at program edges, not inside library code215- [ ] Resources opened with `acquireRelease` are wrapped in `Effect.scoped`216- [ ] Layers are provided before running (no missing `R` requirements)217- [ ] Generator bodies use `yield*` (not `yield` without `*`)218- [ ] Error raises in generators use `return yield*` pattern