Transactions and scopes

By Esteban Trillo5 min readupdated Effect on the BackendEffectTypeScript

The client hangs up mid-transaction. The scope closes anyway: rollback first, then the connection goes back to the pool.
The client hangs up mid-transaction. The scope closes anyway: rollback first, then the connection goes back to the pool.

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-10 tag.

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.

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

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

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?

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:

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:

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:

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.
Inside sql.withTransaction you fork a fiber with Effect.forkDetach. It runs an INSERT 100 ms later, after the transaction has committed. What happens?

Run it

Terminal window
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.


  • 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

  1. packages/platform/node/src/NodeHttpServer.ts at effect@4.0.5 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. ↩

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.