Tx Hooks
Run side effects only after your database transaction commits.
Queuert writes chains and jobs in your transaction, and the side effects of those writes (notify events that wake workers, observability events) must not leak out of a transaction that rolls back. The state provider owns this: it implements onTransactionCommit(txCtx, callback), which runs callback after the transaction commits and before the call that opened it settles, and onTransactionRollback(txCtx, callback), which runs callback synchronously when the transaction, or the savepoint txCtx belongs to, rolls back. The client and the worker register every side effect through these two members, so what you pass to a mutating call or to complete is your transaction context and nothing else.
Two kinds of providers
How a provider implements onTransactionCommit and onTransactionRollback depends on its database client.
A client with transaction events (MikroORM's afterTransactionCommit and beforeTransactionRollback) lets the provider implement them natively: it looks the transaction up from the context and runs the callbacks from those events. The context is the client's own transaction handle, and you pass it alone:
TypeScript
await orm.em.transactional(async (em) =>
client.createChain({ em, typeName: "send-email", input }),
);A client without them (pg, postgres.js, Bun SQL, Drizzle, Prisma, Knex, the SQLite drivers, mysql2) gets a TxHooks instance, which buffers callbacks for one transaction. The provider's transaction context carries it as a txHooks field next to the transaction handle, its withTransaction creates it with withTxHooks, and its onTransactionCommit and onTransactionRollback register callbacks on it:
provider.ts
export type PostgresJsContext = { txSql: postgres.TransactionSql; txHooks: TxHooks };
const stateProvider: PgStateProvider<PostgresJsContext> = {
withTransaction: async (fn) =>
withTxHooks(async (txHooks) => sql.begin(async (txSql) => fn({ txSql, txHooks }))),
onTransactionCommit: (txCtx, callback) => {
txCtx.txHooks.onCommit(callback);
},
onTransactionRollback: (txCtx, callback) => {
txCtx.txHooks.onRollback(callback);
},
// isTransaction, executeSql, classifyError
};txHooks is then part of that provider's transaction context, so a transaction you open yourself creates the hooks the same way and passes them with the rest of the context. Every snippet in these docs that opens a transaction with sql.begin, db.transaction or knex.transaction does this:
Pass a callback to withTxHooks. Flush and discard are managed automatically — no
manual cleanup needed.
TypeScript
await withTxHooks(async (txHooks) =>
sql.begin(async (txSql) => {
await client.createChain({ txSql, txHooks, typeName: "send-email", input });
}),
);Use createTxHooks directly when your database client uses explicit
BEGIN/COMMIT/ROLLBACK rather than a callback-style transaction.
Caution
You are responsible for calling flush() after a successful commit and discard() on error.
TypeScript
const { txHooks, flush, discard } = createTxHooks();
const poolClient = await pool.connect();
try {
await poolClient.query("BEGIN");
const result = await client.createChain({
poolClient,
txHooks,
typeName: "send-email",
input,
});
await poolClient.query("COMMIT");
await flush();
return result;
} catch (error) {
await poolClient.query("ROLLBACK").catch(() => {});
discard();
throw error;
} finally {
poolClient.release();
}A transaction opened through stateProvider.withTransaction already carries its hooks, so you spread its context as it is: stateProvider.withTransaction(async (txCtx) => client.createChain({ ...txCtx, typeName, input })).
How It Works
TxHooks knows nothing about Queuert itself. Queuert registers its notifications and observability events through the provider's onTransactionCommit and onTransactionRollback, and your code can register side effects the same way, through stateProvider.onTransactionCommit(txCtx, callback) with any provider, or on the txHooks in your context:
TypeScript
await withTxHooks(async (txHooks) =>
db.transaction(async (tx) => {
const invoice = await tx.invoices.insert(data);
txHooks.onCommit(() => metrics.increment("invoice.issued"));
txHooks.onRollback(() => uploads.release(invoice.pdfUploadId));
}),
);onCommit callbacks run after the outer callback completes successfully. They start in registration order and run concurrently; flush awaits every returned promise and rethrows the first error once all of them have run. If the callback throws, the commit callbacks are dropped and the onRollback callbacks run instead, newest first. Rollback callbacks must be synchronous, because they also run when a savepoint or a retryBoundary try rolls back.
One TxHooks instance serves one transaction: once it is flushed or discarded, registering another callback throws, so a call that reuses it fails instead of buffering side effects that never run.
The rest of this page is the TxHooks toolkit for a provider that carries the hooks in its context, and for code that opens transactions for such a provider. Whatever the provider, it must run commit callbacks only after COMMIT, follow savepoints, and drop the callbacks of a try its driver reruns; Errors and Commit Detection explains why.
Drivers that rerun the callback
Some drivers rerun the transaction callback after a transient error, such as MongoDB's session.withTransaction and Mongoose's connection.transaction, and so does a retry loop placed inside withTxHooks. Every try then shares one txHooks, so side effects buffered by a rolled-back try flush after the successful one. Wrap the callback in txHooks.retryBoundary, in the provider's withTransaction and wherever you open such a transaction yourself:
TypeScript
await withTxHooks(async (txHooks) =>
session.withTransaction(
txHooks.retryBoundary(async () => {
await orders.insertOne(order, { session });
await client.createChain({ session, txHooks, typeName: "send-receipt", input });
}),
),
);Each call after the first rolls back what the previous try registered, then runs the callback with the driver's arguments. A try can fail after the callback returned, for example a serialization failure at COMMIT, so the rollback happens when the driver calls the callback again rather than when it throws. Callbacks registered before the first try are kept. The failed try's commit callbacks are dropped and its rollback callbacks run. A retry loop placed outside withTxHooks, retry(() => withTxHooks(...)), needs no wrapper, because every try gets its own instance.
A resolved transaction counts as committed
withTxHooks and retryBoundary treat a callback that resolves as committed. A driver whose transaction resolves after a rollback makes the hooks flush for writes that never committed. Knex does this by default: a bare trx.rollback() inside knex.transaction(cb) resolves with undefined. Pass { doNotRejectOnRollback: false } to every knex.transaction that uses txHooks, the provider's withTransaction and your own transactions, including nested trx.transaction(cb) savepoints, so a bare trx.rollback() rejects:
TypeScript
await withTxHooks(async (txHooks) =>
knex.transaction(
async (trx) => {
await client.createChain({ trx, txHooks, typeName: "send-email", input });
},
{ doNotRejectOnRollback: false },
),
);Rolling back by throwing, or with trx.rollback(error) and an Error, rejects at either setting.
Savepoints
TxHooks supports savepoints for partial rollback of buffered side effects. This is useful when a sub-operation within a transaction may fail without invalidating the entire transaction. Pair each database savepoint with a TxHooks savepoint and pass the savepoint's txHooks in the context of the calls made inside it, so rolling back the database savepoint also drops what those calls buffered. A provider with transaction events does this pairing itself: the MikroORM example opens a TxHooks savepoint for every nested em.transactional.
withSavepoint runs a function and automatically rolls back its callbacks on error:
TypeScript
await txHooks.withSavepoint(async (txHooks) =>
txSql.savepoint(async (txSql) =>
client.createChain({ txSql, txHooks, typeName: "send-email", input }),
),
);createSavepoint returns a handle for fine-grained control:
TypeScript
const sp = txHooks.createSavepoint();
await txSql`savepoint send_email`;
try {
await client.createChain({ txSql, txHooks: sp.txHooks, typeName: "send-email", input });
await txSql`release savepoint send_email`;
sp.release();
} catch {
await txSql`rollback to savepoint send_email`;
sp.rollback();
}Every callback belongs to the innermost savepoint open when it was registered. Rolling a savepoint back drops the commit callbacks registered since it was created and runs the rollback callbacks registered since, newest first; a rollback callback that throws does not stop the others. Releasing a savepoint hands its callbacks to the enclosing scope. As in the database, rolling back a savepoint also releases every savepoint created after it, so rolling one of those back afterwards does nothing.
withTxHooks manages this lifecycle automatically: it creates the TxHooks instance, passes it to the callback, and calls flush on success or discard on error. createTxHooks exposes the same lifecycle for manual control — the caller is responsible for calling flush() after commit and discard() on error.
Synchronous transactions
Over a synchronous provider, the client runs inside the driver's own synchronous transaction, such as better-sqlite3's db.transaction(() => …)(), so a synchronous provider without transaction events of its own carries TxHooks in its context, from withTxHooks or createTxHooks. The hooks follow the transaction they wrap: when the callback passed to withTxHooks returns a plain value, withTxHooks returns that value and runs the commit callbacks synchronously, and flush from createTxHooks returns a promise only when a commit callback returned one.
TypeScript
const chain = withTxHooks((txHooks) =>
db.transaction(() => client.createChain({ db, txHooks, typeName: "send-email", input }))(),
);In a synchronous transaction, commit callbacks must be synchronous too: a commit callback that returns a promise makes the flush throw after every callback has run.