What are the two forms of prisma $transaction, and which one fits multi-service logic?
Prisma offers two ways to group writes atomically, and they differ in what your code can do between statements.
The array (sequential) form takes a list of already-built Prisma queries and runs them in order inside one database transaction. Every operation must be fully defined before the transaction starts, so one query cannot read a result and decide what the next one does. This form suits independent writes, such as creating an audit row alongside an update or deleting several related records together.
The interactive form takes an async callback and passes it a transaction client, conventionally named tx. Every query issued through tx runs on the same connection inside the same transaction. Your code can read, branch, validate, and write, and throwing an error rolls everything back. This is what read-then-write logic needs, for example checking a balance before debiting it.
That flexibility has a cost. The callback holds a pooled connection for its entire duration, plus any row locks the database has taken, and it is subject to a configurable timeout. Slow code inside the callback starves the pool and blocks other writers.
| Aspect | Array form | Interactive form |
|---|---|---|
| Input | List of prepared queries | Async callback receiving tx |
| Read-then-write logic | No | Yes |
| Connection held | For the batch only | For the whole callback |
| Spans multiple services | No | Yes, if tx reaches them |
If your use case calls an OrderService, an InventoryService, and a LedgerService that each issue their own queries, only the interactive form can make them atomic. Each service needs a way to obtain tx instead of the global client, and providing that is the subject of the rest of this article.
import { PrismaClient, Prisma } from '@prisma/client';
const prisma = new PrismaClient();
// Array form: queries are fully built before the transaction starts.
// Good for independent writes; no query can depend on another's result.
await prisma.$transaction([
prisma.order.update({ where: { id: 'ord_123' }, data: { status: 'CANCELLED' } }),
prisma.auditLog.create({ data: { action: 'ORDER_CANCELLED', orderId: 'ord_123' } }),
]);
// A helper that accepts the transaction client, so it can join any
// transaction its caller started instead of using the global client.
async function debit(tx: Prisma.TransactionClient, accountId: string, amount: number) {
const account = await tx.account.findUniqueOrThrow({ where: { id: accountId } });
if (account.balance < amount) {
// Throwing inside the callback rolls back every write made through tx.
throw new Error('Insufficient funds');
}
await tx.account.update({
where: { id: accountId },
data: { balance: { decrement: amount } },
});
}
// Interactive form: read, branch, then write on one connection.
// The connection (and any row locks) is held until the callback returns,
// so keep slow work such as HTTP calls outside it.
await prisma.$transaction(
async (tx) => {
await debit(tx, 'acc_42', 100);
await tx.order.create({ data: { accountId: 'acc_42', total: 100 } });
},
{ maxWait: 2000, timeout: 5000 }, // ms to wait for a connection / max callback runtime
);
Contrasts the array form for independent writes with the interactive form, where a tx client passed into a helper enables read-then-write logic inside one transaction.
Why do writes escape the transaction when each NestJS service injects PrismaService?
Take a typical use case: OrderService.placeOrder opens an interactive prisma.$transaction, receives tx, and creates an order row through it. It then calls InventoryService.reserveStock, which was written months earlier and uses its own injected PrismaService. Finally it calls PaymentService.charge, which throws because the card is declined.
Here is what happens at the database level:
$transactiontakes one connection from the pool, issuesBEGIN, and bindstxto that connection.- The order insert runs on that connection, inside the open transaction.
InventoryServicecallsthis.prisma.stockReservation.create. The singleton client knows nothing about the callback it is running inside, so it takes a different pooled connection and runs the insert in autocommit mode. The reservation is durable as soon as the statement returns.- The payment error propagates out of the callback. Prisma issues
ROLLBACKon the first connection, and the order disappears. - The reservation stays. Stock is now held for an order that does not exist.
Nothing fails loudly. The types match, because tx and PrismaService expose the same model delegates. No warning is logged, and the use case returns the error you expected.
Local testing tends to hide this. Most tests exercise the happy path, where every write commits anyway. Unit tests usually mock PrismaService, so the difference between the two clients never reaches a real database. Concurrency on a laptop is low, so you rarely see the one symptom that does surface: the outside write blocking on a row lock held by the open transaction until the interactive transaction times out.
import { Injectable } from '@nestjs/common';
import { PrismaService } from './prisma.service';
import { PaymentService } from './payment.service';
@Injectable()
export class InventoryService {
constructor(private readonly prisma: PrismaService) {}
// Uses the singleton client. It takes its own pooled connection and autocommits.
async reserveStock(orderId: string, sku: string, qty: number) {
return this.prisma.stockReservation.create({ data: { orderId, sku, qty } });
}
}
@Injectable()
export class OrderService {
constructor(
private readonly prisma: PrismaService,
private readonly inventory: InventoryService,
private readonly payments: PaymentService,
) {}
async placeOrder(customerId: string, sku: string, qty: number) {
return this.prisma.$transaction(async (tx) => {
// Runs on the transaction's connection, after BEGIN.
const order = await tx.order.create({ data: { customerId, sku, qty } });
// BUG: tx is not passed down. This insert commits immediately on another connection.
await this.inventory.reserveStock(order.id, sku, qty);
// A declined card throws here. ROLLBACK undoes the order but not the reservation.
await this.payments.charge(customerId, order.id);
return order;
});
}
}
OrderService writes the order through tx, but InventoryService writes through the injected singleton PrismaService, so its reservation survives when the payment error rolls back the transaction.
How does explicit tx passing work, and when is it good enough?
The most direct fix is to stop relying on injection for the client that does the writing. The orchestrating method opens the transaction with this.prisma.$transaction(async (tx) => { ... }) and passes tx into every service call inside the callback. Each participating method takes an optional last parameter typed as Prisma.TransactionClient and resolves its client with tx ?? this.prisma. Called standalone, the method uses the root client. Called from the orchestrator, it joins the open transaction.
This approach is correct for a simple reason: the data flow is explicit. A reviewer can trace tx from the $transaction callback to every query and confirm that all writes share one connection. Prisma.TransactionClient also omits $transaction and the connection-lifecycle methods, so the type system stops a participant from opening a nested transaction or disconnecting the client by mistake.
The cost is that persistence concerns end up in method signatures. A domain service that only computes a price still has to accept and forward tx if a method it calls writes to the database. Every new call path is another chance to forget the argument, and because the parameter is optional, forgetting it compiles cleanly. The write then silently runs on the root client, outside the transaction, which is the same bug described in the previous section.
For a small codebase, or a team with only a handful of multi-service write paths, that cost is often acceptable. Explicit passing requires no setup and has no hidden context that can be lost. It is also easy to replace with a more abstract approach later if the number of call sites grows.
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from './prisma.service';
@Injectable()
export class InventoryService {
constructor(private readonly prisma: PrismaService) {}
// Optional tx: standalone calls use the root client, orchestrated calls join the transaction.
async reserve(productId: string, qty: number, tx?: Prisma.TransactionClient) {
const db = tx ?? this.prisma;
return db.product.update({
where: { id: productId },
data: { stock: { decrement: qty } },
});
}
}
@Injectable()
export class OrderService {
constructor(
private readonly prisma: PrismaService,
private readonly inventory: InventoryService,
) {}
async placeOrder(userId: string, productId: string, qty: number) {
// One interactive transaction; every write below must receive tx explicitly.
return this.prisma.$transaction(async (tx) => {
await this.inventory.reserve(productId, qty, tx);
return tx.order.create({ data: { userId, productId, qty } });
// Forgetting tx, e.g. this.inventory.reserve(productId, qty), still compiles
// but the update then runs on the root client, outside the transaction.
});
}
}
An orchestrating service opens a Prisma interactive transaction and passes tx, typed as Prisma.TransactionClient, to a participant that falls back to the root client when tx is omitted.
How does an AsyncLocalStorage unit of work propagate the transaction client?
Continuation-local storage gives each logical request its own context that follows the request through every await, promise callback, and timer it schedules. You do not pass that context as a parameter. Node exposes this as AsyncLocalStorage in node:async_hooks. Calling run(store, fn) makes store visible to getStore() everywhere inside fn's async chain. Libraries in the nestjs cls family wrap this primitive and integrate it with Nest's request lifecycle.
For transactions, the use-case service opens the interactive transaction and calls run() with the tx client as the store. Repositories never receive tx directly. They ask the store for an active client and fall back to the base PrismaService when none exists. The same repository therefore works inside and outside a transaction, and no service signature changes.
OrderUseCase.place()
└─ prisma.$transaction(async (tx) =>
als.run({ tx }, async () => { ── async context: { tx }
ordersRepo.create() → getStore()?.tx ?? prisma → tx
inventoryRepo.reserve() → getStore()?.tx ?? prisma → tx
ledgerRepo.debit() → getStore()?.tx ?? prisma → tx
}))
ReportsService.list() (no run) → getStore() undefined → prisma
The weakness is that context only follows the async chain. Code that runs from a callback registered somewhere else sees that other context, or none at all. Common cases are event emitter listeners invoked from an unrelated emit, timers or queues set up at startup, and libraries that pool callbacks and invoke them later. In those cases getStore() returns undefined, and the repository falls back to PrismaService. The write commits outside the transaction, with no error, and it will not roll back.
+----------------------------------------------------------------+
| OrderUseCase.place() |
| prisma.$transaction(async (tx) => als.run({ tx }, fn)) |
+-------------------------------+--------------------------------+
v
+================================================================+
| AsyncLocalStorage context: { tx } (follows awaits/promises) |
| OrdersService InventoryService LedgerService |
| +---------------+ +---------------+ +---------------+ |
| | ordersRepo | | inventoryRepo | | ledgerRepo | |
| | .create() | | .reserve() | | .debit() | |
| +-------+-------+ +-------+-------+ +-------+-------+ |
| +-------------------+-------------------+ |
| v |
| getStore()?.tx ?? prisma ==> tx |
+===============================+================================+
v
[ tx: every write commits or rolls back together ]
+----------------------------+ +----------------------------+
| EventEmitter listener | | ReportsService.list() |
| timer set up at startup | | called with no als.run() |
| pooled library callback | | |
+-------------+--------------+ +-------------+--------------+
| getStore() -> undefined |
+-----------------+-----------------+
v
[ PrismaService: commits on its own, no error, no rollback ]
The use-case service opens the transaction and stores tx in AsyncLocalStorage, so repositories in every service on that async chain resolve the same tx, while callbacks registered elsewhere and calls made without run() find no store and silently write through the base PrismaService.
Implementing a transaction runner provider in NestJS
Step 1: run(fn)
The runner is an injectable provider wrapping PrismaService. Its run(fn) method calls prisma.$transaction(async (tx) => ...) and, inside that callback, calls als.run({ tx }, fn). Everything fn awaits sees tx in the store. If fn throws, the error propagates out of the callback and Prisma rolls back. If fn resolves, Prisma commits.
Step 2: Repository base
A base class exposes a client getter that returns als.getStore()?.tx ?? this.prisma. Repositories call this.client.order.create(...) and never know whether they are inside a transaction. This removes tx from every service and repository signature, so adding a write to an existing flow does not require threading a parameter through the call chain.
Step 3: Join semantics
The transaction client cannot open its own $transaction, so run() first checks the store. If a tx is already present, run() calls fn directly and joins the outer transaction. This does not create savepoints and gives no partial rollback. If an inner call throws and the caller catches and swallows the error, the outer transaction continues in an unknown state. It may commit work that was meant to be undone. Rethrow, or treat the whole unit as failed.
Options
Set the following options explicitly instead of relying on defaults:
maxWaitlimits how long the call waits to acquire a connection.timeoutlimits how long the transaction may stay open before Prisma aborts it.isolationLevelsets the database isolation level for the transaction.
To pick values, size timeout to the slowest expected unit of work plus a margin. Keep maxWait short so callers fail fast under pool pressure.
Serializable can abort a transaction with a serialization failure. The correct response is to retry the whole run(), not a single statement. Retrying the whole unit is only safe if it is idempotent.
Decorator and placement
A @Transactional() method decorator can wrap a method body in run(). Apply it to application or use-case services, where the business boundary is defined. Do not apply it to repositories.
How do you keep side effects out of an interactive transaction?
Anything that talks to the outside world (an HTTP call to a payment provider, a message published to a queue, an email sent) does not belong inside the $transaction callback, for two reasons.
The first is resource cost. The interactive transaction holds a pooled connection, and any row locks it has taken, for the whole callback. A slow third-party API therefore keeps locks held and a connection out of the pool. Under load this exhausts the pool or trips the transaction timeout.
The second is correctness. A rollback undoes your SQL, but it cannot recall an email or remove a message from a queue. If the callback publishes order.created and a later write fails, consumers act on an order that does not exist.
After-commit hooks
The async context that already holds the transaction client can also hold a list of callbacks. Services call something like afterCommit(fn) instead of performing the side effect directly. The runner awaits $transaction. If it resolves, the runner flushes the list in order. If it rejects, the runner discards the list. Nested run() calls should append to the outermost list so that nothing fires early.
This is best effort. If the process crashes between the commit and the flush, the hooks are lost.
Outbox table
When losing an event is unacceptable, insert an outbox row inside the same transaction. The row commits or rolls back together with the business data. A separate relay reads unsent rows and publishes them. Delivery is at-least-once, so consumers must be idempotent.
A Prisma transaction covers only one database. Work that spans other services or datastores needs an outbox, a saga, or explicit compensation steps. Widening the transaction cannot cover those systems.
How do you test that rollback actually works across services?
Run these tests against a real database, such as a disposable Postgres container or a dedicated test schema. A mocked PrismaService has no transaction semantics, so it cannot show that a write was undone. Truncate the affected tables between tests rather than wrapping each test in its own transaction. An outer test transaction would hide the rollback behavior you are trying to verify.
Rollback across services
Build the testing module with the real upstream and downstream services and the real transaction runner. Override only the downstream service so it throws after the upstream service has written its row. Call the upstream method through the runner, assert that the promise rejects, and then query the base client for the upstream row using a unique identifier generated for this test. The row must be absent. Asserting that the error was thrown is not sufficient. The test has to show that the earlier write is gone.
Outside a transaction
Call the same service method with no runner. Assert that the client resolved from the context is the base PrismaService instance, and that the write is visible immediately from a separate query.
Regression checks for setup mistakes
The failure that does the most damage is silent: if the context is never populated, the accessor falls back to the base client and every write commits on its own. Catch this in two ways:
- Inside the runner, assert that the resolved client is not the base instance.
- Add one end-to-end test that goes through an HTTP route. A missing context middleware only shows up on the request path. Tests that call services directly bypass that path.
To catch a service that injects PrismaService directly, keep the rollback test pointed at every service that writes. Any write that survives the rollback identifies the service that bypassed the context.
When should you avoid this pattern, and what are the alternatives?
Implicit propagation makes code easier to write but harder to review. A reviewer reading orderService.create() cannot tell from its signature whether it runs inside a transaction, because that depends on the caller's context, which may not appear in the diff. A call that escapes the async context, such as an event emitter handler or a deferred timer, falls back to the base client without raising an error.
An interactive transaction holds one connection for the whole callback. As an illustrative estimate, assume a pool of 10 connections and callbacks that wait 2 seconds on an external API. That path then tops out at about 5 transactions per second before requests start queueing and hitting the transaction timeout. A global transactional interceptor makes this worse because it extends the transaction to the whole request. Row locks taken by the first write are then held through unrelated reads, validation and response serialisation.
The abstraction also carries fixed costs: CLS wiring, a runner provider, test harnesses and a convention that every developer has to follow.
| Approach | Development cost | Reviewability | Main failure mode | Best fit |
|---|---|---|---|---|
Explicit tx passing |
Low | High: the dependency is visible in signatures | Signature churn across call chains | Two or three services, shallow call depth |
| AsyncLocalStorage unit of work | Medium | Low: the transaction is implicit | Context loss, long-held connections | Deep service graphs with many writers |
Array-form $transaction |
Lowest | High | Cannot branch on intermediate results | Independent writes known upfront |
| Outbox / saga | High | Medium | Eventual consistency, compensation bugs | Writes spanning databases or external systems |
Use the unit of work only when explicit passing has become painful. Use outbox or saga when the work does not fit inside one database.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs prisma transactions, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.