Race-safe Writes and Batches
insertWhere, updateWhere and ledgers for race-safe writes, atomic D1 batches, and transaction outcomes and recovery.
Write safely under concurrency from an action: conditional inserts and updates, append-only ledgers, atomic D1 batches, and how to read a transaction's outcome. Start at Scoped Database for the db handle.
Race-safe writes: insertWhere, updateWhere, ledger
D1 runs one statement at a time, but it has no transaction that spans two
statements. So "read, decide, then write" races another request: two votes
both see "no vote yet", two reservations both see "3 credits left". The
scoped db has three methods that put the decision inside the write, so
the database makes it once.
// One vote per voter, only while the poll is open — ONE statement:
// INSERT INTO votes (…) SELECT … WHERE EXISTS (open poll) AND NOT EXISTS (my vote)
const vote = await db.insertWhere(votes, { pollId, voterId: ctx.userId!, choice }, {
exists: { table: polls, where: and(eq(polls.id, pollId), eq(polls.status, "open")) },
notExists: { table: votes, where: and(eq(votes.pollId, pollId), eq(votes.voterId, ctx.userId!)) },
});
if (!vote) return { voted: false }; // the guard did not hold; nothing was written
// UPDATE votes SET choice = ? WHERE <where> AND EXISTS (open poll)
const changed = await db.updateWhere(votes, { choice }, {
where: and(eq(votes.pollId, pollId), eq(votes.voterId, ctx.userId!)),
exists: { table: polls, where: and(eq(polls.id, pollId), eq(polls.status, "open")) },
});| Method | Statement | Resolves to |
|---|---|---|
db.insertWhere(table, values, { exists?, notExists? }) | INSERT … SELECT … WHERE [NOT] EXISTS (…) | the inserted row, or null when the guard failed |
db.updateWhere(table, set, { where, exists?, notExists? }) | UPDATE … WHERE <where> AND [NOT] EXISTS (…) | the updated rows ([] when nothing matched) |
- Everything the scoped
dbdoes still applies. The row is built by the ordinary insert path — scope columns stamped, audit columns hard-stamped, firewall-on-write checked, trigger hooks run, encrypted columns encrypted — and only theVALUESlist becomes a guardedSELECT. - Probes are firewalled. Each
exists/notExistsprobe ANDs its own table's firewall into its WHERE, so a guard can never test another tenant's rows. Pass one probe or an array; at least one is required, and every probe needs awhere(a probe with no WHERE would test the whole table).updateWhererefuses a missingwhere. - One row.
insertWheretakes a single values object. - Postgres. Under
READ COMMITTED, two concurrentINSERT … WHERE NOT EXISTSstatements can both succeed, so on Postgres the guarded statement runs afterpg_advisory_xact_lockin the same transaction (an interactive transaction, ordb.batch()on neon-http, which runs as one transaction). AnupdateWherewith no probes needs no lock: an UPDATE re-checks its own WHERE on the row it writes.
Ledgers: db.ledger.<name>
A ledger is a balance that must never go negative — credits, seats, quota,
stock. Declare it on the debits table; the grants table needs its own
defineTable:
// features/credits/credits.ts
export default defineTable(creditDebits, {
read: { access: { roles: ["owner", "admin"] } },
ledger: {
name: "credits", // db.ledger.credits (default: the table name)
grants: "creditGrants", // the grants table
reserve: { amountColumn: "amount", subjectColumn: "accountId", statusColumn: "status" },
},
});const reservation = await db.ledger.credits.reserve(input.accountId, 1, { purpose: "sms" });
if (!reservation) throw new ActionError("Not enough credits", "INSUFFICIENT_CREDITS", 402);
try {
await sendSms();
await db.ledger.credits.finalize(reservation.id);
} catch (err) {
await db.ledger.credits.release(reservation.id);
throw err;
}| Call | Statement | Resolves to |
|---|---|---|
reserve(subject, amount, values?) | INSERT INTO debits … WHERE Σ grants − Σ live debits >= amount | the reserved debit, or null when the balance is short |
finalize(id) | UPDATE debits SET status = 'finalized' WHERE id = ? AND status = 'reserved' | the row, or null if it was already settled |
release(id) | UPDATE debits SET status = 'released' WHERE id = ? AND status = 'reserved' | the row, or null if it was already settled |
balance(subject) | two firewalled sums | grants − (reserved + finalized) |
amountColumn and subjectColumn must exist on both tables; the debits table
also needs id and the status column (default status), which holds
reserved / finalized / released. Released debits do not count against the
balance; both sums are firewalled, and soft-deleted rows drop out of them like
every other read. amount must be a positive number (400 LEDGER_INVALID_AMOUNT
otherwise), and values may not set the subject, amount or status columns.
A missing table or column, or an unknown key, is a compile error.
Atomic D1 batches and concurrency
On Cloudflare D1, db.batch([builder, ...]) executes the supplied statements in
one native database transaction. A SQL error rolls back every statement,
including database triggers. Build the statements without awaiting them, then
await the batch. Results retain the input order and each builder's result type.
Quickback applies the scoped firewall, audit stamps, synchronous before hooks,
and supported encryption preparation. After hooks and change notifications run
only after the native batch commits. An after-hook failure cannot undo the
commit: it throws DB_BATCH_POST_COMMIT_FAILED with committed: true and the
batch results. Do not retry that write as though it rolled back. Batches
containing SEALED/vault writes are rejected before preparation because that
storage operation is not part of the same D1 transaction. Envelope-encrypted
columns are supported; encryption key metadata may be provisioned during
preparation, before the application-data transaction.
An update to a typed JSON column that needs to compare restricted keys with the
stored row is refused in a D1 batch with DB_BATCH_GATE_UNSUPPORTED before any
writes. That asynchronous check cannot yet join the atomic SQL transaction.
Updates whose action has permission for every affected key remain supported;
standalone updates retain their existing key checks.
Transaction outcomes and recovery
| Outcome | Evidence | May mutation code run again? |
|---|---|---|
| Rejected before submission | Invalid options/revision token, unsupported builder, or preparation failure before the native call | Only after fixing the rejection; preparation may already have provisioned encryption metadata. |
| Definitive SQL rollback | DB_BATCH_CONDITION_FAILED, STALE_REVISION, a batch firewall assertion, DB_BATCH_ROLLED_BACK, or a trigger or invariant refusal (422 TRIGGER_REJECTED, its code in details.code); details.committed: false | A bounded retry is allowed after correcting the condition or re-reading. Idempotency marker cleanup must be acknowledged first. |
| Submitted, outcome unknown | DB_BATCH_OUTCOME_UNKNOWN, details.committed: null; connection loss or a write deadline is not rollback evidence | No. Keep the same key and reconcile with application state. |
| Committed, hooks failed | DB_BATCH_POST_COMMIT_FAILED, details.committed: true | No. Business writes committed. Recover failed post-commit work separately. |
| Completed replayable response | A matching authenticated request returns the saved response with Idempotency-Replayed: true | No. The replay does not execute the handler. |
An unrecognized native failure stays outcome-unknown; Quickback only reports
rollback when it has affirmative SQL constraint/assertion evidence. The original
cause is retained server-side. Post-commit errors retain caller-ordered results
and failed-hook indices in server code, but HTTP errors expose only the commit
indicator, never those unmasked rows. A failure while flushing commit notifications
uses index -1 because it does not belong to an individual builder.
An Idempotency-Key receipt is marked before submission. If the worker dies
between marking and submitting, that receipt still requires reconciliation;
absence of an acknowledgement is not evidence that retrying is safe. Neither
lease expiry nor the 24-hour cache sweep removes an unresolved or committed
atomic receipt. Catching an uncertain batch error and returning a 2xx/4xx does
not make the operation replayable. A second batch in that request is fenced too.
This transaction includes feature-D1 statements, SQL assertions, database triggers and the commit marker. It does not include separate AUTH_DB or audit stores, vault/R2 operations, external calls, or encryption-key provisioning during preparation. After hooks are not a durable delivery mechanism.
To make a queue effect commit with the writes, enable
durable effects and pass
effects: [{ key, queue, message }] to the batch. Each intent row joins this
same transaction, so it is rolled back, unknown or committed exactly as the
writes are. A repeated key rolls the batch back with DURABLE_EFFECT_CONFLICT.
Delivery is at least once.
A batch may require scoped SQL conditions before or after its writes:
const results = await db.batch([
db.update(invoices).set({ status: 'paid' }).where(eq(invoices.id, input.invoiceId)).returning(),
db.insert(paymentLines).values({ invoiceId: input.invoiceId, amount: input.amount }).returning(),
], {
preconditions: {
exists: { table: invoices, where: and(eq(invoices.id, input.invoiceId), eq(invoices.status, 'issued')) },
},
postconditions: {
exists: { table: invoices, where: and(eq(invoices.id, input.invoiceId), eq(invoices.status, 'paid')) },
},
});preconditions and postconditions use the same exists / notExists probe
shape as insertWhere, including arrays of probes. All probes are ANDed and
carry their table's firewall. The checks run inside the native transaction;
a failed final check rolls back the preceding writes. They raise
DB_BATCH_CONDITION_FAILED (409), with details.committed: false and the
failed phase. A conditional update matching zero rows is otherwise a valid
SQL operation: declare a condition when the operation requires a matching row.
For decisions made in JavaScript from several reads, enable
changes.counter and capture await db.revision() before
those reads. Pass the token to the batch:
const revision = await db.revision();
const posting = await preparePosting(db, input);
const result = await db.batch(buildPostingStatements(db, posting), { revision });Database triggers advance the active organization's counter for every write
to its organization-scoped feature tables, including raw SQL, queues, and cron.
The batch compares that counter before writing. If it changed, the entire batch
fails with STALE_REVISION (409), details.committed: false. The application
can repeat its read-only preparation with a fresh revision and a bounded retry
policy. Quickback does not automatically repeat application code or external
side effects.
The token is opaque and server-only, bound to the same scoped database handle that created it. It cannot be serialized, supplied by the client, or used on another handle. Reads must use that handle too: the primary connection or its request-scoped D1 session preserves the ordering needed for the check. The counter covers organization-scoped feature data, not separate AUTH_DB, external services, unscoped global tables, or another organization. Include explicit SQL conditions for additional same-database dependencies.
This API does not make D1 support interactive db.transaction(async tx => ...).
Reads and JavaScript preparation happen before the batch; SQL constraints and
conditions validate the result atomically. Ordinary HTTP changesets retain
their documented meta.transactional behavior.