Skip to content
Agents: this page is Markdown at /effect-handbook/reference/cheat-sheet-index.md · llms.txt · reading guide View raw

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

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 programGetting Started
Choosing between primitives that all look plausibleChoosing Effect Primitives
Looking at a symptom, or checking generated code against known mistakesTroubleshooting & Anti-Patterns
Reviewing a design or a diffReview Checklists
Coming from Effect 3Migration guide
Moving an existing Promise codebase over, one leaf at a timeAdopting Effect in an Existing TypeScript Codebase
Wanting a connected walkthrough rather than a lookupDeep 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.

DecisionDetailed comparison
Where a fact may be collapsed: absence, failure, unknown, requirements, execution, lifetimeBoundary rules before primitives
Which constructor wraps this JavaScriptConstructor by source convention
Which runner the host needsRunner by host contract
Absence, pure failure, a recorded outcome, or effectful workOption vs Result vs Effect
Which recovery operator expresses the intentRecovery operator by intent
Stop at the first failure or collect them allFail fast or accumulate
provideService, a Layer, { local: true }, or Layer.freshProviding dependencies by seam
Which fork, by who owns the fiberFork by owner
Which bracket, by how long the resource livesResource lifetime and bracket
One cell, effectful update, live changes, or atomic multi-value stateRef vs SynchronizedRef vs SubscriptionRef vs transactions
One result, a gate, worker handoff, or broadcastDeferred vs Latch vs Queue vs PubSub
Wait, shed, keep the latest, or grow without boundOverload semantics at a glance
Local parallelism, a shared permit budget, or reusable objectsPer-call concurrency vs Semaphore vs Pool
One effect repeated, one key repeated, or many keys at onceSingle-flight, cache, or batching
Cached values, cached resources, refresh, or batchingCache vs ScopedCache vs Resource vs RequestResolver
Finite collections or incremental protocolsArray/Chunk/Iterable vs Stream/Sink/Channel
Buffer depth, batch size, or rateStream buffering and batching operators
JSON, NDJSON, SSE, or schema-derived binary framesWire codec: JSON, NDJSON, or SchemaBinary
Outbound HTTP, low-level routing, contract HTTP, or proceduresHttpClient vs HttpRouter vs HttpApi vs RPC
Failed attempts, successful repetition, polling, or restart survivalRetry vs repeat vs polling vs Workflow
Durable state, history, orchestration, or distributed identityPersistence vs EventLog vs Workflow vs Cluster
Which test tool proves which claimTest tool by claim
Who owns the runtime and what cancels workHost and runtime ownership

What to reach for when… ​

Build and run ​

You want to…Reach for
Run async/fallible code with typed errorsEffect (tryPromise, callback, gen, fn)
Wrap a Promise or callback API so that a timeout really cancels itCancellable 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 distinctrunPromiseExit with { signal }
Call Effect from Express, Hono, a UI, or a plugin APIManagedRuntime, the ManagedRuntime recipe, and its production-shaped bridge
Carry a host request's abort through to the SDK callRecipe: Request Cancellation Through a Host
Start a process and shut it down gracefullyplatform runMain, the graceful entrypoint recipe, and readiness plus a bounded drain
Choose the host: process, Web handler, framework callback, browser, worker, testChoosing a host
Fall back across providers or modelsExecutionPlan

Fail and recover ​

You want to…Reach for
Decide whether an outcome is a result, a typed failure, or a defectDesigning the error model
Recover from some failures and leave the rest typedcatchTag, catchIf, catchFilter, catchReason
Translate an error, or fail an unacceptable successmapError, filterOrFail
Turn every outcome into one responseEffect.match / matchEffect
Collect every validation problemEffect.validate, Effect.partition, mode: "result"
Map an error union to statuses or policies exhaustivelyMatch.exhaustive / tagsExhaustive
Keep a defect that sits beside a typed failurea guarded catchCause
Move between Option, Result, and Effect (they are not yieldable)Effect.fromOption, Effect.fromResult
Decide what a failed cleanup meansWhen cleanup can fail
Undo partial in-process workexit-aware finalizers
Combine retry with a timeoutWhere the timeout sits relative to retry
Report defects at the process edgeErrorReporter

Depend and configure ​

You want to…Reach for
Inject a dependencyContext.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 LayerEffect.provideService
Know whether a pool is shared or rebuiltWhat is shared, and what is rebuilt
Own a connection or client for the application's lifetimeResourceful services
Use a capability only if the host installed itEffect.serviceOption
Ambient, override-able settingsContext.Reference / References and the default services
Keep a value fresh in the backgroundResource
One Layer per tenant or keyLayerMap
Read config / hide secretsConfig + ConfigProvider / Redacted (PascalCase constructors: Config.String, Config.Int, Config.Redacted, Config.Duration, Config.URL)
Define what a valid deployment looks like, onceDesigning the startup contract
Default a setting without hiding a typoConfig.withDefault, not Config.orElse
Layer CLI overrides over environment over defaultsPrecedence and composition
Decode a secret from a payload without ever encoding it backSchema.RedactedFromValue with disallowEncode

Own lifetimes and fibers ​

You want to…Reach for
Fork work with the right ownerChoosing a fork by its owner
Make sure a forked listener is registered before you publish{ startImmediately: true }
Coordinate fibersDeferred, Latch, Fiber, FiberHandle/Map/Set
List every long-lived thing with its owner, bound, and releasethe ownership ledger
Start up all-or-nothing; separate liveness, readiness, and drainingOwning Lifetimes — Startup, Readiness, and Shutdown
Run a heartbeat only while the main task runsEffect.raceFirst
Run a worker with bounded admission and a drainthe bounded-worker recipe and deep dive

Coordinate, share state, and stream ​

You want to…Reach for
Cap concurrencySemaphore, PartitionedSemaphore, or the { concurrency } option
Hand work to workers with backpressureQueue, with roles in signatures and an explicit lifecycle
Fan events out to every subscriberPubSub and its delivery semantics
Shed load deliberately and count itMake loss observable
Share expensive connectionsPool
Hold shared stateRef / SynchronizedRef; reactive → SubscriptionRef, always as one transition per call
Mutate several pieces of state atomicallySTM: TxRef and friends, run with Effect.tx
Process a sequence or stream over timeStream + Sink + Channel
Merge, zip, partition, or broadcast streamsCombining and splitting streams
Recover, retry, or time out a streamHandling stream failures
Keep a file or cursor open exactly as long as a stream is consumedStream.unwrap over a scoped acquisition
Find every place a pipeline buffersWhere buffering hides
Batch by size or timeStream.grouped / groupedWithin, Stream.transduce
Frame bytes on a socket or fileNdjson, Sse, SchemaBinary
Import a large file without buffering itStreaming Ingestion Without Accidental Buffering

Time and scheduling ​

You want to…Reach for
Retry, repeat, or pollSchedule + Duration + Cron, the retry policy checklist, and the { schedule, while, until, times } options
See the delays a composed schedule will produceSchedule.toStep
Prove a retry policy's shapeTesting a policy and the TestClock recipe
Work with time correctlyDateTime + Clock (never Date.now)
Parse a duration from config or a payloadConfig.Duration, Schema.DurationFromString
Build a zoned time from wall-clock input; format for peopleConstructing zoned values, Formatting
Build a cron expression from fieldsCron.make

Data and boundaries ​

You want to…Reach for
Validate / parse / encode dataSchema + JsonSchema and the Schema deep dive
Pick the decode runnerby who consumes the failure
Reject or strip unknown keys, collect all issuesParse options are boundary policy
Model an optional, nullable, or Option fieldOptional fields, null, and Option
Put Option, Result, Exit, Duration, maps, sets, or Redacted on the wireEffect data types at the boundary
Write human-readable validation messagesCustom error messages
Validate against a service (uniqueness, lookup)Effectful schemas and services
Hand a schema to a form library or routerSchema.toStandardSchemaV1
Generate JSON Schema (open objects by default)JsonSchema
Pattern-match exhaustivelyMatch and how to close a matcher
Compare or hash values structurallyEqual and its pitfalls
Deeply update immutable dataOptic
Branded / nominal typesBrand + Newtype
Exact decimal math (money)BigDecimal
Exact byte counts and size limitsByteSize (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 APIHttpClient, with budgets and safe retries and three failure classes
Fetch a URL a user suppliedUser-controlled destinations
Call an existing GraphQL API with typed operations and subscriptionsGraphQL and @effect/graphql-generator (experimental; not a server executor)
Build a contract-first HTTP APIHttpApi, its status mapping, and authentication vs authorization
Serve HTTP and set edge limitsHttpServer and the edge policy checklist
Work with status codes and media typesHttpStatus, Mime
Typed client⇄server callsthe RPC modules, contract evolution, and operational defaults
Talk to a databasethe SQL modules (SqlClient, SqlModel) and where SQL belongs
Write state and an external effect atomicallythe outbox and Recipe: A Transactional Write with an Outbox
Give a repository one stable errorNormalizing errors at a repository boundary
Run migrations and operate pools in productionOperating migrations, Operating SQL in production
Upgrade @effect/sql-pgUpgrading to the native client
Go end to end from Schema to HttpApi to SQLthe boundary recipe
Files, sockets, workers, child processesPlatform & Runtime Hosts; sockets are pull-based (reader / writer)
Parse and match IP addresses and networksNetAddress, IpNetwork, IpInterface
Parse host names, query DNS, or resolve endpointsHost, Dns, AddressResolver (experimental; DNS validation alone does not prevent SSRF)
Send or receive UDP datagramsDatagramSocket (experimental; not a byte stream)
Test file code without a diskFileSystem.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 cardinalityDesigning signals
Swap the log format without losing log-to-span correlationInstalling and swapping loggers
Set the minimum log level from config, or for one operationScoping and configuring the minimum level
Count, time, and gauge an effect without touching its bodyEffect.track*, lifetime gauges
Choose OTLP, the OpenTelemetry SDK, or PrometheusChoosing and owning an export path
Memoize one expensive effectEffect.cached / cachedWithTTL
Memoize expensive lookups by keyCache / 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 restartsKeyValueStore, PersistedQueue, PersistedCache, after reading what each guarantees
Process durable jobs at least oncePersistedQueue (retry policy lives on make) and its failure windows
Run a durable, resumable processWorkflow, with replay and versioning rules
Distribute stateful entitiesthe cluster modules, their transport options and capacity limits
Event-source / local-first syncthe event-log modules
Decide how much durability the problem needsThe Durability and Distribution Ladder
Reactive UI stateAtom + 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 concurrencyTool-call resolution
Expose tools over MCPMcpServer
Host MCP on a serverless request lifetimelayerHttpRequestScoped (stateless adapters only)
Ship an AI feature with budgets, gates, and testsBuilding 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 digestsA seeded SecureRandom layer beside the host digest layer
Property-test from a SchemaArbitrary (effect/Arbitrary; the fast-check bridge was removed)
Know what an in-memory harness does not proveIn-memory test runtimes shipped with Effect
Test laziness and the exact E and RProve laziness and the static contract
Capture Effect.log* records or spans in a testa test Logger, structural span tests
Audit a green suite for false greensWhen green means nothing
Catch floating Effects and removed APIs in the editor and CI@effect/tsgo and diagnostics setup
Build a command-line appthe CLI modules (PascalCase constructors; boolean flags need Flag.withDefault(false)), and testing a command

Recipes and deep dives by task ​

TaskRecipe (one complete file)Deep dive (connected walkthrough)
Define a service with live and test LayersService and LayersAnatomy of a Real Effect Application
Decode a request, serve it, store itSchema to HttpApi to SQLSchema — From External Input to Domain and Back
Bounded, resource-safe background workResource-Safe Bounded WorkerStructured Concurrency Through a Bounded Worker
Classified retry, proven with virtual timeTyped Retry with TestClockFailure, Retry, Fallback, and Interruption
Logs, traces, and metrics wired for productionProduction Observability—
A process that starts, serves, and stops cleanlyGraceful Node EntrypointOwning Lifetimes — Startup, Readiness, and Shutdown
Effect inside a framework you do not controlManagedRuntime at an Imperative Boundary, Request Cancellation Through a HostAdopting Effect in an Existing TypeScript Codebase
A database write plus an external effectTransactional Write with an OutboxThe Durability and Distribution Ladder
Large imports and live feeds—Streaming Ingestion Without Accidental Buffering
A test strategy for a whole service—Testing an Effect Application
Reactive UI state—Reactivity — From Atoms to Mastery
An LLM feature with tools and budgets—Building a Production AI Capability
An MCP server other agents can call, with auth and approvalsMcpServerExposing an Effect Application over MCP

Tip: Most of what you import from "effect" is @stability stable and covered by semver. Exceptions such as Arbitrary, FileSystem, Path, ExecutionPlan, LayerMap, Graph, and ByteSize, plus advanced Schema APIs, carry explicit stability labels. Most subsystem APIs under "effect/<area>" are unstable and may change in minor releases; GraphQL, host/DNS resolution, and UDP APIs are experimental and may change in patches. See Stability and support for the distinctions. Pin exact versions, read the changelog, and keep each unstable or experimental import behind one app-owned capability.

Edition 4.1 · audited 2026-11-19 against Effect 4.1.4.