Part 10 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-10tag.
Part 9 ended on a promise: once creating a user writes something else, both writes have to land or neither does. This part adds the second write. Every new user now gets a created row in a user_events table, which a background job in part 14 can pick up.
CREATE TABLE user_events ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, user_id bigint NOT NULL REFERENCES users (id), type text NOT NULL, created_at timestamptz NOT NULL DEFAULT now())With pg you’d write this by hand. Take a client with pool.connect(), send BEGIN, run the inserts in a try, COMMIT at the end, ROLLBACK in the catch, and client.release() in a finally, because forgetting that one leaks a connection for good. It works, and it has a hole you won’t see in tests: when the client hangs up, nothing stops. I checked with a bare node:http handler that waits three seconds. After curl --max-time 1 gave up, the handler woke up and carried on, with res.destroyed already true. Your transaction commits a user nobody got a response for.
Two writes, one transaction
create: Effect.fn("Users.create", { attributes: { "db.system": "postgresql" } })( function* (input: NewUser) { const user = yield* insert(input) yield* sql`INSERT INTO user_events ${sql.insert({ user_id: user.id, type: "created" })}` yield* Effect.annotateCurrentSpan("user.id", user.id) return user }, // Both INSERTs run on one connection between BEGIN and COMMIT. Any failure, or an interruption, rolls back. sql.withTransaction, Effect.catchTags({ SqlError: Effect.die, SchemaError: Effect.die, NoSuchElementError: Effect.die }),),That’s the whole change, one line in the extra arguments. sql.withTransaction takes an Effect and returns one with SqlError added to its errors, so it fits there like any other combinator, inside the Users.create span, before the catchTags that turns database failures into defects. Order matters: the catchTags has to come after, or the SqlError from a failed COMMIT would slip past it.
The body doesn’t mention the transaction. Both queries use the same sql as before, and they still end up on the transaction’s connection. withTransaction puts that connection in the fiber’s context, and every query checks the context before it asks the pool.
To see it roll back, I renamed user_events in psql and POSTed Linus. The server answered 500 with relation "user_events" does not exist in the log, and users still had only Ada and Grace. After renaming it back, the next POST gave Linus id 4, not 3. A rollback undoes rows, but an identity sequence doesn’t go backwards, so expect gaps in the ids.
Hanging up halfway
The interesting failure isn’t an error. It’s the client leaving.
In a scratch copy I put SELECT pg_sleep(3) between the two inserts and ran curl --max-time 1 against POST /users. The server logged http.status: 499. Postgres logged canceling statement due to user request on the pg_sleep. Hopper wasn’t in users, and pg_stat_activity had no connection idle in transaction.
Three different pieces made that happen. NodeHttpServer listens for the response’s close event and interrupts the request fiber if it fires before the response is done.1 PgConnection handles that interruption by sending Postgres a CancelRequest on a side connection, which is the line in the Postgres log. And withTransaction sees an interrupted exit and runs ROLLBACK before it hands the connection back.
Then I took sql.withTransaction out and did it again. Same 499, same cancelled pg_sleep, and this time Hopper was in users as id 6 with no row in user_events. Interruption alone stops the work; it doesn’t undo what already ran. You need both.
withTransaction is acquire, use, release
Read makeWithTransaction in SqlClient.ts and there’s nothing special in it. It’s the same shape you’d write with Effect.acquireRelease. It opens a Scope, takes a connection from the pool into it and sends BEGIN. Then it runs your effect with the connection in its context. When that finishes it looks at the Exit: success sends COMMIT, anything else sends ROLLBACK. Last, it closes the scope, and the connection goes back to the pool.
All of it sits inside Effect.uninterruptibleMask. Only your effect gets its interruptibility back, so an interruption can stop your queries but can’t land between BEGIN and the rollback and leave the connection checked out.
A Scope is a list of finalizers, and closing it runs them, last one added first. Effect.acquireRelease adds one. Here’s the same thing at toy size, from gotchas.ts, timed out after 100 ms while it waits forever:
acquire connection acquire transaction release transaction Failure release connection Failurescoped FailureBoth finalizers ran, transaction first, and each one got the Exit, which is how withTransaction knows whether to commit.
Scope shows up in the type
withTransaction closes its own scope, so you never see one. sql.reserve doesn’t. It’s for when you want one connection for a while without a transaction, and its type is Effect<Connection, SqlError, Scope>. That Scope in the requirements spreads to everything that yields it, until something closes it:
error TS2375: Type 'Effect<readonly any[], SqlError, SqlClient | Scope>' is not assignable to type 'Effect<unknown, SqlError, SqlClient>' Type 'SqlClient | Scope' is not assignable to type 'SqlClient'.Effect.scoped is the fix. It opens a scope, runs the effect and closes it, and the requirement goes away. In plain Node the reminder to call client.release() is a code review comment. Here it’s a type error.
Gotchas
gotchas.ts runs each of these against its own tables:
no transaction users: [1]withTransaction users: [1]interrupted Failure after 500 ms, users: [1], idle in transaction: 0connections outside: 3, inside: 1forked PgConnection: Pinned connection was released, users: [1,4]reserve same connection: trueThe first two lines are the two-writes case from above in miniature. The third is a five-second transaction timed out at 500 ms: Postgres cancelled the sleep, so the rollback didn’t wait for it.
- A transaction is one connection. Three queries with
concurrency: "unbounded"used three connections outside a transaction and one inside. They take turns, soEffect.allbuys you nothing in there. - Don’t fork out of a transaction. A fiber started with
Effect.forkDetachinsidewithTransactioninherits the context, connection included. When it ran its INSERT after the commit, it failed withPinned connection was released. I’m glad it fails loudly instead of writing on whatever request got that connection next. A background job should start its own transaction. - Nested
withTransactioncalls become savepoints. I read that in the source and didn’t need it here. - Ada has no
createdevent. The migration doesn’t backfill. If part 14 wants every user to have one, that’s a0003.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-10npm installdocker compose up -d --waitcp .env.example .envnpm startA database from part 9 picks up migration 2 on the next start. node --env-file=.env src/part-10/gotchas.ts prints the output above and drops its tables at the end. The repo is still on effect 4.0.5.
Anyone can create a user right now, and nothing records who did it. That’s the next thing to fix.
Next in the series: auth middleware and a CurrentUser service.
- Part 11 — Auth middleware and a CurrentUser service: POST /users needs a bearer token. An HttpApiMiddleware provides CurrentUser, Users.create asks for it, and a route without the middleware doesn't compile.
Footnotes
-
packages/platform/node/src/NodeHttpServer.tsateffect@4.0.5callsfiber.interruptUnsafe(parent.id, ClientAbort.annotation)onclose, andHttpServerError.tsmaps that annotation to the 499. The transaction side ismakeWithTransactioninpackages/effect/src/sql/SqlClient.ts. ↩

