Skip to content

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 insideCollapse it only atOwning section
Absence (Option)a display or protocol edge that owns the fallbackFallbacks and boundary exits
Expected failure (E)the terminal boundary that owns the response, with one foldFolding both channels at a boundary
Untrusted representation (unknown)ingress: decode once, with that boundary's parse optionsParse options are boundary policy
Requirements (R)the application, module, or test edge that provides themProviding one value or building a graph
Execution (laziness)a runner at an edge that owns the fiberRunning effects at an owned edge
Lifetime (Scope in R)the narrowest owner that is still validWrite the ownership ledger first
Secrets (Redacted)the single call that needs the bytesRedacted
Units of time (Duration)an interop edge that requires a numberParsing 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.

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 wrappingConstructorA throw or rejection becomesAvoid it when
A value you already holdEffect.succeed(value)not applicable: the argument is evaluated eagerly, while the program is builtthe expression does work (Date.now(), counter.next(), a side effect); use Effect.sync
Synchronous code that cannot throwEffect.sync(() => ...)a defectthe code can throw: JSON.parse, new URL, a synchronous Schema decoder
Synchronous code that can throwEffect.try({ try, catch })the typed error catch returnsyou would use the bare-thunk form and accept Cause.UnknownError without meaning to
A Promise that can rejectEffect.tryPromise({ try: (signal) => ..., catch })the typed error catch returnsthe thunk ignores signal: interruption then stops the fiber but not the I/O
A Promise that is not expected to rejectEffect.promise((signal) => ...)a defectthe call touches a network, disk, or SDK; Effect.promise(() => fetch(url)) moves every outage out of E
A one-shot callback APIEffect.callback<A, E>((resume, signal) => ...)whatever is passed to resume; only the first call countsthe source emits many values; use a Queue or Stream.callback
Building the next effect is itself workEffect.suspend(() => effect)a defect if the thunk throwsa plain conditional inside Effect.gen already defers it
An Option, Result, or nullable valueEffect.fromOption, Effect.fromResult, Effect.fromNullishOrnot applicableyou expected yield* to accept the Option or Result directly; it does not

Details: Creating effects, 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.

RunnerReturnsFailure surfaces asChoose it whenAvoid it when
Effect.runSync / runSyncExitA / Exit<A, E>a throw / a defect holding AsyncFiberError at the first asynchronous boundarythe effect is known to finish synchronouslyanything may suspend; the types cannot tell you
Effect.runPromisePromise<A>a rejection with the squashed cause; failure, defect, and interruption are no longer distincta JavaScript edge wants value-or-rejectionthe host must tell cancellation from failure
Effect.runPromiseExitPromise<Exit<A, E>>always resolvesan adapter, reporter, or test must keep the three outcomes apart—
Effect.runForkFiber<A, E>, immediatelyFiber.await or an observerthe caller keeps the handle and owns its lifetimenobody will join, observe, or interrupt the fiber
Effect.runCallbackan interruptor functionthe onExit callbackcallback-style hostsa Promise or fiber handle fits
Platform runMainvoida logged error and a process exit codethe process entry point, onceinside application code
ManagedRuntimethe same family as methodsas abovea non-Effect host calls in repeatedly against one Layer graphone 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, ManagedRuntime, Bridge into a host that is not Effect.

Option vs Result vs Effect ​

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid 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, Moving between Option, Result, and Effect, Exit.

Official guides: Expected Errors, Exit.

Recovery operator by intent ​

IntentOperatorWhat remains in EAvoid it when
Handle one or several tagged variantsEffect.catchTag("A"), catchTag(["A", "B"]), catchTags({ ... })every other variantthe policy depends on a field rather than the tag
Handle by predicate, refinement, or FilterEffect.catchIf, Effect.catchFilterwhat the selector rejectsa tag already says it; the narrowest selector documents the policy best
Handle one nested reason of a wrapper errorEffect.catchReason, catchReasonsthe other reasonsthe error has no reason union
Translate without recoveringEffect.mapErrorthe new errornothing was learned at this layer; pass the error through unrenamed
Turn an unacceptable success into a failureEffect.filterOrFailthe added errorthe check belongs in a Schema at the boundary
Produce exactly one ordinary shape at a terminal edgeEffect.match, Effect.matchEffectneverthe code is not a terminal boundary; folding in a lower layer steals policy from callers
Default a valueEffect.orElseSucceed after narrowing with catchTagneveronly one variant should default; un-narrowed, it replaces every typed failure
Try different effects in orderEffect.firstSuccessOf([...])the last errorthe same effect should run under different services; that is ExecutionPlan
Observe onlyEffect.tapError, tapErrorTag, tapCause, tapDefectunchangedyou intended to recover
Treat the outcome as dataEffect.result, Effect.option, Effect.exitneveroption would discard an error value somebody needs
Inspect defects or interruption deliberatelyEffect.catchCause with a guard, Effect.catchDefect that re-dies what it does not recognizeunchanged unless handledinside domain logic; these belong to a request, job, or process boundary
Discard a best-effort failureEffect.ignore (typed failures only), Effect.ignoreCause (defects and interruption too)neveranything but best-effort cleanup or telemetry
Promote to a defectEffect.mapError then Effect.orDieneverthe goal is only a tidier error union

Typed recovery operators look at the first Fail reason. A defect beside it takes precedence — the operator does not recover and propagates the error as a defect — while an interruption beside it is dropped when the handler's result replaces the Cause. Where an interruption or a second failure matters, use a guarded catchCause. Details: Effect error handling, Recovery and mixed causes, Classifying an error union.

Fail fast or accumulate ​

NeedUseOutcomeAvoid it when
Stop the batch at the first problemEffect.all / Effect.forEach (the default mode; sequential unless concurrency is set)fails with the first E; no partial successes are returnedthe caller needs every problem at once
Every problem at once, or else every valueEffect.validate(items, f, { concurrency? })Array<B>, or fails with NonEmptyArray<E>successes matter even when some items fail
Act on both sidesEffect.partition(items, f, { concurrency? })never fails: [failures, successes]a failure should stop the caller
One outcome per member, in the input's shapeEffect.all(effects, { mode: "result" })a Result per membera flat list of failures is enough
Every Schema issue of one decodethe parse option errors: "all"one SchemaError holding every reachable issueyou 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, Parse options are boundary policy.

Providing dependencies by seam ​

SeamEffect on RWhat is built, and how oftenChoose it whenAvoid it when
Effect.provideService(Service, value)removes exactly one identifiernothing is built; the value already existsa focused test fake, a script, a per-request value set by middlewarethe implementation needs state, configuration, other services, or teardown
Effect.provide(context)removes every key in the Contextnothing is builtseveral ready values travel togetherthe values need construction
Layer.succeed(Service, value)removes the outputa finished value, no finalizera constant implementation inside a Layer graphanything 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 acquireReleasestate, configuration, other services, or a lifetime—
One Effect.provide(AppLive) at the edge, or one ManagedRuntimecloses R to neverevery Layer value once, released at shutdownthe application rootrepeated next to each use: sibling Effect.provide(PoolLive) calls build two pools
Effect.provide(layer, { local: true })samea brand-new memo map: the whole provided graph is rebuilt, then released when that effect endsdeliberate isolation per tenant, test, or transactionsilencing a type error; it duplicates pools, caches, and subscriptions
Layer.fresh(layer)samethat Layer and its dependencies are private to one branch of a buildone branch needs its own instanceas a default; sharing is the resource-safety default
Effect.serviceOption(Service)does not add the service—a capability the host may or may not installthe 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, What is shared, and what is rebuilt, Resourceful services, Optional services.

Fork by owner ​

Name the owner first; the fork function follows.

FunctionOwnerInterrupted whenChoose it whenAvoid it when
Effect.forkChildthe current fiberthe parent ends, for any reasonthe work must not outlive the code that started itthe work has to survive the function that forked it
Effect.forkScoped (adds Scope to R)the surrounding Scopethat scope closesbackground work owned by a Layer, a request scope, or a testthe nearest scope closes too early, such as an Effect.scoped around the fork itself
Effect.forkIn(effect, scope)a Scope you were handedthat scope closes"start it here, own it there"the current scope is already the right owner
Effect.forkDetachnobodynever, unless someone keeps the handleprocess-lifetime work with a documented stop pathlibrary and domain code; an unowned detached fiber is a leak
FiberSet / FiberMap / FiberHandlea scoped supervisorthe supervisor's scope closes; FiberMap and FiberHandle also replace by key or slota 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 / racethe combinatorthe combinator endsa 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, When a forked fiber starts, Structured concurrency is ownership.

Resource lifetime and bracket ​

ShapeLifetime unitWho closes itMay cleanup fail in E?Choose it whenAvoid it when
Effect.acquireUseRelease(acquire, use, release)one use callthe combinatoryesthe resource lives for exactly one operation and the caller must see a failed release, such as a commit or flushthe handle must outlive use
Effect.acquireRelease + Effect.scopedthe scoped regionEffect.scopedno; the finalizer's error type is neverseveral resources share one region and release in reverse orderthe value escapes the region; returning it is a use-after-release bug
Effect.acquireRelease inside Layer.effectthe Layer's owner: application, ManagedRuntime, or testthe Layer build's scopenopools, clients, exporters, listenersthe resource is per request; providing the Layer in a handler acquires it per request
Effect.ensuring / Effect.onExit / Effect.onErrorone effectthe combinatoronly onExitcleanup with no handle to pass: a gauge decrement, a Deferred completion, a flagthere is a resource; pair it with its acquisition instead
Effect.addFinalizerthe current Scopewhoever owns that scopenoregistering cleanup from inside a scoped constructornothing will discharge the Scope it adds to R
Stream.unwrap over a scoped effect, Stream.scopedthe stream's consumptionthe stream, on completion, failure, interruption, and early stopnoa cursor, file, or subscription read incrementallyacquiring before the stream and closing "when done"
Pool.get, ScopedCache, RcRef / RcMapa borrow or a cache entrythe pool, cache, or reference countnobounded sharing of expensive instancesone 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, When cleanup can fail, One bracket per resource, 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.

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid 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, Choosing the right state tool, 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.

QuestionAnswerPrimitive
Do readers want the current value or each event?current valueRef, or SubscriptionRef when they also want changes
Does it happen once or repeatedly?onceDeferred (a result) or Latch (a reopenable gate)
Should one consumer or every consumer see each value?one / everyQueue / PubSub
Under overload, should the producer wait, should data be shed visibly, or does only the latest value matter?wait / shed / latestthe bounded, dropping, or sliding constructor — see Overload semantics at a glance
PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid 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.
LatchNo 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, Queue lifecycle: who ends it, and what a failure does, Deferred, Latch.

Official guide: 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.

StrategyQueue.offerPubSub.publishStream.buffer / Stream.callbackWhat is lostChoose it when
Suspend (Queue.bounded, PubSub.bounded, strategy: "suspend")the producing fiber waits, then gets truewaits while any subscriber lags by a full bufferupstream is back-pressurednothingevery value must be processed and the producer is an Effect that can wait
Droppingreturns false; offerAll returns the rejected remainderreturns false; the message is dropped for every subscriberthe newest elements are discardedthe newest valuesshedding load is an accepted policy and the false results are counted
Slidingreturns true; the eviction is not reportedreturns true; only lagging subscribers miss the evicted messagethe oldest elements are evictedthe oldest valuesonly the latest state matters: progress, presence, prices
Unbounded (Queue.unbounded, PubSub.unbounded, capacity: "unbounded", and the default of Stream.callback)always truealways truenothing pushes backnothing, until memory runs outsomething 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, Make loss observable, Overflow strategies and the publish result, Where buffering hides, Durability and Distribution Ladder.

Per-call concurrency vs Semaphore vs Pool ​

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid it when
{ concurrency } on Effect.all, Effect.forEach, Stream operatorsCombines 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.
SemaphoreWrapped 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, TTL is not a health check, Operational defaults, 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 shapeWhat the measurement showsToolWhy the neighbors do not help
One expensive effect, no keythe same effect runs once per caller instead of once per freshness windowEffect.cached, Effect.cachedWithTTL, Effect.cachedInvalidateWithTTLa keyed cache is machinery you do not need
Repeat lookup of the same keylookup count ≈ request count; keys recurCache with a key, capacity, and TTLbatching shrinks one burst and remembers nothing afterwards
Cold stampede on one keya burst of identical lookups at startup or right after expiryalready solved by Cache.get: concurrent misses for one key share one lookupa hand-written promise map or lock duplicates it
N+1 over different keysbackend calls scale with rows, one id eachRequestResolver + Effect.request; SqlResolver for SQLa cache cannot help: remembering one key does nothing for the others

Single-flight is not batching: the first collapses concurrent gets of the same key, the second collapses requests for different keys into one backend call. They compose through RequestResolver.withCache and asCache. Base batching does not deduplicate equal requests; only those two combinators do. Details: Which problem do you have?, Caching a single Effect, Resolver obligations.

Cache vs ScopedCache vs Resource vs RequestResolver ​

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid 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.requestEach 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, Keys are logical values.

Array, Chunk, Iterable vs Stream, Sink, Channel ​

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid it when
Array / ReadonlyArrayPlain 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, Sink introduction.

Stream buffering and batching operators ​

Flow-control depth, batch size, and rate are three different knobs. Buffer capacity is not batch size.

NeedOperatorWhat it retainsAvoid it when
Decouple a fast producer from a slow consumerStream.buffer({ capacity, strategy? })up to capacity elements; "suspend" back-pressures, "dropping" / "sliding" lose datayou wanted batches, or a cheap prefix: buffer runs ahead of a downstream take
Fixed-size batches from a finite sourceStream.grouped(n)the batch under constructionthe source is live: a partial batch waits indefinitely
Batches by size or elapsed timeStream.groupedWithin(n, duration)the batch under constructionthe 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 accumulatessize or time already expresses it
Resize chunks for an array-consuming sinkStream.rechunk(n)one chunkthe consumer needs arrays as elements; that is grouped
Bound in-flight effectful workStream.mapEffect(f, { concurrency })up to concurrency inputs and results"unbounded" over an uncontrolled source
Limit rateStream.throttle, Stream.scheduleone chunk / one elementthe goal is load shedding by count; that is a dropping buffer
Keep only the latest after a quiet periodStream.debounce(duration)the latest valueevery value matters
Bound a push sourceStream.callback(register, { bufferSize, strategy })unbounded unless bufferSize is setthe 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, Where buffering hides, Adapting, leftovers, and repeatable batching, Batch by size or time when the source is live.

Wire codec: JSON, NDJSON, or SchemaBinary ​

CodecFramingFailure typeEvolutionChoose it whenAvoid it when
JSON through a Schema codec (Schema.toCodecJson, Schema.fromJsonString; RpcSerialization.layerJson)none: one document per messageSchema.SchemaErrorordinary Schema evolution: optional keys, decoding defaults, unions of versionsone request, one response; public HTTP; human-readable storagemany messages share one long-lived connection
Ndjson (RpcSerialization.layerNdjson) — unstableone JSON value per lineNdjsonError (kind: "Pack" or "Unpack") for the JSON step, Schema.SchemaError for validationas JSONstreaming, sockets, the peer is not an Effect program, frames must be inspectablepayload size dominates, or an unbounded line from an untrusted peer is not capped
SchemaBinary, default mode (RpcSerialization.layerSchemaBinary()) — unstablebinary frames whose layout is compiled once from the Schema's encoded sideSchema.SchemaErrortolerant: fields carry hashed ids, so peers may add optional fields independently; pin SchemaBinary.fieldId(n) before a renameworkers, TCP, cluster runners, high-throughput links between Effect programsthe peer cannot share the Schema, or frames must be read by humans
SchemaBinary with { fingerprint: true }positional layout plus a layout hashSchema.SchemaError; a mismatched layout is rejectednone: both peers must deploy the same schema togethersmallest frames under lock-step deploymentpeers are upgraded independently
Sse — unstableserver-sent events texta Retry failure carries the retry: directiveas JSON for the data payloadone-way server-to-browser pushbidirectional or binary traffic

SchemaBinary is the default binary format for cluster runner transports and EventLog journals and remote messages, so switching a link or a journal to or from it changes bytes on the wire and on disk. maxFrameSize is unset by default on the raw codec; set it for untrusted peers. Details: SchemaBinary, Ndjson, RpcSerialization, Serialization codecs.

HttpClient vs HttpRouter vs HttpApi vs RPC ​

These modules are @stability unstable; pin all Effect packages to exactly the same release. The adjacent GraphQL family is experimental, so it can change even in a patch release.

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid it when
HttpClientTyped 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.
HttpRouterHandlers 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.
HttpApiEndpoint 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.
RPCEach 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, Status mapping is part of the contract, Evolving a contract, 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.

Retry vs repeat vs polling vs Workflow ​

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid 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 StreamPoll 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 primitivesPayload, 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, Shorthand options for retry and repeat, Where the timeout sits relative to retry, Replay, versioning, and rollout.

Official guides: Retrying, Using schedules, Schedule cookbook.

Persistence vs EventLog vs Workflow vs Cluster ​

PrimitiveError and requirementsScope, lifetime, and backpressureDurability and distributionChoose it whenAvoid it when
Persistence / PersistedCacheSchema 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.
EventLogEvent 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.
WorkflowSchema-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 / ShardingEntity 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, Failure windows and honest guarantees, External effects after commit (outbox), 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 testToolIt does not prove
A delay, timeout, retry spacing, or TTL behaves as specifiedTestClock inside it.effect: fork, adjust, jointhat a real driver or OS timer honors the same timing
Orchestration, typed failures, interruption, cleanupit.effect plus replacement Layers; assert on Exitthe real adapter's behavior
Console.* output / Effect.log* recordsTestConsole / a capturing test Loggereach other
Reproducible crypto-service random bytes and UUIDsA seeded SecureRandom layer beside the host crypto layerscryptographic security of the seeded test generator; Random operations use a separate seed
A rule holds for every valid inputArbitrary.schema via it.effect.proprejection of malformed wire input; generated values are already valid
A codec decodes, encodes, and round-tripsTestSchemacross-field rules the schema does not state
HTTP or RPC contract, routing, middleware, status mappingHttpApiTest.groups, RpcTest.makeClientsockets, malformed wire input, and for RpcTest serialization
An adapter works against a real dependencylayer(L, { excludeTestServices: true }) or it.live, with a scoped real fixturethat the packaged entry point starts, serves, and shuts down
Durable orchestration and storage contractsWorkflowEngine.layerMemory, Persistence.layerMemory, KeyValueStore.layerMemorydurability across a restart
E and R are exactly what the contract saysexpectTypeOf under the type checkerany runtime behavior
The shipped artifact starts, serves, and stopslaunch the built bundle or container—

Details: Testing & Dev Tooling, In-memory test runtimes shipped with Effect, Model the proof before writing the test, 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.

HostRunner and ownerWhat cancels workWhat it cannot promiseAvoid
Node / Bun / Deno processone platform runMain at the root; the launched Layer's scope owns everythingSIGINT and SIGTERM interrupt the main fiber; finalizers run before exitsurviving SIGKILL or an expired grace periodprocess.exit() in application code
Web-standard handler (serverless, edge)HttpRouter.toWebHandler returns { handler, dispose }; module scope owns the Layer, each request its own scoperequest.signal interrupts the request fiberthat dispose is ever awaited, or that work continues after the responsenode:* assumptions; work scheduled past the response
Request-scoped MCP on a serverless hostMcpServer.layerHttpRequestScoped; each POST owns its serverthe request ending closes its server scopesessions, subscriptions, or background work past the requestusing 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 hooknothing, unless you forward the host's AbortSignal with { signal } and stop admission yourselfa drain: dispose() interrupts managed fibers and awaits cleanup before releasing the Layer, rather than letting requests finish normallya runtime per request
Browser pageBrowserRuntime.runMaina non-persisted pagehidecompletion of asynchronous finalizers or network flushesrelying on a final flush
Worker thread or child processthe parent's scope around the worker; the worker side runs a WorkerRunnerthe parent scope closingworker-side cleanup longer than the adapter's grace periodunscoped spawns
CLICommand.run handed to the platform runMainas a process—a second runner inside a command handler
Testthe scope of it.effect / it.layerthe end of the test; time is virtualanything about real signals, ports, files, or bundlingclaiming host behavior from fakes

Business code is identical in every row; only the outermost line and the platform Layer change. Details: Choosing a host, The host matrix, Choose the correct runtime edge.

More choosers on their owning pages ​

DecisionOwning section
Which Schema decode runner, by who consumes the failureDecoding and encoding — pick your result style
Optional key, undefined, null, or Option on the wireOptional fields, null, and Option
A setting is required, optional, or defaultedDeciding required, optional, and defaulted
Config.withDefault vs ConfigProvider.orElse vs Config.orElseAbsence is not malformed input
Log, span, or metricWhich signal answers which question
Direct OTLP, the OpenTelemetry SDK bridge, or PrometheusOne export path per signal
RPC transport: HTTP, WebSocket or socket, worker, stdioRpcServer
Cluster runner transport and serializationTransport options
Combining or splitting streams: merge, zip, partition, broadcastCombining and splitting streams
Stream recovery: catch*, retry, timeout, timeoutOrElseHandling stream failures
Workflow finalizer, compensation, or scope finalizerFinalizers, compensation, and cancellation
Which durability rungA compact selection guide
Five kinds of order under concurrencyFive kinds of order
Match.exhaustive vs Match.orElseClosing a matcher

A compact selection order ​

  1. 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.
  2. Is this just data? Start with Option, Result, Array, Chunk, or Iterable. Keep pure, synchronous, dependency-free transformations as plain functions.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. Is shared state involved? Choose Ref, SynchronizedRef, SubscriptionRef, or Effect.tx according to update and observation semantics.
  8. 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.
  9. Is work repeated? Measure the waste shape: one effect (Effect.cached), the same key (Cache), or many keys at once (RequestResolver).
  10. 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.
  11. 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.
  12. 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.
  13. How will you know? Pick the test tool by the claim, and finish with the Review Checklists.

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