# Transactions and scopes

- Published: 2026-11-17
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-10-transactions-and-scopes/

> Part 10 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-10), and this part is the `part-10` tag.

[Part 9](/writing/effect-backend-9-sql-and-migrations/) 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.

```sql title="src/migrations/0002_create_user_events.ts (excerpt)"
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

```ts title="src/Users.ts (excerpt)"
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.[^abort] `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.

**Quiz:** Users.create runs its two INSERTs inside sql.withTransaction. The client disconnects after the first INSERT, while the second is still waiting. What's in the database afterwards?

- The user, without its event
- Nothing: the handler is interrupted and the transaction rolls back
- Both rows: the handler finishes and commits, like plain Node

**Answer:** Nothing: the handler is interrupted and the transaction rolls back — The Node server interrupts the request fiber when the client goes away, and withTransaction treats an interruption like any other failure.

- Not "The user, without its event": That's what happens without withTransaction. With it, the interrupted exit rolls back the first INSERT too.
- Not "Both rows: the handler finishes and commits, like plain Node": Plain node:http keeps running after a disconnect. NodeHttpServer interrupts the fiber instead, and logs a 499.

## 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:

```text title="node src/part-10/gotchas.ts (excerpt)"
                 acquire connection
                 acquire transaction
                 release transaction Failure
                 release connection Failure
scoped           Failure
```

Both 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:

```text title="npm run check (src/part-10/types.ts without its @ts-expect-error, trimmed)"
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:

```text title="node src/part-10/gotchas.ts (excerpt)"
no transaction   users: [1]
withTransaction  users: [1]
interrupted      Failure after 500 ms, users: [1], idle in transaction: 0
connections      outside: 3, inside: 1
forked           PgConnection: Pinned connection was released, users: [1,4]
reserve          same connection: true
```

The 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, so `Effect.all` buys you nothing in there.
- **Don't fork out of a transaction.** A fiber started with `Effect.forkDetach` inside `withTransaction` inherits the context, connection included. When it ran its INSERT after the commit, it failed with `Pinned 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 `withTransaction` calls become savepoints.** I read that in the source and didn't need it here.
- **Ada has no `created` event.** The migration doesn't backfill. If part 14 wants every user to have one, that's a `0003`.

**Quiz:** Inside sql.withTransaction you fork a fiber with Effect.forkDetach. It runs an INSERT 100 ms later, after the transaction has committed. What happens?

- The INSERT goes through on a fresh connection from the pool
- It fails with a SqlError: the pinned connection was released
- The transaction waits for the forked fiber before committing

**Answer:** It fails with a SqlError: the pinned connection was released — The fiber still points at the transaction's connection, which went back to the pool at COMMIT. In 4.0.5 that's an error, not a silent write.

- Not "The INSERT goes through on a fresh connection from the pool": The forked fiber copied the context, and the transaction's connection is in it. Queries check the context before the pool.
- Not "The transaction waits for the forked fiber before committing": withTransaction waits for the effect you gave it, and forkDetach returns immediately.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-10
npm install
docker compose up -d --wait
cp .env.example .env
npm start
```

A 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.

[^abort]: `packages/platform/node/src/NodeHttpServer.ts` at [`effect@4.0.5`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/platform/node/src/NodeHttpServer.ts) calls `fiber.interruptUnsafe(parent.id, ClientAbort.annotation)` on `close`, and `HttpServerError.ts` maps that annotation to the 499. The transaction side is `makeWithTransaction` in [`packages/effect/src/sql/SqlClient.ts`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/src/sql/SqlClient.ts).

---

- **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.
