Shared-DB transactions
Shared-DB transactions
Two rules for db.transaction() on the shared Drizzle client (meta.db). Per-user SQLite writes use withWriteLock instead (see gate-ordering.md).
The callback is synchronous
Bun's native transaction wrapper does not await an async callback. It calls the callback and issues COMMIT as soon as the call returns, which for an async function is at its first internal await: later statements run after the commit, and a later throw rolls nothing back. It does not throw or warn.
Every bun-sqlite/Drizzle call is synchronous underneath, so drop async/await inside the callback: .sync() on tx.query.*.findFirst()/findMany() reads, .run() on tx.insert()/.update()/.delete() writes.
// WRONG: COMMIT fires at the first await; the update runs unprotected after
// commit, and a later throw won't roll back the insert.
await db.transaction(async tx => {
const existing = await tx.query.purchases.findFirst({ where: ... });
if (existing) return;
await tx.insert(purchases).values({ ... });
await tx.update(users).set({ ... }).where(...);
});
// RIGHT: fully synchronous callback, real atomicity
db.transaction(tx => {
const existing = tx.query.purchases.findFirst({ where: ... }).sync();
if (existing) return;
tx.insert(purchases).values({ ... }).run();
tx.update(users).set({ ... }).where(...).run();
});
Transactions begin IMMEDIATE
withWriteLock is an in-process mutex: under cluster.ts it serializes nothing across worker processes; only SQLite's own locking does. Drizzle's default BEGIN DEFERRED makes a read-then-write transaction upgrade its lock mid-flight, which fails at once with database is locked (no busy_timeout wait) when another process committed first: 2037 of 2400 Stripe-handler transactions failed this way across 12 processes.
withImmediateTransactions (src/lib/db/immediate-transactions.ts) makes IMMEDIATE the default for the real client and for makeTestSharedDb(). Never pass { behavior: 'deferred' } to a transaction that writes, and call .immediate() on any raw bun:sqlite db.transaction() that reads before it writes (as runUserMigrations does). make check-write-contention is the regression check; numbers in performance.md.