Transactions
A transaction is a sequence of database operations that succeed or fail as one unit. Either everything happens, or nothing does. Cascade exposes transactions through a single utility: transaction(async ctx => {...}). Same callback shape across Postgres and MongoDB; the driver differences are handled underneath.
The recommended pattern is the callback form: wrap your work in transaction(...) and let Cascade handle commit, rollback, and cleanup.
The callback pattern (recommended)
Section titled “The callback pattern (recommended)”import { transaction } from "@warlock.js/cascade";
const order = await transaction(async (ctx) => { const newOrder = await Order.create({ userId, total });
for (const item of items) { await OrderLine.create({ orderId: newOrder.id, ...item }); }
await User.whereId(userId).increment("orderCount");
return newOrder;});transaction is a thin shorthand over the current data source’s driver. If you have multiple data sources (rare), you can still reach the driver directly via getDatabaseDriver().transaction(...).
What happens:
- Auto-commit on success. If the callback returns normally, the transaction commits and the return value flows back out.
- Auto-rollback on error. Any thrown error rolls back and re-throws to the caller.
- Cleanup guaranteed. Session / connection cleanup happens whether you committed or rolled back.
This is the right shape for ~95% of transaction use. You don’t manage the session, you don’t remember to commit, you don’t need a try/finally.
Explicit rollback
Section titled “Explicit rollback”If the work inside the callback decides the transaction shouldn’t commit (validation failure, business-rule veto), call ctx.rollback(reason?):
await transaction(async (ctx) => { const balance = await Account.whereId(accountId).value<number>("balance"); if (balance < amount) { ctx.rollback("Insufficient funds"); }
await Account.whereId(accountId).decrement("balance", amount); await Transfer.create({ accountId, amount, type: "withdrawal" });});ctx.rollback() throws a TransactionRollbackError immediately — the callback exits, Cascade rolls back, and the error is re-thrown to the outer caller. Catch it explicitly if you want to handle the rollback case without a hard failure:
try { await transaction(async ctx => { ... });} catch (err) { if (err instanceof TransactionRollbackError) { // soft-fail UX } else { throw err; }}Driver caveats
Section titled “Driver caveats”MongoDB requires a replica set. A single-node MongoDB (mongod with no replica set config) doesn’t support transactions at all — the driver throws when you try. For local dev, run a single-node replica set (mongod --replSet rs0 + initial rs.initiate()). Production clusters are usually replica sets by default.
Postgres just works. No setup needed beyond a regular connection.
A nested transaction() joins the outer one. A transaction() called inside another transaction() does not throw and does not open a savepoint: it runs flat in the outer transaction, and nothing is committed until the outer one commits. Code placed after the inner transaction() therefore still runs before the outer COMMIT. When something must run only after the data is committed (an email, a cache clear), queue it with afterCommit(). If you need savepoint semantics, drop to the manual form (beginTransaction) and use the driver’s native savepoint API.
The manual pattern (rare)
Section titled “The manual pattern (rare)”When you need control that the callback form doesn’t give — multi-step orchestration across services that each manage part of the work — drop to the driver’s manual API:
import { getDatabaseDriver } from "@warlock.js/cascade";
const driver = getDatabaseDriver();const tx = await driver.beginTransaction();try { await driver.insert("users", { name: "Alice" }); await driver.insert("audit_logs", { ... }); await tx.commit();} catch (err) { await tx.rollback(); throw err;}beginTransaction() binds the transaction to the async flow that called it. Every query that flow runs after await driver.beginTransaction() (driver calls, models, query builders) uses the transaction’s session until you call commit() or rollback(). After either one, that same flow runs with no session, outside any transaction. Requests, timers and jobs running at the same time never see the session. You can also use tx.context (the MongoDB session or the PostgreSQL client) directly. Because it attaches to the async flow that called it, call beginTransaction() inside the async function that runs the transactional work, and always commit or roll back, for example with try / finally.
You own commit, rollback, and cleanup. The pattern is more error-prone (forget to commit in one branch and you’ve leaked a session); reach for it only when the callback form genuinely can’t express your flow.
What runs inside the transaction
Section titled “What runs inside the transaction”Anything that goes through the driver during the callback is part of the transaction. That includes:
Model.create()/model.save()/model.destroy()— all driver writes.- Query builder reads —
User.where(...).first(), etc. - Direct driver calls —
driver.insert(...),driver.update(...), etc.
Operations outside the driver — file writes, HTTP calls, cache invalidations — are not transactional. If you need them to roll back on transaction failure, do the irreversible work after the transaction completes:
const order = await driver.transaction(async ctx => { const o = await Order.create({ ... }); await OrderLine.create({ orderId: o.id, ... }); return o;});
// Only runs if the transaction committedawait sendOrderConfirmationEmail(order);The pattern: transaction owns the database; external side effects fire after commit.
import { transaction } from "@warlock.js/cascade";
const order = await transaction(async ctx => { const o = await Order.create({ ... }); await OrderLine.create({ orderId: o.id, ... }); return o;});
// Only runs if the transaction committedawait sendOrderConfirmationEmail(order);Events inside transactions
Section titled “Events inside transactions”Model lifecycle events (onSaving, onCreated, onDeleted, …) fire as they normally would inside a transaction. If you have an onCreated listener that emails the user, the email goes out even if the transaction later rolls back.
For that reason, side effects that should respect transaction outcome belong in afterCommit().
afterCommit(fn)
Section titled “afterCommit(fn)”import { afterCommit } from "@warlock.js/cascade";
User.events().onCreated((user) => { afterCommit(() => sendWelcomeEmail(user.get("email")));});
Product.events().onSaved(() => afterCommit(() => regenerateSitemap()));- Inside a transaction,
fnis queued and runs after the outermost COMMIT, in the order queued, awaited one by one. If the transaction rolls back (or the COMMIT fails), the queued callbacks are discarded. - Outside a transaction,
fnruns on the next microtask. The caller does not await it. - Errors thrown by a callback are logged. They never change the transaction result and never stop the remaining callbacks.
- Callbacks run after the transaction context has exited, so any database work they do is outside the finished transaction.
- Called from work that runs after the transaction ended (a timer armed inside it),
fnruns on the next microtask.
Good fits: cache clears, sitemap regeneration, emails, webhooks. afterCommit is in-memory, so a crash between COMMIT and the callback loses it; when the side effect must survive that, use an outbox / job queue.
Work scheduled inside a transaction
Section titled “Work scheduled inside a transaction”A setTimeout, a queue push or a fire-and-forget promise started inside the callback usually runs after the transaction has ended. That work runs outside the transaction and with no session: its Cascade queries behave as if no transaction had ever been opened, transaction() called from it opens a fresh transaction, and afterCommit() called from it runs on the next microtask.
await transaction(async () => { const user = await User.create({ name: "Sara" });
// Runs after COMMIT, outside the transaction, with no session. setTimeout(() => User.find(user.id), 100);});- It is not rolled back. If the transaction rolls back, the scheduled work still runs, and any writes it makes are committed on their own.
- To see committed data, queue the work with
afterCommit(): it runs after the outermost COMMIT and is discarded on rollback. - Do not rely on the transaction for anything armed this way, including reads that need the transaction’s uncommitted writes. Do that work before the callback returns.
Patterns
Section titled “Patterns”Try-with-fallback
Section titled “Try-with-fallback”async function transferFunds(from: string, to: string, amount: number) { return transaction(async (ctx) => { const fromBalance = await Account.whereId(from).value<number>("balance"); if (fromBalance < amount) ctx.rollback("Insufficient funds");
await Account.whereId(from).decrement("balance", amount); await Account.whereId(to).increment("balance", amount); await Transfer.create({ from, to, amount }); });}Bulk operations with all-or-nothing semantics
Section titled “Bulk operations with all-or-nothing semantics”await transaction(async (ctx) => { for (const row of csvRows) { await User.create(row); // any one failure rolls everything back }});For large bulk imports, consider chunking the transactions — one giant transaction holding a million inserts will tie up locks and replication far longer than ten smaller transactions of 100k each.
Reading-then-writing safely
Section titled “Reading-then-writing safely”await transaction(async (ctx) => { const post = await Post.whereId(id).first(); if (!post) ctx.rollback("Post not found");
// Inside the transaction, the read and write happen with consistent locking post.increment("viewCount"); await post.save();});For pure counter-style increments, prefer the query-builder form — Post.whereId(id).increment("viewCount") is a single statement with no read race, no transaction needed.
Going further
Section titled “Going further”- Atomic increments / decrements (race-safe without a transaction): Querying essentials + Query Builder API reference
- Outbox pattern for side-effects-after-commit — recipe
- MongoDB replica-set setup for local dev — recipe