Part 9 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-9tag.
Part 8 left Users.layer as the only place that knew how users are stored. They lived in a Map, so every restart forgot Grace.
This part moves them to Postgres. It finally reads the DATABASE_URL that part 7 has been checking, and a migration creates the table at startup.
In a plain Node server you’d install pg, make a Pool in db.ts, and cast the rows to User with as. Migrations would be a separate tool with its own CLI. Effect splits the job in two. effect/sql has the generic parts: SqlClient, the query builder, SqlSchema and the Migrator. The driver is a separate package, pinned like effect:
npm install --save-exact @effect/sql-pg@4.0.5It has no dependencies. Version 4.0.5 speaks the Postgres wire protocol itself (PgProtocol.ts), so there’s no pg underneath. The repo also gained a compose.yaml that runs postgres:18 with the credentials from .env.example.
One client, read from config
const PgLive = PgClient.layerConfig({ url: Config.Redacted("DATABASE_URL") })
// Runs every migration in src/migrations that the database hasn't seen, while the layer builds.const MigratorLive = PgMigrator.layer({ loader: PgMigrator.fromFileSystem(`${import.meta.dirname}/migrations`),}).pipe(Layer.provide(NodeServices.layer))
// provideMerge: the migrator needs the client, and so does everything built on SqlLive.export const SqlLive = MigratorLive.pipe(Layer.provideMerge(PgLive))layerConfig takes part 7’s Config.Redacted, so the password stays <redacted> all the way into the driver. The layer provides two services, PgClient and SqlClient. The app only asks for SqlClient, the generic one, so nothing outside Sql.ts knows it’s Postgres.
Why NodeServices.layer? PgMigrator.layer’s type wants FileSystem, Path and ChildProcessSpawner. The first two read the migrations folder. The last one is for pg_dump, which only runs if you pass schemaDirectory. I don’t pass it, but the type asks regardless.
Queries are tagged templates
sql is a template tag. Every ${} becomes a bind parameter, never text in the query. Here’s what three queries compile to:
value ["SELECT * FROM users WHERE name = $1",["Robert'); DROP TABLE users;--"]]identifier ["SELECT \"name\" FROM \"users\"",[]]insert ["INSERT INTO users (\"name\",\"email\") VALUES ($1,$2)",["Grace","grace@example.com"]]Bobby Tables stays a value. To put a name into the query you call sql("users"), which quotes it as an identifier. sql.insert(object) writes the columns and placeholders. I POSTed Bobby’s name to the real server. It came back 201, and the table was still there.
Rows go through Schema
Rows from sql are typed as ReadonlyArray<Row>. That’s a guess. SqlSchema puts a schema on both ends: Request encodes the input, Result decodes each row. Users.make now yields SqlClient instead of Ids:
const sql = yield* SqlClient.SqlClient
// Postgres returns bigint ids as JS bigints. User.id is a string, so cast in the query.const findById = SqlSchema.findOne({ Request: Schema.String, Result: User, execute: (id) => sql`SELECT id::text, name, email FROM users WHERE id = ${id}`,})const insert = SqlSchema.findOne({ Request: NewUser, Result: User, execute: (input) => sql`INSERT INTO users ${sql.insert(input)} RETURNING id::text, name, email`,})Result: User is part 5’s schema, the one the API contract uses. A row that doesn’t fit the response fails here, not on the wire.
It caught me on the first query.
The id column is bigint, and this driver returns bigint as a JS bigint (1n). User.id has been a string since part 4:
bigint id SchemaError Expected string at ["id"]With pg and as User, that 1n would have passed the type checker as a string. The ::text cast keeps ids as strings in the API and numbers in the table. Ada is still "1".
findOne fails with NoSuchElementError when no row comes back. The service turns that into part 6’s UserNotFound, and database failures into defects:
find: Effect.fn("Users.find", { attributes: { "db.system": "postgresql" } })( function* (id: string) { yield* Effect.annotateCurrentSpan("user.id", id) return yield* findById(id).pipe( Effect.catchTag("NoSuchElementError", () => new UserNotFound({ id })), ) }, // A database or decoding failure isn't the caller's problem: it's a defect, and a 500. Effect.catchTags({ SqlError: Effect.die, SchemaError: Effect.die }),),My first draft had Effect.orDie there. The extra arguments wrap the whole body, catchTag included, so orDie killed UserNotFound too. /users/4 became a 500. The only warning was a type error in the old in-memory version, which no longer matched the service. Naming the two tags is longer, and it keeps the 404.
Migrations run before anything else
A migration is a file in src/migrations named <id>_<name>.ts. Its default export is an Effect that needs SqlClient:
export default Effect.gen(function* () { const sql = yield* SqlClient.SqlClient yield* sql` CREATE TABLE users ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, email text NOT NULL ) ` yield* sql`INSERT INTO users ${sql.insert({ name: "Ada", email: "ada@example.com" })}`})Ada got an email. User.email is an optional string, and a null from the database fails to decode (Expected string at ["email"]), so the column is NOT NULL.
PgMigrator.layer runs while the layer builds. It creates effect_sql_migrations if needed and locks it. Then it runs everything pending in one transaction. On a fresh database, Config to Listening took about 50 ms, and the table had one row: 1 | create_users. You won’t see that in the log, because the migrator logs at Debug. I checked the table.
On the next start it finds 1 recorded and runs nothing. Grace, POSTed before the restart, is still id 2.
Three things surprised me. gotchas.ts runs the migrator against its own gotcha_migrations table:
1 and 3 [[1,"one"],[3,"three"]]then add 2 []tables gotcha_migrations, gotcha_one, gotcha_three4 fails Cause([Die(MigrationError: Migration "4_four" failed (cause: ... division by zero))])after 4 gotcha_four exists: false, recorded: 1, 3two at once [[5,"five"]] []The first two lines can hurt you. The migrator only runs ids above the highest one it has recorded. Migration 2, added after 3 ran, is skipped without a word. Two branches that each add “the next number” will do this to each other.1
A failing migration rolls back whole: its table and its row in the migrations table. I tried it on the real server too. A 0002 added a created_at column, then a NOT NULL column to a table with rows. Postgres refused: column "nickname" of relation "users" contains null values. Afterwards created_at wasn’t there either, and the process had exited 1 without listening.
Two servers starting at once is fine. The second waits on the lock, sees 5 is recorded, and does nothing.
Where the database goes in main.ts
Part 8’s convention says a service’s layer arrives with its dependencies. So I put Layer.provide(SqlLive) on Users.layer and pointed the server at a database that accepts TCP and never answers.
curl /health hung. The port was open and requests waited until the connect timeout killed the process five seconds later. Users.layer builds inside HttpRouter.serve, after the server listens. Part 8 warned about this.
So I also provided SqlLive under the HTTP server, next to LogConfig. With a log line in PgLive, the server printed PgLive built twice, from two fibers.
Two pools.
Part 8’s “shared by reference” holds within one build, and serve runs its own. Its JSDoc puts it plainly: layers first built inside the app “are private to this server”.
In my runs, providing it on both sides still built it twice. The fix is one home for the database, outside serve. Users.layer now asks for SqlClient instead of providing it:
// Bottom up: the config check, then the database and its migrations, then the port.// provideMerge passes SqlClient on to everything inside HttpRouter.serve.const HttpLive = NodeHttpServer.layerConfig(createServer, { port }).pipe( Layer.provideMerge(SqlLive), Layer.provide(LogConfig),)provideMerge is part 8’s other tool. It builds SqlLive first and keeps SqlClient in the output, so HttpLive hands both HttpServer and SqlClient to everything under serve. Use plain provide and the types notice:
error TS2684: The 'this' context of type 'Effect<never, SqlError | ConfigError | MigrationError | ServeError, SqlClient>' is not assignable to method's 'this' of type 'Effect<unknown, unknown, never>'. Type 'SqlClient' is not assignable to type 'never'.Now PgLive built prints once. Against the silent database, curl /health gets connection refused until the process exits 1. UsersLive still provides Users.layer right under the handlers, as in part 8. main.ts is 46 non-blank lines (part 8: 41).
The Map didn’t go away. It’s Users.layerMemory now: the side files from parts 1, 2, 3 and 8 run against it, and so can a test that doesn’t want a database.
Gotchas, and what I left alone
- Huge ids are a 500.
/users/99999999999999999999passesUserId’s pattern, then Postgres saysvalue "99999999999999999999" is out of range for type bigint. That’s aSqlError, so a defect, so a 500. A max length onUserIdwould make it a 400. It’s a bug, and I’m leaving it for now. - There are no down migrations. Undoing one means a new one with a higher id.
- 4.0.6 shipped while I wrote this. The repo stays on 4.0.5, and everything here ran on 4.0.5.
I skipped Model.Class and SqlModel.makeRepository, which the Effect docs’ SQL example uses. They derive insert and update schemas from one model. That earns its keep with more columns and more update paths. With three columns and two queries, the SQL is shorter.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-9npm installdocker compose up -d --waitcp .env.example .envnpm startnode --env-file=.env src/part-9/gotchas.ts prints the output above. It uses its own gotcha_* tables and drops them at the end.
Creating a user is one INSERT today. Once it also writes something else, both writes have to land or neither does. That needs a transaction, and a connection held for as long as it runs.
Next in the series: transactions and scopes.
- Part 10 — Transactions and scopes: Creating a user writes two rows inside sql.withTransaction, and a client that hangs up mid-request rolls it back: Scope and acquireRelease make the connection come home.
Footnotes
-
packages/effect/src/sql/Migrator.tsateffect@4.0.5: therunloop hasif (currentId <= latestMigrationId) continue, runs the rest insql.withTransaction, and turns a migration’s failure into aMigrationErrordefect. ↩

