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
Self-contained source · Type-checked
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(neverasync/awaitortry/catchinside them); useClock/DateTime(neverDate.now); write callbacks as lambdas —Effect.forEach(ids, (id) => loadBand(id)), notEffect.forEach(ids, loadBand), becauseforEachalso 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 |
| Choosing between primitives that all look plausible | Choosing Effect Primitives |
| Looking at a symptom, or checking generated code against known mistakes | Troubleshooting & Anti-Patterns |
| Reviewing a design or a diff | Review Checklists |
| Coming from Effect 3 | Migration guide |
| Moving an existing Promise codebase over, one leaf at a time | Adopting Effect in an Existing TypeScript Codebase |
| Wanting a connected walkthrough rather than a lookup | Deep Dives |
When several primitives look right
The companion Choosing Effect Primitives page is the contrastive layer: it compares error channels, required services, ownership, backpressure, durability, distribution, and the situations where each plausible choice is wrong.
| Decision | Detailed comparison |
|---|---|
Where a fact may be collapsed: absence, failure, unknown, requirements, execution, lifetime | Boundary rules before primitives |
| Which constructor wraps this JavaScript | Constructor by source convention |
| Which runner the host needs | Runner by host contract |
| Absence, pure failure, a recorded outcome, or effectful work | Option vs Result vs Effect |
| Which recovery operator expresses the intent | Recovery operator by intent |
| Stop at the first failure or collect them all | Fail fast or accumulate |
provideService, a Layer, { local: true }, or Layer.fresh | Providing dependencies by seam |
| Which fork, by who owns the fiber | Fork by owner |
| Which bracket, by how long the resource lives | Resource lifetime and bracket |
| One cell, effectful update, live changes, or atomic multi-value state | Ref vs SynchronizedRef vs SubscriptionRef vs transactions |
| One result, a gate, worker handoff, or broadcast | Deferred vs Latch vs Queue vs PubSub |
| Wait, shed, keep the latest, or grow without bound | Overload semantics at a glance |
| Local parallelism, a shared permit budget, or reusable objects | Per-call concurrency vs Semaphore vs Pool |
| One effect repeated, one key repeated, or many keys at once | Single-flight, cache, or batching |
| Cached values, cached resources, refresh, or batching | Cache vs ScopedCache vs Resource vs RequestResolver |
| Finite collections or incremental protocols | Array/Chunk/Iterable vs Stream/Sink/Channel |
| Buffer depth, batch size, or rate | Stream buffering and batching operators |
| JSON, NDJSON, SSE, or schema-derived binary frames | Wire codec: JSON, NDJSON, or SchemaBinary |
| Outbound HTTP, low-level routing, contract HTTP, or procedures | HttpClient vs HttpRouter vs HttpApi vs RPC |
| Failed attempts, successful repetition, polling, or restart survival | Retry vs repeat vs polling vs Workflow |
| Durable state, history, orchestration, or distributed identity | Persistence vs EventLog vs Workflow vs Cluster |
| Which test tool proves which claim | Test tool by claim |
| Who owns the runtime and what cancels work | 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 (tryPromise, callback, gen, fn) |
| Wrap a Promise or callback API so that a timeout really cancels it | Cancellable adapters: forward the signal |
Branch or loop (there is no Effect.if, unless, or loop) | plain if / for in Effect.gen, Effect.when |
| Run an effect from a host, keeping cancellation distinct | runPromiseExit with { signal } |
| Call Effect from Express, Hono, a UI, or a plugin API | ManagedRuntime, the ManagedRuntime recipe, and its production-shaped bridge |
| Carry a host request's abort through to the SDK call | Recipe: Request Cancellation Through a Host |
| Start a process and shut it down gracefully | platform runMain, the graceful entrypoint recipe, and readiness plus a bounded drain |
| Choose the host: process, Web handler, framework callback, browser, worker, test | Choosing a host |
| Fall back across providers or models | 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 |
| Recover from some failures and leave the rest typed | catchTag, catchIf, catchFilter, catchReason |
| Translate an error, or fail an unacceptable success | mapError, filterOrFail |
| Turn every outcome into one response | Effect.match / matchEffect |
| Collect every validation problem | Effect.validate, Effect.partition, mode: "result" |
| Map an error union to statuses or policies exhaustively | Match.exhaustive / tagsExhaustive |
| Keep a defect that sits beside a typed failure | a guarded catchCause |
Move between Option, Result, and Effect (they are not yieldable) | Effect.fromOption, Effect.fromResult |
| Decide what a failed cleanup means | When cleanup can fail |
| Undo partial in-process work | exit-aware finalizers |
| Combine retry with a timeout | Where the timeout sits relative to retry |
| Report defects at the process edge | ErrorReporter |
Depend and configure
| You want to… | Reach for |
|---|---|
| Inject a dependency | Context.Service + Layer and the service recipe |
Shape a service contract (R = never, no throws, domain verbs) | Designing a service contract |
| Provide one fake in a test without building a Layer | Effect.provideService |
| Know whether a pool is shared or rebuilt | What is shared, and what is rebuilt |
| Own a connection or client for the application's lifetime | Resourceful services |
| Use a capability only if the host installed it | Effect.serviceOption |
| Ambient, override-able settings | Context.Reference / References and the default services |
| Keep a value fresh in the background | Resource |
| One Layer per tenant or key | LayerMap |
| Read config / hide secrets | Config + ConfigProvider / Redacted (PascalCase constructors: Config.String, Config.Int, Config.Redacted, Config.Duration, Config.URL) |
| Define what a valid deployment looks like, once | Designing the startup contract |
| Default a setting without hiding a typo | Config.withDefault, not Config.orElse |
| Layer CLI overrides over environment over defaults | Precedence and composition |
| Decode a secret from a payload without ever encoding it back | Schema.RedactedFromValue with disallowEncode |
Own lifetimes and fibers
| You want to… | Reach for |
|---|---|
| Fork work with the right owner | Choosing a fork by its owner |
| Make sure a forked listener is registered before you publish | { startImmediately: true } |
| Coordinate fibers | Deferred, Latch, Fiber, FiberHandle/Map/Set |
| List every long-lived thing with its owner, bound, and release | the ownership ledger |
| Start up all-or-nothing; separate liveness, readiness, and draining | Owning Lifetimes — Startup, Readiness, and Shutdown |
| Run a heartbeat only while the main task runs | Effect.raceFirst |
| Run a worker with bounded admission and a drain | the bounded-worker recipe and deep dive |
Coordinate, share state, and stream
| You want to… | Reach for |
|---|---|
| Cap concurrency | Semaphore, PartitionedSemaphore, or the { concurrency } option |
| Hand work to workers with backpressure | Queue, with roles in signatures and an explicit lifecycle |
| Fan events out to every subscriber | PubSub and its delivery semantics |
| Shed load deliberately and count it | Make loss observable |
| Share expensive connections | Pool |
| Hold shared state | Ref / SynchronizedRef; reactive → SubscriptionRef, always as one transition per call |
| Mutate several pieces of state atomically | STM: TxRef and friends, run with Effect.tx |
| Process a sequence or stream over time | Stream + Sink + Channel |
| Merge, zip, partition, or broadcast streams | Combining and splitting streams |
| Recover, retry, or time out a stream | Handling stream failures |
| Keep a file or cursor open exactly as long as a stream is consumed | Stream.unwrap over a scoped acquisition |
| Find every place a pipeline buffers | Where buffering hides |
| Batch by size or time | Stream.grouped / groupedWithin, Stream.transduce |
| Frame bytes on a socket or file | Ndjson, Sse, SchemaBinary |
| Import a large file without buffering it | Streaming Ingestion Without Accidental Buffering |
Time and scheduling
| You want to… | Reach for |
|---|---|
| Retry, repeat, or poll | Schedule + Duration + Cron, the retry policy checklist, and the { schedule, while, until, times } options |
| See the delays a composed schedule will produce | Schedule.toStep |
| Prove a retry policy's shape | Testing a policy and the TestClock recipe |
| Work with time correctly | DateTime + Clock (never Date.now) |
| Parse a duration from config or a payload | Config.Duration, Schema.DurationFromString |
| Build a zoned time from wall-clock input; format for people | Constructing zoned values, Formatting |
| Build a cron expression from fields | Cron.make |
Data and boundaries
| You want to… | Reach for |
|---|---|
| Validate / parse / encode data | Schema + JsonSchema and the Schema deep dive |
| Pick the decode runner | by who consumes the failure |
| Reject or strip unknown keys, collect all issues | Parse options are boundary policy |
Model an optional, nullable, or Option field | Optional fields, null, and Option |
Put Option, Result, Exit, Duration, maps, sets, or Redacted on the wire | Effect data types at the boundary |
| Write human-readable validation messages | Custom error messages |
| Validate against a service (uniqueness, lookup) | Effectful schemas and services |
| Hand a schema to a form library or router | Schema.toStandardSchemaV1 |
| Generate JSON Schema (open objects by default) | JsonSchema |
| Pattern-match exhaustively | Match and how to close a matcher |
| Compare or hash values structurally | Equal and its pitfalls |
| Deeply update immutable data | Optic |
| Branded / nominal types | Brand + Newtype |
| Exact decimal math (money) | BigDecimal |
| Exact byte counts and size limits | ByteSize (replaces FileSystem.MiB and friends) |
| Model and analyze a graph (org chart, approval chain) | Graph and its witnesses, reductions, and matchings |
Interfaces
| You want to… | Reach for |
|---|---|
| Call an HTTP API | HttpClient, with budgets and safe retries and three failure classes |
| Fetch a URL a user supplied | User-controlled destinations |
| Call an existing GraphQL API with typed operations and subscriptions | GraphQL and @effect/graphql-generator (experimental; not a server executor) |
| Build a contract-first HTTP API | HttpApi, its status mapping, and authentication vs authorization |
| Serve HTTP and set edge limits | HttpServer and the edge policy checklist |
| Work with status codes and media types | HttpStatus, Mime |
| Typed client⇄server calls | the RPC modules, contract evolution, and operational defaults |
| Talk to a database | the SQL modules (SqlClient, SqlModel) and where SQL belongs |
| Write state and an external effect atomically | the outbox and Recipe: A Transactional Write with an Outbox |
| Give a repository one stable error | Normalizing errors at a repository boundary |
| Run migrations and operate pools in production | Operating migrations, Operating SQL in production |
Upgrade @effect/sql-pg | Upgrading to the native client |
| Go end to end from Schema to HttpApi to SQL | the boundary recipe |
| Files, sockets, workers, child processes | Platform & Runtime Hosts; sockets are pull-based (reader / writer) |
| Parse and match IP addresses and networks | NetAddress, IpNetwork, IpInterface |
| Parse host names, query DNS, or resolve endpoints | Host, Dns, AddressResolver (experimental; DNS validation alone does not prevent SSRF) |
| Send or receive UDP datagrams | DatagramSocket (experimental; not a byte stream) |
| Test file code without a disk | FileSystem.layerNoop |
Operate
| You want to… | Reach for |
|---|---|
| Logs, traces, metrics (+ export) | Logger / Tracer / Metric + exporters and the production observability recipe |
| Decide which signal to add, and bound its cardinality | Designing signals |
| Swap the log format without losing log-to-span correlation | Installing and swapping loggers |
| Set the minimum log level from config, or for one operation | Scoping and configuring the minimum level |
| Count, time, and gauge an effect without touching its body | Effect.track*, lifetime gauges |
| Choose OTLP, the OpenTelemetry SDK, or Prometheus | Choosing and owning an export path |
| Memoize one expensive effect | Effect.cached / cachedWithTTL |
| Memoize expensive lookups by key | Cache / ScopedCache, with a failure TTL |
| Kill N+1 queries (batch) | Request + RequestResolver (or SqlResolver), honoring the resolver obligations |
Durable and distributed systems
| You want to… | Reach for |
|---|---|
| Persist across restarts | KeyValueStore, PersistedQueue, PersistedCache, after reading what each guarantees |
| Process durable jobs at least once | PersistedQueue (retry policy lives on make) and its failure windows |
| Run a durable, resumable process | Workflow, with replay and versioning rules |
| Distribute stateful entities | the cluster modules, their transport options and capacity limits |
| Event-source / local-first sync | the event-log modules |
| Decide how much durability the problem needs | The Durability and Distribution Ladder |
| Reactive UI state | Atom + framework bindings, or the deep dive |
| Call an LLM (provider-agnostic) | LanguageModel + an @effect/ai-* provider, under the production rules |
| Gate tool calls behind approval, or bound their concurrency | Tool-call resolution |
| Expose tools over MCP | McpServer |
| Host MCP on a serverless request lifetime | layerHttpRequestScoped (stateless adapters only) |
| Ship an AI feature with budgets, gates, and tests | Building a Production AI Capability |
Test and tool
| You want to… | Reach for |
|---|---|
| Test effects deterministically | @effect/vitest + TestClock and Testing an Effect Application |
| Seed random bytes and IDs without faking digests | A seeded SecureRandom layer beside the host digest layer |
| Property-test from a Schema | 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 |
Test laziness and the exact E and R | Prove laziness and the static contract |
Capture Effect.log* records or spans in a test | a test Logger, structural span tests |
| Audit a green suite for false greens | When green means nothing |
| Catch floating Effects and removed APIs in the editor and CI | @effect/tsgo and diagnostics setup |
| Build a command-line app | the CLI modules (PascalCase constructors; boolean flags need Flag.withDefault(false)), and testing a command |
Recipes and deep dives by task
Tip: Most of what you import from
"effect"is@stability stableand covered by semver. Exceptions such asArbitrary,FileSystem,Path,ExecutionPlan,LayerMap,Graph, andByteSize, plus advancedSchemaAPIs, carry explicit stability labels. Most subsystem APIs under"effect/<area>"are unstable and may change in minor releases; GraphQL, host/DNS resolution, and UDP APIs are experimental and may change in patches. See Stability and support for the distinctions. Pin exact versions, read the changelog, and keep each unstable or experimental import behind one app-owned capability.