Effect v4
Effect 4.0.0 is the stable release. Write v4.
Model memory and effect.website default to v3. Do not trust either.
Every example that starts with import compiles against effect@4.0.0. Blocks under Fail review on are wrong on purpose.
The model
Effect.Effect<A, E, R> describes work. Building it runs nothing.
Ais the success value.Eis the expected failures, as tagged errors.Ris the services still required. ALayerprovides them.
Run an Effect once, at the program edge. Everything below the edge returns an Effect.
Hover A, E, and R. Inference is the documentation.
Imports
| Need | Import |
|---|---|
| Core | import { Effect, Layer, Schema, Context } from "effect" |
| HTTP client and server | effect/http |
| HttpApi | effect/http-api |
| SQL | effect/sql |
| LLMs | effect/ai |
| Test services | effect/testing |
| Everything else | effect/<area>: cli, rpc, workflow, cluster, persistence, reactivity, observability, encoding, process, socket, workers, eventlog, schema |
| Runtimes, drivers, providers | @effect/platform-node, @effect/sql-sqlite-node, @effect/sql-d1, @effect/ai-openai, @effect/ai-anthropic, @effect/vitest |
effect/unstable/*, @effect/platform, @effect/sql, and @effect/ai are prerelease paths. They do not exist in 4.0.0.
Most of effect/<area> is tagged @stability unstable. It is production code, but a 4.x minor can break it.
Pin effect and every @effect/* to one exact version. Upgrade them together.
House rules
Write
- A reusable effectful function is
Effect.fn("Owner.method"). One-off sequencing is inlineEffect.gen. The name is the span. - Pure work stays plain TypeScript.
xs.map(f), neverEffect.forEach(xs, (x) => Effect.succeed(f(x))). - No ambient globals in Effect code.
fetch→HttpClient.Date.now()→ClockorDateTime.console→Effect.log*.setTimeout→Effect.sleep.Math.random()→Random. - Run effects only at the entry point. Never
Effect.runPromiseinside a helper.
Errors
- An expected failure is a
Schema.TaggedErrorclass. Fail withreturn yield* new ItemMissing({ id }). Returning{ _tag: "ItemMissing" }is a success. _tagis the only discriminant. Success unions useData.taggedEnum. Never write{ _tag: "X" as const }.- Handle an error only where you have a real answer: a fallback, a retry, a response, a settlement. Otherwise leave it in
E. - Never swallow. No
Effect.ignore, no catch-to-void. Best-effort work returns a tagged outcome and logs it. - Bugs and impossible states die. Only the entry point inspects
Cause.
Data
- Decode unknown input once, at the boundary, with Schema. Do not decode values you just built.
Services
- A service owns I/O, state, credentials, or policy. Everything else is a function.
- Yield dependencies once in
Layer.effectand close over them. Public methods haveR = never. - Service keys are path-shaped and unique:
"@app/store/ItemStore". - Provide shared infrastructure once, at the composition root: HTTP transport, SQL driver, logger.
Config
- Read env and host bindings only at the entry point. Pass plain typed values into layer constructors:
catalogLayer({ baseUrl, apiKey }). - Every setting is required. No
??fallbacks. NoConfig.withDefaultfor business constants. Keep constants in one config module.
Retry
- One retry owner per failure. Bound every retry with
timesand a schedule. Set SDK retries to zero when Effect retries.
Testing
- No module mocks. No fake services. No stubbed
HttpClient. Test pure functions, recorded fixtures through the production schema, and real local engines (SQLite:memory:, temp directories) withTestClock. - Prove a workflow change with the project's real end-to-end run. Show the output.
Style
- No comments on functions. Names and types are the docs.
Choose
| I need | Use | Read |
|---|---|---|
| Sequence effects | Effect.gen + yield* | core |
| A named, traced operation | Effect.fn("X.y") | core |
| A value that may be absent | Option | core |
| A success-or-failure value, not an effect | Result | core |
| Exhaustive branching on a union | Match, $match | core |
| Durations and dates | Duration, DateTime | core |
| A typed expected failure | Schema.TaggedError | errors |
| Recover from one failure | catchTag, catchTags, catchReason | errors |
| Wrap a Promise or SDK call | Effect.tryPromise | errors |
| Validate unknown input | Schema.decodeUnknownEffect | schema |
| Parse JSON text | Schema.fromJsonString | schema |
| A dependency or capability | Context.Service + Layer | services |
| Settings and secrets | Config, Redacted at the entry | services |
| Start the program | NodeRuntime.runMain, ManagedRuntime | services |
| Do work in parallel | Effect.forEach(xs, f, { concurrency }), Effect.all | concurrency |
| Open and close a resource | Effect.acquireRelease, Scope | concurrency |
| A background loop | Effect.forkScoped in a layer | concurrency |
| Shared mutable state | Ref, SynchronizedRef, SubscriptionRef | concurrency |
| Wait for a signal, limit access | Deferred, Latch, Semaphore | concurrency |
| A work queue or fan-out | Queue, PubSub | concurrency |
| Retry, repeat, poll | Effect.retry, Effect.repeat, Schedule | time |
| A deadline | Effect.timeoutOrElse | time |
| Values over time, pagination, SSE | Stream | streams |
| Memoize a lookup | Cache, Effect.cachedWithTTL | caching |
| Batch many lookups into one call | Request, RequestResolver | caching |
| Logs, spans, metrics | Effect.log*, Effect.fn, Metric | observability |
| Call an HTTP API | HttpClient | http |
| Serve HTTP | HttpRouter, HttpApi | http |
| Query SQL | SqlClient, SqlSchema | sql |
| Call an LLM | Vercel AI SDK or effect/ai | llm |
| Files, paths, child processes, CLIs | FileSystem, Path, ChildProcess, effect/cli | platform |
| Write a test | @effect/vitest, TestClock | testing |
| RPC, durable workflows, cluster, persistence, atoms, event logs | — | modules |
| You wrote a v3 or prerelease name | — | v3 traps |
| Cloudflare Workers | — | cloudflare |
Verify an API
Do not guess a signature. The installed package ships its source and docs:
node_modules/effect/src/<Module>.ts, orsrc/<area>/for subpaths. Exports carry When to use and Gotchas JSDoc.node_modules/effect/ai-docs/src/holds the official examples by topic.node_modules/effect/AGENTS.mdis the upstream agent guide.
With pnpm, look under the package that depends on effect: <package>/node_modules/effect.
rg smart case makes lowercase patterns case-insensitive. Search with rg -s.
The Effect language service (@effect/tsgo) reports v3 names as outdatedApi. Run the typecheck.
Cloudflare Workers
Effect runs on Workers with no platform package.
Build the layer graph per invocation from env. Use FetchHttpClient.layer and @effect/sql-d1.
D1 has no transactions. Use batch([...]) on the D1Client service.
Read cloudflare only for Workers work. Nothing else in this skill depends on it.
Review
- Hover
R. A service inRthat no layer provides defects at run time → reject. - Hover
E. A new error class with nocatchTagupdate means an exhaustive edge is lying. Effect.forEachwhose callback only wraps a pure value → reject. That isxs.map.{ _tag: "X" as const }→ reject. Use a constructor.yield*of a service inside a public method → reject. Capture it in the layer.- Global
fetchinsidetryPromisefor an HTTP API → reject. UseHttpClient. Effect.ignore,catchCause, or a handler returningEffect.voidbelow the entry → reject.- A retry without
times→ reject. It retries forever. Cache.makewithouttimeToLive→ reject. It caches failures forever.vi.mock,Layer.mock,Layer.succeedof an app service, orHttpClient.makein a test → reject.
Provenance
A copy of this skill also lives in a work repository. Update both copies when either changes.


