Skip to content

Transactions

A transaction makes several writes succeed or fail together. base.transaction() sends a list of operations in one request and runs them in one Postgres transaction, with the caller’s role and JWT, so RLS, grants, timeouts and rate limits apply as they do for single requests. If any operation fails, everything is rolled back and the promise rejects with a TransactionError.

import { TransactionError } from "@potalab/base"
try {
const { value } = await base.transaction((tx) => {
const order = tx.from("orders").insert({ note: "gift" }).returning("id")
tx.from("order_items").insert([
{ order_id: order.ref("id"), sku: "A", qty: 1 },
{ order_id: order.ref("id"), sku: "B", qty: 2 },
])
tx.from("stock").update({ qty: { $inc: -1 } }).eq("sku", "A").gte("qty", 1).expect({ affected: 1 })
return order.index
}, { retry: 2 })
} catch (e) {
if (e instanceof TransactionError) {
e.failedIndex // which operation failed
e.pgCode // Postgres SQLSTATE (23505, 42501, ...) or BT409 when an expect() was not met
e.retryable // true after a deadlock, serialization failure or lock timeout
}
}

The callback only records operations; nothing is sent until it returns. You cannot await an operation inside it, because its result exists only after commit. To use a value produced by an earlier operation, pass op.ref("column") to a later one (it must return exactly one row).

Supported in tx Notes
from(t).insert / upsert / update / delete / select update and delete without a filter need .all(). select returns flat columns only.
rpc(fn, args) Only SECURITY INVOKER functions. A scalar result is returned as [{ result: value }].
.expect({ affected }) On a write: the number of affected rows must be n or within { min, max }. Otherwise the whole transaction rolls back with HTTP 409 and failedIndex set.
.when(op, { exists }) Run this operation only if an earlier one returned (or did not return) rows; also { affected: n | { min, max } }. A skipped operation has skipped: true in its result.
{ $inc: n } As a value in update and upsert: atomic col = col + n on a numeric column. No read-then-write race.

These three guards cover most “check, then write” flows in a single request, without raw SQL and without an expression language. Logic that needs more than that belongs in a SQL function called with tx.rpc(), or in an interactive transaction.

Limits by default: 50 operations, 1 MiB per request, 1000 rows returned. Isolation is read committed. A deadlock (40P01), serialization failure (40001) or lock timeout (55P03) answers HTTP 409 with retryable: true; nothing was committed, so { retry: 2 } resends the same request (the callback is not run again). A failed expect() is never retried.

base.transaction.interactive(cb, opts) is for the case the one-request form cannot cover: your code reads, decides, then writes. Each awaited statement runs inside one open transaction and resolves with its data (it rejects on error instead of returning { data, error }). If the callback throws, everything is rolled back. A deadlock or serialization failure (HTTP 409) re-runs the whole callback, up to retries (default 3), so keep the callback free of side effects outside the database.

await base.transaction.interactive(async (tx) => {
const row = await tx.from("inventory").select("qty").eq("product_id", id).forUpdate().single()
if (row.qty < n) throw new Error("out of stock") // rolls back
await tx.from("inventory").update({ qty: row.qty - n }).eq("product_id", id)
}, { isolation: "read committed", retries: 3 })

Prefer base.transaction() (with .expect(), .when(), { $inc } or a SQL function) when the decision can live in the database: it is one round trip and holds a connection only briefly. The e-commerce example shows both.

Pattern: conditional decrement (stock, balances, quotas)

Section titled “Pattern: conditional decrement (stock, balances, quotas)”

Never read a number, subtract in your code, and write it back: two requests will both read “1 left”. Do the check and the change in one UPDATE, which takes the row lock itself, and add a CHECK as a second line of defence. With base.transaction() that is one operation:

tx.from("inventory").update({ qty: { $inc: -n } }).eq("product_id", id).gte("qty", n).expect({ affected: 1 })

{ $inc: -n } is computed by the database (qty = qty + -n), .gte("qty", n) makes the update match nothing when stock is short, and .expect({ affected: 1 }) turns “nothing matched” into a rollback of the whole transaction. The same rule as a SQL function, if you prefer to keep it in the database:

create table inventory (
product_id bigint primary key,
qty int not null check (qty >= 0)
);
create function take_stock(p_product_id bigint, p_qty int) returns int
language plpgsql security invoker set search_path = '' as $$
declare v_left int;
begin
update public.inventory set qty = qty - p_qty
where product_id = p_product_id and qty >= p_qty
returning qty into v_left;
if not found then
raise exception 'out of stock' using errcode = 'P0001'; -- the whole transaction rolls back
end if;
return v_left;
end $$;

When one purchase touches several products, send the stock updates (or take_stock calls) sorted by product id. Every transaction then locks rows in the same order and two carts cannot wait on each other. Without the sort, the same test produced deadlocks and lock timeouts (see the example). Retrying a rolled-back transaction after a deadlock (40P01) or lock timeout (55P03) is safe, because nothing was committed.

Pattern: no double booking with an exclusion constraint

Section titled “Pattern: no double booking with an exclusion constraint”

“No two bookings of one room overlap” is a rule of the data, so let the database enforce it. A concurrent insert for an overlapping slot waits for the first one and then fails with 23P01 (HTTP 409), which your UI shows as “slot taken”.

create extension if not exists btree_gist;
create table bookings (
id uuid primary key default gen_random_uuid(),
room_id bigint not null,
during tstzrange not null,
status text not null default 'booked' check (status in ('booked', 'cancelled')),
constraint no_overlap exclude using gist (room_id with =, during with &&)
where (status <> 'cancelled')
);

Use half-open ranges ([start, end)) so 9:00 to 10:00 and 10:00 to 11:00 do not conflict. Cancelled rows drop out of the index, so the slot can be booked again.

Booking plus attendees is one base.transaction(); moving a booking is “cancel the old one, book the new one, or neither”:

await base.transaction((tx) => {
const old = tx.from("bookings").update({ status: "cancelled" }).eq("id", oldId).eq("status", "booked").expect({ affected: 1 })
tx.from("bookings").insert({ room_id, during: newRange }).when(old, { exists: true })
})
// a taken slot rejects with TransactionError { status: 409, pgCode: "23P01" } and the old booking stays booked

See the meeting room example.

Pattern: time-limited holds, payment by callback

Section titled “Pattern: time-limited holds, payment by callback”

Holding a seat or a unit while the customer pays can take minutes, far longer than any transaction should stay open. Do not keep a transaction open waiting for payment. Instead, make the hold a row:

  1. In a short transaction, reserve the units (conditional decrement or an available counter) and insert a holds row with expires_at = now() + interval '10 minutes'.
  2. Send the customer to the payment provider.
  3. When the provider calls your webhook or Edge Function, confirm the hold: mark the order paid and keep the stock.
  4. A scheduled job releases holds past expires_at and returns the units.

Each step is its own short transaction, and every step is idempotent (confirming an already confirmed hold does nothing), so retried callbacks are harmless. The timed hold example is a complete version.

Pattern: sequence numbers with a SQL function

Section titled “Pattern: sequence numbers with a SQL function”

Invoice numbers like INV-2026-000123 must not be computed as max(n) + 1 in your code. Use a sequence inside a function and call it from the transaction:

create sequence invoice_seq;
create function next_invoice_no() returns text
language sql security invoker set search_path = '' as $$
select 'INV-' || to_char(now(), 'YYYY') || '-' || lpad(nextval('public.invoice_seq')::text, 6, '0')
$$;
grant usage on sequence invoice_seq to authenticated;
await base.transaction((tx) => {
const no = tx.rpc("next_invoice_no")
tx.from("invoices").insert({ number: no.ref("result"), total: 120 })
})

A sequence never hands out the same number twice, even concurrently. It is not gap-free: a rolled-back transaction still consumes its number. If your regulation requires gap-free numbers, assign the number in a separate step at the moment the document is issued, and treat that as a design decision of its own.