Wiring a real app with layers

By Esteban Trillo6 min readupdated Effect on the BackendEffectTypeScript

The config check turns first, then the server listens. Moving a line can't change that.
The config check turns first, then the server listens. Moving a line can't change that.

Part 8 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the part-8 tag.

Part 7 ended with this at the bottom of main.ts:

src/main.ts at part-7 (excerpt)
const Server = HttpRouter.serve(Layer.mergeAll(Health, ApiRoutes, HttpApiScalar.layer(Api))).pipe(
Layer.provide(Users.layer),
Layer.provide(NodeHttpServer.layerConfig(createServer, { port })),
Layer.provide(LogConfig),
)

It works. A missing DATABASE_URL stops the server before it listens, but only because LogConfig is the last line. Swap two lines, or tidy the three into one call, and that guarantee goes away without a type error. Users.layer sits down there too, a long way from the handlers that use it.

In a plain Node or Hono server, the wiring is the import graph. db.ts creates a pool when it’s first imported, every route file imports it, and the order things start in is the order Node happens to evaluate modules. Tests replace the module. It’s fine until you need to know what starts before what.

This part rewires the server so each dependency is provided where it’s used, and startup order comes from what depends on what.

Users gets a dependency

Until now Users needed nothing. It made ids from the size of its own map. Part 9 hands ids to Postgres; for now they come from a small service, so Users has something to wire:

src/Ids.ts
// Hands out user ids. In memory for now: part 9's database takes over.
export class Ids extends Context.Service<Ids, { readonly next: Effect.Effect<string> }>()("Ids") {
static readonly layer = Layer.sync(Ids, () => {
let last = 0
return { next: Effect.sync(() => String(++last)) }
})
}

Users.make yields Ids, seeds Ada with the first id, and calls ids.next in create. Its layer provides Ids itself:

src/Users.ts (excerpt)
export class Users extends Context.Service<Users>()("Users", { make }) {
static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(Ids.layer))
}

That’s the shape Effect 4’s own docs use: a service’s layer arrives with its dependencies already provided, so whoever uses Users never hears about Ids.1 Leave the Layer.provide off and the third type parameter says what’s missing:

npm run check (src/part-8/types.ts without its expect-error line, trimmed)
error TS2375: Type 'Layer<Users, never, Ids>' is not assignable to type 'Layer<Users, never, never>'
Type 'Ids' is not assignable to type 'never'.

Layer<Out, Error, In>: what it builds, how it fails, what it still needs. Most wiring errors are that third slot not being never.

Provide it next to the handlers

The handlers are the only thing that uses Users, so Users.layer belongs on the handler group, not at the bottom of main.ts. There’s a catch. Part 7’s handlers called Users.use(...) inside each handler. That’s a per-request requirement, and the router keeps it on the type even after you provide Users to the group:

npm run check (src/part-8/types.ts, per-request handlers, trimmed)
error TS2375: Type 'Effect<never, ServeError, Users>' is not assignable to type 'Effect<never, ServeError, never>'
Type 'Users' is not assignable to type 'never'.

The requests would work: I ran that version of main.ts with a cast, and /users/1 answered 200. Without the cast, runMain won’t compile, so you’d end up providing Users a second time outside HttpRouter.serve, which is where part 7 had it. The fix is to yield Users once, while the group builds:

src/main.ts (excerpt)
// Yield Users once, when the layer builds, so it can be provided right here.
const UsersLive = HttpApiBuilder.group(
Api,
"users",
Effect.fn(function* (handlers) {
const users = yield* Users
return handlers
.handle("get", ({ params }) => users.find(params.id))
.handle("create", ({ payload }) => users.create(payload))
}),
).pipe(Layer.provide([Users.layer, ValidationLive]))

Now Users is an ordinary requirement of the group layer, and the Layer.provide right under it removes it. ValidationLive moved here too: the types showed that only the group needs it, not HttpApiBuilder.layer. Part 2’s getUser wrapper drops out of main.ts, since the handler has users in hand.

Order is a dependency, not a position

Layer.provide promises one thing about order: the dependency builds first. Layer.mergeAll promises nothing, and builds its layers at the same time. The array form, Layer.provide([a, b]), merges a and b, so it’s concurrent too. src/part-8/gotchas.ts has three tiny layers. Check takes 50 ms and fails, like a database that isn’t there; Listen stands in for opening the port; App needs both:

node src/part-8/gotchas.ts (excerpt)
chain check failed
array port open, check failed

The array is the refactor I’d have made to part 7’s three Layer.provide calls, and it opens the port before the check fails. Today LogConfig fails before anything gets far enough to notice, but part 9’s database check is a network round trip.

So the config check now sits on the one layer it has to beat:

src/main.ts (excerpt)
// Layer.provide builds LogConfig first, so the port opens only after the config check.
const HttpLive = NodeHttpServer.layerConfig(createServer, { port }).pipe(Layer.provide(LogConfig))
const Server = HttpRouter.serve(Layer.mergeAll(Health, ApiRoutes, HttpApiScalar.layer(Api))).pipe(
Layer.provide(HttpLive),
)

Drawn out, every Layer.provide is an arrow into the layer that needs it:

The layer graph in main.ts at part 8Each arrow points from a layer to the layer it is provided to, and Layer.provide builds the arrow's source first. Ids.layer is provided to Users.layer. Users.layer and ValidationLive are both provided to UsersLive, the handler group, and UsersLive is provided to ApiRoutes. ApiRoutes, Health and HttpApiScalar are merged with Layer.mergeAll, which builds them at the same time, and the merge goes into HttpRouter.serve. On a separate chain, LogConfig is provided to HttpLive, NodeHttpServer.layerConfig with the port, so the config check finishes before the port opens, and HttpLive is provided to the server.Ids.layerUsers.layerValidationLiveUsersLiveLayer.mergeAllHealthApiRoutesHttpApiScalarLogConfigHttpLivelayerConfig(port)ServerHttpRouter.serve
Layer.provide builds the source of an arrow first. Layer.mergeAll builds its three at once.

main.ts is now 41 non-blank lines (part 7: 37), and each Layer.provide sits under the layer that needs it. No DATABASE_URL still exits 1 without listening, and PORT=eighty still fails the same way. Here’s each wiring from this part and what it did when I ran it:

Pick a wiring
What happened
check failed. The port never opens: Check builds first, and Listen waits for it.
What happened
port open, check failed. The array builds both at once, so the port opens before the 50 ms check fails.
What happened
POST /users → 201 "2", then GET /users/2 → 404 "user 2 not found". Every request builds its own Users, with its own map.
What happened
Users built, Users built. Each call returns a new layer value, and layers are shared by reference. The same value twice builds once.
What happened
Requests work, but npm run check fails on runMain: Type 'Users' is not assignable to type 'never'. Yield Users when the group builds instead.
What happened
Config { port: 3000, databaseUrl: <redacted> }, Listening on 3000. /users/1 → 200, POST then GET /users/2 → 201, 200. No DATABASE_URL → ConfigError, exit 1, never listens.

Shared by reference

Two handler groups that both provide Users.layer get one Users, with one map. Within one build, each layer is built once, and “the same layer” means the same value, compared by reference:

node src/part-8/gotchas.ts (excerpt)
same reference Users built
two calls Users built, Users built

The second line is Layer.mergeAll(counted(), counted()), where counted is a function that returns a layer. Each call returns a new value, so each one builds its own Users with its own map. If you write layer factories that take options, that’s the bug waiting in them. Assign the result to a constant once, and pass the constant around.

The worse version is Effect.provide inside a handler. Nothing above the handler has built Users, so every request builds one:

node src/part-8/gotchas.ts (excerpt)
provide inside 201 "2" then 404 "user 2 not found"

Grace got id 2, in a map that was thrown away when the request ended.

A handler runs Users.use(...).pipe(Effect.provide(Users.layer)), and nothing else in the server provides Users. You POST a user, then GET it by the id you got back. What does the GET return?

provide or provideMerge

Layer.provide feeds Ids into Users and hides it: the result is a Layer<Users>. A test that creates a user and then wants the next id can’t yield Ids from it, and npm run check says Type 'Ids' is not assignable to type 'never'. Layer.provideMerge does the same feeding and keeps Ids in the output, the same instance Users used.2

src/part-8/gotchas.ts (excerpt)
const merged = Layer.effect(Users, Users.make).pipe(Layer.provideMerge(Ids.layer))
console.log("provideMerge ", await Effect.runPromise(nextAfterCreate.pipe(Effect.provide(merged))))
console.log("provide twice ", await Effect.runPromise(nextAfterCreate.pipe(Effect.provide(Users.layer), Effect.provide(Ids.layer))))
console.log("fresh Ids ", await Effect.runPromise(nextAfterCreate.pipe(Effect.provide(Users.layer), Effect.provide(Layer.fresh(Ids.layer)))))
provideMerge 3
provide twice 3
fresh Ids 1

Ada is 1, Grace is 2, so 3 means the test saw the same counter. The middle line surprised me. Providing Ids.layer again from outside also gives 3, because v4 shares the layer cache with nested Effect.provide calls, the same thing part 1 measured. Only Layer.fresh, or a new layer value, builds a second counter. So provide versus provideMerge is about what the type lets you reach, not about how many instances exist. Use provide by default, and provideMerge when the caller needs the dependency too.

What the types tell you

src/part-8/types.ts is type-check only. Without its @ts-expect-error lines:

npm run check (without the expect-error lines, trimmed)
error TS2375: Type 'Layer<Users, never, Ids>' is not assignable to type 'Layer<Users, never, never>'
Type 'Ids' is not assignable to type 'never'.
error TS2375: Type 'Effect<string, never, Ids>' is not assignable to type 'Effect<string, never, never>'
Type 'Ids' is not assignable to type 'never'.
error TS2375: Type 'Effect<never, ServeError, Users>' is not assignable to type 'Effect<never, ServeError, never>'
Type 'Users' is not assignable to type 'never'.

All three are the same sentence: something is still in the last slot. The first is Users without Ids. The second is a program that wants Ids from a layer that hid it. The third is the per-request handler group, Users provided on the group and still owed by the server. The type names the service, not the line that forgot it. So I ask which layer’s third slot it came from, and walk down main.ts from Server.

The gotchas, and when not to bother

  • The array form is concurrent. Layer.provide([a, b]) looks like a shorter chain and isn’t one. It’s right for Users.layer and ValidationLive, which don’t need each other, and wrong for anything that has to finish first.
  • Layer.fresh is the deliberate version of the factory bug. It builds a second instance on purpose, which is what a test wants when it needs its own counter, and almost never what a server wants.

When not to bother: a service with no dependencies doesn’t need any of this, and one Layer.provide at the edge is fine. And I didn’t split Users.layer into a version without Ids; the docs’ layerNoDeps is for tests that bring their own, and the series isn’t writing those yet.

Run it

Terminal window
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-8
npm install
cp .env.example .env
npm start

node src/part-8/gotchas.ts prints every line above. src/part-8/types.ts has the type errors.

Users.layer is now the only place that knows how users are stored and where ids come from. Part 9 changes both, in that file.

Next in the series: SQL and migrations with effect/sql.

  • Part 9 — SQL and migrations with effect/sql: Users move into Postgres: tagged-template queries, rows decoded by Schema, migrations that run before the port opens, and one connection pool for the whole server.

Footnotes

  1. ai-docs/src/01_effect/03_services/20_layer-composition.ts in the effect@4.0.5 package: layerNoDeps with the requirement, layer with Layer.provide, and layerWithSqlClient with Layer.provideMerge. The HTTP server example in ai-docs/src/51_http-server/ yields Users inside HttpApiBuilder.group and provides Users.layer on the group, the same shape as above. ↩

  2. Layer.ts at the effect@4.0.5 tag: provide (“returning a layer that only provides the services from this layer”), provideMerge (“returning a layer that provides both sets of services”), and merge/mergeAll (“The layers are built concurrently”). ↩

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.