Neon Transactions
Batch and interactive transactions on Neon, and measuring database cost with Server-Timing.
How batch and interactive transactions run on Neon for each connection mode, and how to measure what a request spends in the database. Start at Neon for connection modes.
Batch transactions
Whether a batch handler (PATCH /batch, DELETE /batch, …) is truly atomic
depends on the connection mode, and the response advertises the guarantee via
meta.transactional:
| Mode | meta.transactional | Behavior |
|---|---|---|
| Neon HTTP (Cloudflare default) | false | Fail-fast per-record loop, no rollback — drizzle-orm/neon-http has no interactive transactions, so this matches D1's semantics honestly |
| Neon Hyperdrive (Cloudflare) | true | db.transaction() wraps the loop; any failure rolls back every write in the batch |
| Neon WebSocket (Node/Bun) | true | db.transaction() wraps the loop; any failure rolls back every write in the batch |
drizzle-orm/neon-http throws "No transactions support in neon-http driver" at
runtime, so the HTTP path deliberately treats batches like D1 (fail-fast,
non-transactional) rather than emitting code that would 500 on every failed
batch. Honest advertisement over runtime surprises. For true atomic batches and
interactive transactions on Cloudflare, use
connectionMode: 'hyperdrive'.
Interactive transactions
connectionMode: 'hyperdrive' runs the feature database over a Cloudflare
Hyperdrive binding using
postgres.js (drizzle-orm/postgres-js), which supports real interactive
transactions — read current state, lock it, decide in TypeScript, then write
dependent rows, all committed atomically:
import { z } from "zod";
import { eq } from "drizzle-orm";
import {
defineAction,
ActionError,
registrations,
registrationEvents,
} from "../.quickback/define-action";
export default defineAction({
description: "Advance a registration inside one interactive transaction.",
access: { roles: ["admin"] },
input: z.object({ registrationId: z.string() }),
async execute({ db, input }) {
return db.transaction(async (tx) => { // tx is fully typed
const [reg] = await tx.select()
.from(registrations)
.where(eq(registrations.id, input.registrationId))
.for("update"); // row lock held to commit
if (!reg) throw new ActionError("Not found", "NOT_FOUND", 404); // → rollback
const [updated] = await tx.update(registrations)
.set({ status: nextStatus(reg) })
.where(eq(registrations.id, reg.id))
.returning();
await tx.insert(registrationEvents).values({ registrationId: updated.id });
return updated; // atomic commit
});
},
});Note the tx.select()…for("update") form: Drizzle's relational query API
(tx.query.<table>.findFirst) is blocked on the scoped
db/tx
because the tenant firewall can't be injected into relational queries. The
select builder gives you the same row lock with scope conditions applied
automatically.
Configure it on the database provider:
providers: {
database: {
provider: "neon",
config: { connectionMode: "hyperdrive", hyperdrive: { id: "<binding-id>" } },
},
}The compiler emits the [[hyperdrive]] wrangler binding pointing at your Neon
direct connection string. Each Worker invocation (request, queue batch,
cron, inbound email) opens one lease pool of up to five single-connection
postgres.js clients, shared by every createDb / createServiceDb call in it
— the request db, Better Auth, idempotency, the audit writer. Statements are
prepared (Cloudflare's guidance for postgres.js on Hyperdrive, which caches
named prepared statements; an unprepared statement costs an extra
parameter-describe round trip) and type-fetch round trips are skipped;
Hyperdrive owns the origin pool.
Every write statement runs as one pipelined claims transaction on a
leased connection: BEGIN plus the claims preamble travel as one message, then
the statement, then COMMIT, all written before anything is awaited. That is
one round trip once the statement is prepared on that connection and three
while it is cold — down from six. It fails closed by construction: a preamble
that errors after BEGIN aborts the transaction so the statement is refused
rather than run unscoped, and a failed statement turns the pipelined COMMIT
into ROLLBACK.
Reads share one transaction per connection. The first read-only statement
on a leased connection opens BEGIN READ ONLY plus the claims preamble and
leaves that transaction open; every later read on the same connection with the
same claims runs bare, one round trip, with no BEGIN/COMMIT around it. A
read under different claims (a service-lane lookup between caller reads, a
scope minted mid-request) re-stamps the preamble inside the open transaction —
set_config(…, true) is transaction-local, so the previous claims are gone the
moment the new ones land. The read lane is rolled back before a write or a
db.transaction() takes the connection, after any read error, as soon as the
handler returns (before deferred waitUntil work runs — a deferred read opens
a fresh lane), and when the invocation scope closes the pool. That ROLLBACK is its own round trip, never
pipelined with the write's BEGIN: Hyperdrive's transaction pooler releases
the origin connection at the transaction end and loses anything pipelined past
it, which hung every write that followed a read in 0.70.10–0.70.12. A
SELECT the server refuses inside a read-only transaction (nextval(), a
volatile function that writes) falls back to the write lane automatically. Only statements that begin with SELECT or a
non-modifying WITH and carry no FOR UPDATE / FOR SHARE qualify; anything
else is a write.
Each read sees everything committed before it, including the request's own
writes — Postgres runs READ COMMITTED by default, and a read-only transaction
changes nothing about that. Hyperdrive pools in transaction mode, so an open
lane pins one origin connection until the handler returns (up to five under
Promise.all); idle_in_transaction_session_timeout (15 s on the deployed
role) and the scope close bound the worst case. A ten-statement read path costs
about eleven round trips instead of thirteen to thirty-four, which is where the
tx versus stmts ratio in Server-Timing
comes from.
The pool closes when the invocation ends, after its waitUntil work
(deferred audit writes, after-commit effects) settles. A client that is never
closed leaves its backends mid-transaction, holding Hyperdrive origin
connections until Postgres times them out. Code outside an invocation — a
Durable Object, a test — gets a fresh pool per createDb call and owns
closing it.
Measuring database cost: Server-Timing
Every response from a Hyperdrive project carries a
Server-Timing
header, and the Worker logs one structured line per request with the same
fields plus the matched route pattern:
Server-Timing: total;dur=312.6, db;dur=212.4;desc="stmts=11 tx=2 cold=1", gate;dur=31, action;dur=240.8{"event":"request.timing","requestId":"…","method":"POST","route":"/api/v1/tasks/:id/approve","status":200,"totalMs":312.6,"dbMs":212.4,"stmts":11,"tx":2,"cold":1,"gateMs":31,"actionMs":240.8}| Field | Meaning |
|---|---|
total | Wall time from the request-id middleware to the response |
db | Time statements held a leased connection, summed. Statements that run concurrently (Promise.all) each count in full, so db can exceed the time the request actually spent waiting |
stmts | Statements run, including those inside db.transaction() |
tx | Claims transactions opened (one per statement, one per db.transaction()) |
cold | Connections the lease pool had to open for this invocation |
auth | Time from the request-id middleware to the end of the auth middleware: Better Auth's session and user lookups plus the membership/role lookup for the active org. Paid by every authenticated request, CRUD and action alike |
gate / action | Action routes only: the generated pre-action pipeline (auth, access, firewall pre-reads, input validation) vs. the action's execute body |
Statement text and parameters are never logged. Work the invocation defers to
waitUntil (audit writes, after-commit effects) runs after the header is sent
and is not counted.
cold=5 tx=5 on every bundle request is the pool shape, not a leak. The
lease pool is per invocation and holds up to five connections. A
bundle runs its sections in one Promise.all, so five or
more sections lease five connections at once; each is opened cold for this
request and opens its own read lane (BEGIN READ ONLY + claims), which is
the tx count. Summed db time exceeds wall time because those leases
overlap. Connections cannot outlive the invocation on Workers, so there is
nothing to warm across requests; the cost of a cold connection is the
Hyperdrive handshake plus three round trips before its prepared statements
are cached. Before changing a bundle's shape, run SERVER_TIMING = "debug"
and read the first flags per lane: if most statements are first, the
request is paying for connections, and fewer, larger sections (or a lower
section count) is the lever; if few are, the cost is the statements
themselves.
The header and log line are on by default. Set the Wrangler var
SERVER_TIMING = "0" on a target (for example in environments.production.vars)
to turn both off there. SERVER_TIMING = "debug" adds a statements array to
the log line only (never the header): one entry per statement with the first
120 characters of the SQL, its duration, its lane (read, write, or tx for
a db.transaction()), and whether it was the first statement on its
connection. Parameters are never logged, and the trace is for dev and staging:
an N+1 shape shows up as the same SQL head repeated with per-row durations. Aggregate p50 / p95 by route with wrangler tail or
Workers Logs to find the endpoints where round trips, not the statements
themselves, are the cost.
Postgres authorizes SELECT … FOR UPDATE as both a read and a write: the row
must pass its SELECT and UPDATE policies. This matters for delegated
principals because a lane that declares only databaseAccess.select emits a
FOR SELECT policy — by design, since read-only is what the author declared.
Such a principal can read an eligible row but cannot lock it with
.for("update").
Keep read-only eligibility and reference-table lookups as ordinary scoped
selects. Lock the mutable grant, capacity, or redemption row that the action is
authorized to update. If an action legitimately must lock another table, declare
a narrowly bounded databaseAccess.update rule for that principal — which makes
its one lane policy FOR ALL with the same predicate as WITH CHECK. Do not
broaden the predicate or bypass the generated principal fence.
Security is preserved, unchanged. The verified caller claims run as the
first transaction-local statement inside the transaction (the same
set_config(..., true) preamble batches use), so RLS enforces inside the
callback and the claims reset at commit/rollback — they never leak across
Hyperdrive's connection pool.
Hyperdrive query caching must be disabled in the Hyperdrive configuration: its cache keys on query text,
not the caller's RLS claims, so a cached read would leak across tenants. HTTP
response ETags provide caching at the correct post-auth layer. The compiler
emits the binding but does not inspect or change the remote caching setting;
quickback deploy does not yet verify that setting either. Requesting an
interactive db.transaction() under any other connectionMode is a fail-closed
compile error.
Neon Row Level Security
Worker-scoped RLS on Neon — the set_config claim model, generated policies, the soft-delete lane, delegated principals, relationship arms and helper functions.
Neon Migrations
Better Auth schema generation, migrations, the quickback canary rehearsal on a Neon branch, and pg-core for raw Drizzle interop tables on Neon.