---
title: Transactions
label: Transactions
order: 30
keywords: database, transactions, sql, mongodb, postgres, documentation, Content Management System, cms, headless, typescript, node, react, nextjs
desc: How Payload uses database transactions with supported database adapters.
---

Database transactions allow your application to make a series of database changes in an all-or-nothing commit. Consider an HTTP request that creates a new **Order** and has an `afterChange` hook to update the stock count of related **Items**. If an error occurs when updating an **Item** and an HTTP error is returned to the user, you would not want the new **Order** to be persisted or any other items to be changed either. When transactions are enabled, Payload can roll back these related database changes together.

Payload uses transactions by default for data-changing operations with Postgres and with MongoDB when connected to a replica set, unless transactions are disabled in the adapter configuration. When a Payload operation starts a transaction, its database changes are committed on success or rolled back on failure. Nested operations share that transaction when you pass `req`.

When transactions are disabled or unavailable, Payload continues to operate, but related operations do not have an all-or-nothing guarantee. If a later operation fails, earlier database changes can persist.

<Banner type="info">
  **Note:**

MongoDB requires a connection to a replicaset in order to make use of transactions.

</Banner>

<Banner type="info">
  **Note:**

SQLite transactions are disabled by default (`transactionOptions: false`). Leave this option unset or set to `false`. Transactions with the SQLite adapter are not fully supported or recommended because enabling them can cause database locking issues. Do not enable them as a general setup step or to make nested hook operations atomic.

</Banner>

When transactions are enabled, a data-changing Payload operation begins a transaction and attaches its identifier to `req.transactionID`. Pass `req` to nested database operations in hooks so they share the active transaction. Passing `req` is also recommended when transactions are disabled because it preserves request context, but it does not enable transactions or provide rollback across operations. For example:

```ts
const afterChange: CollectionAfterChangeHook = async ({ req }) => {
  // Share the parent operation's transaction, if active.
  // Without a transaction, this write is not rolled back if the parent fails.
  await req.payload.create({
    req,
    collection: 'my-slug',
    overrideAccess: true,
    data: {
      some: 'data',
    },
  })
}
```

## Async Hooks with Transactions

Since Payload hooks can be async and be written to not await the result, it is possible to have an incorrect success response returned on a request that is rolled back. If you have a hook where you do not `await` the result, then you should **not** pass the `req.transactionID`.

```ts
const afterChange: CollectionAfterChangeHook = async ({ req }) => {
  // WARNING: an async call made with the same req, but NOT awaited,
  // may fail resulting in an OK response being returned with response data that is not committed
  const dangerouslyIgnoreAsync = req.payload.create({
    req,
    collection: 'my-slug',
    overrideAccess: true,
    data: {
      some: 'other data',
    },
  })

  // Should this call fail, it will not rollback other changes
  // because the req (and its transactionID) is not passed through
  const safelyIgnoredAsync = req.payload.create({
    collection: 'my-slug',
    overrideAccess: true,
    data: {
      some: 'other data',
    },
  })
}
```

## Direct Transaction Access

When writing your own scripts or custom endpoints, you may wish to have direct control over transactions. This is useful for interacting with your database outside of Payload's Local API.

Direct transaction control requires an adapter with transactions enabled. Keep SQLite transactions disabled; calling these methods does not enable them.

The following functions can be used for managing transactions:

- `payload.db.beginTransaction` - Starts a new transaction and returns its ID for use in other Payload Local API calls, or `null` when transactions are disabled.
- `payload.db.commitTransaction` - Takes the identifier for the transaction, finalizes any changes.
- `payload.db.rollbackTransaction` - Takes the identifier for the transaction, discards any changes.

Payload uses the `req` object to pass the transaction ID through to the database adapter. If you are not using the `req` object, you can make a new object to pass the transaction ID directly to database adapter methods and Local API calls.
Example:

```ts
import payload from 'payload'
import config from './payload.config'

const standalonePayloadScript = async () => {
  // initialize Payload
  await payload.init({ config })

  const transactionID = await payload.db.beginTransaction()

  if (transactionID == null) {
    throw new Error('This operation requires transactions to be enabled')
  }

  try {
    // Make an update using the Local API
    await payload.update({
      collection: 'posts',
      overrideAccess: true,
      data: {
        some: 'data',
      },
      where: {
        slug: { equals: 'my-slug' },
      },
      req: { transactionID },
    })

    /*
      You can make additional db changes or run other functions
      that need to be committed on an all or nothing basis
     */

    // Commit the transaction
    await payload.db.commitTransaction(transactionID)
  } catch (error) {
    // Rollback the transaction
    await payload.db.rollbackTransaction(transactionID)
    throw error
  }
}

standalonePayloadScript()
```

## Disabling Transactions

If you wish to disable transactions entirely, you can do so by passing `false` as the `transactionOptions` in your database adapter configuration. All the official Payload database adapters support this option. This is already the default for SQLite; you do not need to add it to your SQLite configuration.

In addition to allowing database transactions to be disabled at the adapter level. You can prevent Payload from using a transaction in direct calls to the Local API by adding `disableTransaction: true` to the args. For example:

```ts
await payload.update({
  collection: 'posts',
  overrideAccess: true,
  data: {
    some: 'data',
  },
  where: {
    slug: { equals: 'my-slug' },
  },
  disableTransaction: true,
})
```
