# Layer composition makes dependencies explicit

> For agents: start with the [agent guide](https://ratstack.sh/llms.txt). Every page is Markdown by default; add `Accept: text/html` for HTML.

New on /news: [Foldkit joins Effect as its full-stack framework](/news).

A service is a named interface. A Layer describes how to build a service from other services.
Choose and supply the services and their dependencies before running the application. Keep dependencies private unless callers need them too.

## Supply dependencies without changing the domain

`FileInspector.layer` needs a filesystem implementation.
`NodeServices.layer` supplies platform services. The CLI combines them before execution.

apps/cli/src/cli.ts at b4d6b8f499e57bc76914ad70df3a0c99751ae28c; lines 22-35; highlighted none.

```typescript
  Effect.provide(
    Layer.mergeAll(
      Layer.provideMerge(FileInspector.layer, NodeServices.layer),
      remoteJoinInterestLayer,
      localPromptLibraryLayer.pipe(Layer.provide(NodeServices.layer)),
      localCafeDirectoryLayer.pipe(Layer.provide(NodeServices.layer)),
      localLearnLayer,
      Flags.defaults(eventFlags),
      Approval.denyAll
    )
  )
);

NodeRuntime.runMain(program);
```

Choose the combinator by the services the resulting Layer should expose:

- **`Layer.provide(dependency)`**: The consuming Layer's services
- **`Layer.provideMerge(dependency)`**: The consuming Layer's services and the dependency's services
- **`Layer.merge` or `mergeAll`**: The combined services; unrelated requirements remain unresolved

Merging services does not, by itself, feed one Layer into another Layer's requirements.

The test suite retains platform services with `provideMerge` because tests also create temporary files.
Production callers that need only the inspector can keep its implementation dependency private with `provide`.

## Reuse Layer identity when sharing construction

Sharing follows Layer identity within a build context that remembers which Layer values it has already constructed. Equivalent construction code does not make two Layer values identical.
Sharing is limited to that construction context.

The fixture gives two consumers a resource. One case shares a Layer value; the other calls the Layer factory again.

packages/core/test/layer-composition.test.ts at 72306d84e9b57f068f8e293c0d2f0c7b934338e1; lines 16-23; highlighted none.

```typescript
      const resource = Resource.layer();

      const graph = Layer.merge(
        ReadAccess.layer.pipe(Layer.provide(resource)),
        WriteAccess.layer.pipe(
          Layer.provide(shared ? resource : Resource.layer())
        )
      );
```

`Resource.layer()` creates a new Layer value. Reusing `resource` lets the two branches share construction.

The fixture counts constructions and compares service ids:

packages/core/test/layer-composition.test.ts at 72306d84e9b57f068f8e293c0d2f0c7b934338e1; lines 25-32; highlighted none.

```typescript
      const ids = yield* Effect.gen(function* readServiceIds() {
        return [yield* ReadAccess, yield* WriteAccess];
      }).pipe(Effect.provide(graph));

      const count = yield* ConstructionCount;

      expect(yield* Ref.get(count)).toBe(constructions);
      expect(ids[0] === ids[1]).toBe(shared);
```

Independent application runtimes do not share instances merely because they import the same Layer value.
Their construction context and memo-map lifetime matter too.

## Common wrong approach

Calling a Layer factory twice can create two pools, caches, or background workers when one shared instance was intended.
Keep the constructed Layer value and provide that same value to both consumers.

Do not use `provideMerge` everywhere to silence missing-service errors.
Read which services callers need. Retaining every dependency exposes implementation details and makes removal harder.

## Effect idiom and house rule

- Layers carry output services, construction failures, and input requirements. Composition resolves the requirements.
- In rat-stack, each entrypoint, where the application starts, chooses and supplies implementations in its composition root.
- A cartridge packages one job and its infrastructure. It must be removable without breaking unrelated packages.
- The application chooses its workspace layout and adapter package boundaries.

See also: [service construction](/lore/services-capture-dependencies), [domain structure](/lore/structure-effect-by-domain), [cartridges](/lore/cartridges), and [testing](/lore/tests-that-earn-their-place).

Read [why dependency injection matters](/lore/dependency-injection-is-the-reason-to-choose-effect).

## Sources

1. [Effect contributors. 2026. Layer. Effect 4.0.0.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/packages/effect/src/Layer.ts)
   Effect-TS. provide supplies dependencies; provideMerge retains their services; memoization uses Layer identity and a MemoMap. Accessed 2026-10-06.

2. [Effect contributors. 2026. Layer tests.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/packages/effect/test/Layer.test.ts)
   Effect-TS. Tests establish shared construction and resource lifetime within memoization contexts. Accessed 2026-10-06.

3. [rat-stack contributors. 2026. CLI composition root.](https://github.com/joelhooks/rat-stack/blob/65e9465f38092e24486392f22c08f45d61230c20/apps/cli/src/cli.ts)
   rat-stack. The CLI provides FileInspector and platform services before NodeRuntime.runMain. Accessed 2026-10-06.

4. [rat-stack contributors. 2026. Layer identity fixture.](https://github.com/joelhooks/rat-stack/blob/72306d84e9b57f068f8e293c0d2f0c7b934338e1/packages/core/test/layer-composition.test.ts)
   rat-stack. A checked seam fixture counts one construction for shared identity and two for separate Layer instances. Accessed 2026-10-06.

5. [Langton, Kit. 2026. Services & Layers. Effect Solutions.](https://github.com/kitlangton/effect-solutions/blob/09f82e6c5c928e7232cd32daf04d7c6a830b63f7/packages/website/docs/04-services-and-layers.md)
   Kit Langton. Topic framing for provision and identity-based Layer sharing; rewritten around rat-stack's code. Accessed 2026-10-06.

## Lore on this page

- [Structure an Effect codebase by domain](/lore/structure-effect-by-domain)
- [A cartridge owns one job and its resources](/lore/cartridges)

## Linked from

- A Layer as constructor → Sam Goodwin compares an Effect Layer that builds a service to a constructor. → [Read page](https://ratstack.sh/lore/layer-constructor-pattern)

- A service captures its construction dependencies → Build a service with its dependencies, then expose methods that callers can use without rebuilding the graph. → [Read page](https://ratstack.sh/lore/services-capture-dependencies)

- Agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms.txt)

- Bindings → Sam Goodwin describes bindings as the place where runtime permissions and configuration meet infrastructure. → [Read page](https://ratstack.sh/lore/bindings)

- Change log → What changed in the files served here, newest first. → [Read page](https://ratstack.sh/log)

- Configuration is a supplied, validated dependency → Parse configuration when a Layer builds, reject invalid values, and supply controlled settings in tests. → [Read page](https://ratstack.sh/lore/configuration-is-a-dependency)

- Dependency injection is the reason to choose Effect → Effect tracks service requirements in types and supplies replaceable implementations through Layers. → [Read page](https://ratstack.sh/lore/dependency-injection-is-the-reason-to-choose-effect)

- Durability → Seven durable Effect patterns, each with its seam, its fence, and the incident that taught it. → [Read page](https://ratstack.sh/systems/durability)

- Durability starts with a recovery record → A reading order for storage, replay, worker ownership, overload, and recovery tests. → [Read page](https://ratstack.sh/lore/durability)

- Effect basics → An Effect describes work, expected failures, and required services before a runtime executes it. → [Read page](https://ratstack.sh/lore/effect-basics)

- Effect keeps the surfaces on one contract → Schema owns values, projections build interfaces, and Layers supply implementations. → [Read page](https://ratstack.sh/lore/how-we-do-it-with-effect)

- Feature flags → Typed feature flags with owners, removal dates, and stable subject rollouts. → [Read page](https://ratstack.sh/systems/flags)

- Full agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms-full.txt)

- learn-rat-stack → Trace a capability through Effect, XState, five projections, the CLI, and Alchemy. Try hosted search and read. → [Read page](https://ratstack.sh/skills/learn-rat-stack)

- Pure cores reduce timeline coupling → Move deterministic rules out of time-dependent actions and shared mutable state. → [Read page](https://ratstack.sh/lore/pure-cores-reduce-timelines)

- query-design → Design or review SQL reads, writes, scans, backfills, and slow database paths. Use before changing a store method or any loop that queries. Covers round-trip arithmetic, batching, keyset paging, index evidence, row budgets, PlanetScale Vitess limits, Hyperdrive connections, statement-count tests, and statement-template fences. → [Read page](https://ratstack.sh/skills/query-design)

- Rat Stack lore | rat-stack → Short, source-grounded notes on the ideas and decisions behind rat-stack. → [Read page](https://ratstack.sh/lore)

- Scopes release resources when work ends → Acquire resources lazily, keep their use inside the owner, and release them after success, failure, or interruption. → [Read page](https://ratstack.sh/lore/scopes-own-resources)

- Source change history (log.md) → The generated change log as Markdown. → [Read page](https://ratstack.sh/log.md)

- Structure an Effect codebase by domain → Start with folders for application work, services and Layers in the same file, and startup code that supplies implementations. → [Read page](https://ratstack.sh/lore/structure-effect-by-domain)

- Workers answer requests; Durable Objects own named state → A Worker must not rely on module state between requests, so state that must persist lives in a Durable Object addressed by name. → [Read page](https://ratstack.sh/lore/workers-answer-requests-durable-objects-own-named-state)

## Unlinked mentions

- [A cartridge owns one job and its resources](https://ratstack.sh/lore/cartridges) → A Layer describes how to build services and supply their dependencies.¶

- [A clean playground](https://ratstack.sh/lore/a-clean-playground) → A Layer describes how to build services and supply their dependencies.

- [A Layer as constructor](https://ratstack.sh/lore/layer-constructor-pattern) → A Layer describes how to build a service and supply its dependencies.

- [A service captures its construction dependencies](https://ratstack.sh/lore/services-capture-dependencies) → A Layer describes how to build a service and supply its dependencies.

- [add-a-capability](https://ratstack.sh/skills/add-a-capability) → A Layer builds services and supplies their construction dependencies.¶

- [add-a-lifecycle-machine](https://ratstack.sh/skills/add-a-lifecycle-machine) → Provide its service Layer in apps/cli/src/cli.ts.

- [add-a-store](https://ratstack.sh/skills/add-a-store) → A Layer builds services and supplies their construction dependencies.

- [Agent rules for rat-stack (AGENTS.md)](https://ratstack.sh/AGENTS.md) → Role: Private crash-trace archive: trace schemas, captureCrashes, and the R2 archive layer (@rat-stack/crash/r2).

- [Bindings](https://ratstack.sh/lore/bindings) → Alchemy documents the same two steps for queues: WriteQueue in the init phase, and WriteQueueBinding in the runtime layer.

- [Build and run rat-stack (README.md)](https://ratstack.sh/README.md) → ts imports its content capabilities and Node layer; apps/web/src/website.ts imports its RPC workers.

- [Code snippets quote a pinned source](https://ratstack.sh/lore/code-snippets) → A Layer describes how to build a service and supply its dependencies.

- [Configuration is a supplied, validated dependency](https://ratstack.sh/lore/configuration-is-a-dependency) → A Layer describes how to build it and supply its dependencies.

- [Context and requirements](https://ratstack.sh/lore/context-and-requirements) → The tests pay the same debt with their own Layer:¶

- [Dependency injection is the reason to choose Effect](https://ratstack.sh/lore/dependency-injection-is-the-reason-to-choose-effect) → A Layer builds its implementation and declares its construction requirements.

- [Devtools](https://ratstack.sh/systems/devtools) → A Layer describes how to build services and supply their construction dependencies.

- [Effect + Alchemy peer patterns](https://ratstack.sh/resources/same-version-repos) → This is the closest inspected resource graph to rat-stack’s planned PlanetScale Postgres Layer.

- [Effect 4 study: September 2026](https://ratstack.sh/resources/effect-4-reference-projects) → Why it matters to us: Our infra layer.

- [Effect basics](https://ratstack.sh/lore/effect-basics) → A Layer describes how to build a service and supply its dependencies.¶

- [Effect keeps the surfaces on one contract](https://ratstack.sh/lore/how-we-do-it-with-effect) → provide supplies a Layer’s dependencies.

- [Effect Office Hours 27: Alchemy, infrastructure as effects](https://ratstack.sh/lore/effect-office-hours-27-alchemy-infrastructure-as-effects) → A Layer describes how to build services and supply their dependencies.

- [Hexagonal architecture](https://ratstack.sh/lore/hexagonal-architecture) → Rat-stack’s Effect layer follows the inside/outside boundary.

- [Infrastructure as effects](https://ratstack.sh/lore/infrastructure-as-effects) → An Alchemy Layer can declare the cloud resources behind a service.

- [investigate-a-failure](https://ratstack.sh/skills/investigate-a-failure) → Write it down with its evidence and move to the next layer.¶

- [keep-or-cut](https://ratstack.sh/skills/keep-or-cut) → A Layer builds services and supplies their construction dependencies.

- [learn-alchemy](https://ratstack.sh/skills/learn-alchemy) → A Layer builds services and supplies their construction dependencies.

- [learn-rat-stack](https://ratstack.sh/skills/learn-rat-stack) → A Layer builds services and supplies their construction dependencies.¶

- [Lint and type escape ledger (debt.md)](https://ratstack.sh/debt.md) → Reason: The Mischief router’s layer scope owns this cache: one dynamic import and one MCP sub-router build over services captured at router construction, with no request-bound I/O.

- [One schema, three surfaces](https://ratstack.sh/lore/one-schema-three-surfaces) → ts derives HttpApi endpoints, the handler Layer, and OpenAPI.¶

- [Purpose and boundaries of rat-stack (VISION.md)](https://ratstack.sh/VISION.md) → With Alchemy, an Effect Layer can declare the cloud resources it needs.

- [query-design](https://ratstack.sh/skills/query-design) → effect and a counting executor Layer at the adapter boundary.

- [Run Effect at the integration boundary](https://ratstack.sh/lore/run-effect-at-the-boundary) → A Layer describes how to build a service and supply its dependencies.

- [Schema projections: 2026-09-18 history](https://ratstack.sh/resources/schema-projections-and-code-mode) → live with the layer provided inline.

- [Scopes release resources when work ends](https://ratstack.sh/lore/scopes-own-resources) → A service Layer can own that resource for its build lifetime.

- [Structure an Effect codebase by domain](https://ratstack.sh/lore/structure-effect-by-domain) → A Layer describes how to build a service and supply its dependencies.¶

- [test-behaviour](https://ratstack.sh/skills/test-behaviour) → Keep one, and supply services through a Layer:¶

- [Tests prove behavior through supplied services](https://ratstack.sh/lore/tests-that-earn-their-place) → A Layer describes how to build a service and supply its dependencies.

- [Trace operations where they mean something](https://ratstack.sh/lore/trace-meaningful-operations) → Mischief and RpcBackend register a per-event telemetry Layer.

- [uncomplect](https://ratstack.sh/skills/uncomplect) → Layer: A description of how to construct services and supply their dependencies.¶

- [Worker init runs twice](https://ratstack.sh/lore/init-runs-twice) → See cartridges for the rule that each resource belongs to its Layer and the fence for the required tests that check this separation.¶
