Database transactions in Strapi

Strapi's strapi.db.transaction groups several database operations so they commit or roll back together. This page explains when teams need it, how it is configured, and what to confirm before relying on it in production.

On this page

When Strapi database transactions keep multi-step writes consistent

If your custom import, sync or integration writes to several content types or tables, a failure halfway through can leave half the records saved and half missing. Strapi database transactions, opened with strapi.db.transaction, make those writes atomic: the statements inside the callback either all commit or all roll back. Use this when a single business operation spans more than one write, such as creating a parent entry with its related entries and a sync log row, and a partial result would be harder to repair than a clean retry.

A transaction wraps the database operations you run inside its callback, using the same database connection. It does not wrap external calls such as HTTP requests to a partner system, file uploads to object storage or message queue publishes, so a rollback will not undo them. Plan for that boundary by ordering external side effects after the commit or by making them idempotent. The feature is documented by Strapi as experimental, so confirm its current status and behavior against the version you run before relying on it in production, and test rollback paths on a staging copy of your database.

In Strapi 5, most content writes go through the Document Service API, which is the layer your import code should normally call. Confirm with your team which calls will run inside the transaction and verify, in a test, that the Document Service operations you use behave as expected when the callback throws. Record the Strapi and database versions you tested with, because the transaction behavior is the part of the workflow most likely to change between releases.

Where Strapi transactions matter for imports and integrations

Most Strapi writes touch one entry, but imports, webhooks, sync jobs and migrations often write several related records in one logical change. Each card below describes one such pattern, the partial-write failure a transaction prevents, and the lock and batch-size trade-off to settle before the job runs in production.

Bulk imports across related types

A spreadsheet or feed import often creates a parent article, then its components, categories and relations in separate calls. If the job fails halfway, editors see articles with missing sections or broken category links. Wrapping each record's full set of writes in one transaction means a failure rolls back that record cleanly. The trade-off is lock time: a large batch held in one transaction keeps locks open longer and can slow editors, so test with realistic file sizes and choose a batch size that finishes well within your database's lock timeout.

Strapi migration docs

Webhook updates to parents and components

An inbound webhook from a commerce or CRM system may update a product entry and rewrite its repeatable components in one request. If the handler writes the parent and then fails on a component, the product shows a price with stale specifications. Grouping the parent and component writes inside one transaction keeps the entry consistent. Check that the handler is idempotent, because providers retry deliveries, and keep the transaction short so slow external calls happen outside it.

ERP and CRM sync jobs

A scheduled sync that pulls customers or price lists from an ERP or CRM usually runs as many small writes across types. A crash between the order header and its line items leaves orphaned records that the next run may duplicate. Use transactions around each source record, store the source system's identifier on every entry so reruns can match and update instead of insert, and record failed records for review. Confirm how the source API paginates, since a transaction cannot span API calls.

Migration scripts that rewrite relations

A migration that moves a relation from one type to another, or splits a field into a new content type, must delete old links and create new ones together. A partial run can leave some content pointing at deleted targets, which is hard to detect later. Run these scripts against a restored copy of production first, take a database backup before the run, and compare record counts afterward. Because Strapi 5 migrations and downgrades carry their own risks, treat transactions as one safeguard within a documented rollback plan.

Choosing between transactions, batching and idempotent retries

This table compares three ways to keep multi-step Strapi writes correct: an atomic transaction, per-record writes with compensating logic, and idempotent re-runs keyed on external IDs. Read each row against your own import or integration, because the database engine and the size of each unit of work change which option is safe and affordable.

ApproachWhat it protects againstCost in complexity or throughputWhen it fits
strapi.db.transaction (atomic group)Partial writes when a group of related inserts, updates or deletes must all succeed or all roll backHolds database locks for the whole group, so large groups slow concurrent writes; the API is marked experimental in Strapi 5 docsSmall to medium related writes, such as a parent entry with its components, where a half-finished state would be visible
Per-record writes with compensating logicFailures in one record without rolling back the whole batch, by running a defined undo step for work already doneUndo logic must be written and tested for each step; errors during compensation need their own handling and loggingLong imports or calls to external systems that cannot share a database transaction
Idempotent re-runs keyed on external IDsDuplicate records when a job is retried after a timeout, crash or restartNeeds a stored mapping from external ID to Strapi document ID and a lookup before each write; the mapping table must be maintainedRecurring syncs and imports where the source system can be read again and rerun safely
Large unit of work (thousands of records)Atomicity is hard to keep without long transactions that increase lock and rollback costUsually favors batching with per-batch checkpoints plus idempotent keys over one transactionBulk migrations where the reader must be able to resume from the last checkpoint
Engine and isolation behaviorResults differ by database engine, such as PostgreSQL, MySQL, MariaDB and SQLite, in locking and concurrent write handlingRequires testing against the engine you run in production, not only SQLite in developmentConfirm the supported engine versions in the Strapi installation docs and test rollback behavior on your target
Calls to external services inside the writeA transaction cannot roll back a payment, email or third-party API call already sentRequires moving side effects after commit or adding compensation; confirm the ordering in your codeIntegrations that send messages or create records outside Strapi

Setting up a transactional write in a Strapi 5 project

This sequence takes a multi-step write from a plain service function to a tested, atomic operation in Strapi 5. The output is a wrapped write path that either commits every change or leaves no partial rows behind, verified by a deliberate failure in a non-production environment.

  1. Confirm the Strapi 5 version and database

    Start by recording the exact Strapi 5 version your project runs and the database engine behind it. Strapi 5 supports PostgreSQL 14 or later, MySQL 8.0 or later, MariaDB 10.3 or later and SQLite 3, and it does not support MongoDB or other NoSQL databases. Check that your Node.js version is an Active or Maintenance LTS release, since Strapi 5 runs only on those. The engineer responsible for the project confirms these values in writing in the ticket. Done means the version, database and Node.js release are recorded and match the supported list.

  2. Define the unit of work

    Decide which writes must succeed or fail together, such as creating a parent entry, its related entries and an audit record during an import. List each write, the content types it touches and the order it runs in. Also decide what the caller receives when the unit fails. Ask the business owner to sign off on which partial states are unacceptable. Done means you have a written list of the operations inside one transaction and a clear rule for what happens to each on failure.

  3. Wrap the writes in strapi.db.transaction

    Move the listed operations into a single call to strapi.db.transaction in your service layer, not in the controller, so every caller uses the same path. Pass the transaction callback every write in the unit, and avoid calling external services or sending emails inside it, because those cannot be rolled back with the database. Because transactions are experimental in Strapi 5, pin the version and review the release notes before upgrading. Done means all writes in the unit run inside one transaction block and no write in that block bypasses it.

  4. Add error handling and logging

    Catch errors thrown inside the transaction callback, log the operation name, the input identifiers and the error message without personal data, and rethrow or return a controlled error to the caller. Make sure a failed unit does not return a success response. Keep log entries consistent so support staff can trace a failed import. Done means a failing write produces one clear log entry, returns an error to the caller and does not return a partial result.

  5. Force a failure in a non-production environment

    In a non-production environment seeded with representative data, add a temporary step after the first writes that throws an error, then run the operation. This test is your rollback check and should be run by someone other than the author where possible. Record the row counts for each affected table before and after the call. Done means the forced failure returns an error and the test records show the same counts as before the call.

  6. Confirm no partial rows remain

    After the induced error, query each table the unit touches and confirm that no parent entry, related entry or audit record was left behind, including draft and published versions where Strapi stores them separately. Compare the results with the before snapshot and check that identifiers used by the failed run do not appear. Done means every table matches its pre-run state, and the query results are saved with the test record.

  7. Remove the forced failure and run the success path

    Remove the temporary throw, run the same operation with valid input and confirm that all expected rows are written together. Check that the success response matches what the caller expects. Keep the rollback test in the automated suite so future changes to the unit are checked before deployment. Done means the success path writes every expected row, the rollback test passes in the suite and the results are documented for the release.

Security and operational risks of transactional writes

A transaction makes a multi-step write all-or-nothing, but it also holds database resources, repeats work on retry and runs with internal privileges. The cards below cover the failure modes that matter most when Strapi writes are wrapped in strapi.db.transaction, and the operational checks that keep an import or integration recoverable.

Long transactions holding locks

A transaction keeps its row locks until it commits or rolls back, so a batch that reads, transforms and writes thousands of entries in one transaction can block editors and other writers for as long as it runs. Keep each transaction to a bounded unit of work, such as one parent entry and its components, and measure lock wait times in a staging copy with production-sized data before scheduling an import.

External calls inside transactions

A database rollback cannot undo an email, a webhook, a payment call or a file written to object storage. If these run inside the transaction callback, a later failure leaves the side effect in place while the content disappears. Perform external calls after commit, or record them in an outbox table that a separate job sends once the write is durable.

Retries that duplicate data

When a job times out or a network call fails, a retry can re-run a transaction that partly or fully succeeded, creating duplicate entries or double-counted relations. Give each imported record a stable external identifier, use it as a unique key, and make the write an upsert so a rerun converges on the same state. Confirm how your database driver reports an ambiguous commit before trusting a retry.

Personal data in failure logs

Error handlers often log the full payload that failed to save, which can include names, emails, identifiers or health and financial details. Log the record's external identifier, the step name and the error code instead, and redact fields that the content type marks as personal. Check your log retention and access rules, since a failed import can write personal data into systems that were never meant to hold it.

Permission bypass on internal writes

Calls to strapi.db.query or the Document Service run without the route policies, sanitizers and role checks that apply to API requests. A script or integration that uses these directly can create or publish content that the requesting user could never write. Route internal writes through a service that enforces the same ownership and role rules, and test that a low-privilege token cannot reach the same outcome through a custom path.

Strapi v5 migration docs

Pool sizing, rollback monitoring and backups

Each open transaction holds a database connection, so an import running alongside API traffic can exhaust the pool and stall requests. Set the pool size with your database's connection limits in mind, alert on rollback counts and lock waits, and take and test a full database backup before any large import, because a rollback only protects the writes that were inside the transaction. Confirm your supported database versions against the installation requirements first.

Strapi installation requirements

What the experimental label means for production planning

An experimental label means the API surface can change before Strapi declares it stable, so depending on it is a design decision with a cost. Engineering leads should decide whether transactions sit in a critical user-facing write path or in a bounded import or integration job that can be safely rerun.

  • Minor releases can change behavior: Strapi 5 minor releases have shipped roughly weekly, so a helper can change its signature, error handling or commit semantics in a release that looks routine. Pin the exact Strapi version in your lockfile and promote upgrades through staging.
  • Keep calls in one module: Place every transaction call inside a single service so that an API change touches one file instead of every controller and script.
  • Test failure midway through a write: Write tests that force an error after the first of several writes and assert that no partial rows remain. A passing happy-path test does not prove atomicity.
  • Pair transactions with idempotency: Use transactions with keys that let an import or sync be retried safely, and avoid building user-facing flows that assume the API will never change.
  • Document the dependency: Record the pinned version, the reason for the dependency and the exit plan if the API is changed or removed.

Confirm the current status and any known issues for your target version in the Strapi release notes before you approve the dependency.

Limits to confirm in your environment before relying on transactions

Transactions only protect a multi-step write when the database engine, the Strapi version and your own hooks and middlewares all behave the way the code assumes. The cards below cover the checks to run in your environment before an import or integration depends on atomic writes.

Database engine behavior

Strapi 5 supports PostgreSQL 14 or later, MySQL 8.0 or later, MariaDB 10.3 or later and SQLite 3, and does not support MongoDB or other NoSQL databases. Isolation behavior, locking and rollback handling differ between these engines, so test your rollback path on the exact engine and version you run in production. Do not assume a test run on SQLite reflects PostgreSQL or MySQL behavior.

Installation requirements

Lifecycle hooks and middlewares

Lifecycle hooks and Document Service middlewares run inside your write logic, and some of them may perform their own reads or writes or call external services. Confirm which work happens inside the transaction boundary and which runs after commit. A hook that sends an email or calls an external API cannot be rolled back with the database, so plan compensating actions for those side effects.

Import volume and performance

Large imports hold locks and grow transaction logs for as long as the transaction stays open. Measure the throughput and lock duration of your real import file on a staging copy of production-sized data, and choose a batch size that keeps each transaction short enough for your database. Ask your team to record these results before setting a schedule for the production run.

Nested transaction handling

When one service calls another that also opens a transaction, confirm whether the inner call joins the outer transaction or creates its own. If it creates its own, a failure in the outer step may leave the inner write committed. Write a test that forces a failure at each level and checks the database state afterward.

Draft and publish states

In Strapi 5, a document can exist as a draft and a published version, and a single write may touch both. Confirm that a rollback restores both versions consistently and that your publish step does not run before the draft write commits. Test with content types that have draft and publish enabled, and with those that do not.

API stability in your version

The strapi.db.transaction API is marked experimental in the Strapi docs, so its signature and behavior may change between releases. Pin the Strapi version you test against, read the release notes for each upgrade, and re-run your transaction tests after every minor update. Strapi 5 minor releases ship frequently, so schedule regression runs as part of your upgrade routine.

Strapi releases

Questions teams ask about Strapi transactions

Can our in-house team build Strapi transactions ourselves?

Yes, if your team already writes Strapi server code and knows the database engine it runs on. The core work is wrapping related writes in one transaction, rolling back on any failure, and holding side effects such as emails or webhooks until the commit succeeds. Teams without Strapi backend experience often spend most of their time on the Document Service and test setup before they reach the transaction call itself. Check which Strapi version you run and read its current transaction documentation first, because the API is marked experimental and its behavior may change between releases. A partner adds the most value when the import is large, the integrations are many, or the team lacks spare capacity to test failure paths.

What drives the effort of a transaction project in Strapi?

Effort rises with the number of places where a single business action touches several linked records. Four factors matter most:

  • The number of related content types written in one unit of work, including components, dynamic zones and relations
  • The import volume and batch size, which decide how long a transaction stays open and how a failure is recovered
  • The number of external integrations and how each one fails, since a timeout after a partial write needs its own compensating step
  • Test coverage, especially rollback paths, concurrent writes and retries after a partial failure

A small set of endpoints with two or three linked types is a contained job. A nightly feed that writes thousands of records across many types and calls three external systems is a larger one. Ask any provider to break the estimate down by these four factors.

What does the partner need from our team to start?

The partner needs enough material to see every write path and every failure mode before building starts. Prepare the following before kickoff:

  • The content type schema export, including components, dynamic zones and relations
  • Sample request payloads and the expected responses for each custom endpoint or import file
  • A staging copy of the database with data close to production volume and shape
  • Named data owners who approve field mappings, decide how rejected records are handled and sign off on test results
  • Read and write access to the repository, the CI pipeline and a staging environment

Without data owners, the team often discovers late that a rule the business assumed was never written down.

Do Strapi transactions require an upgrade to Strapi 5?

Whether a transaction works depends on the Strapi version you run, so confirm that against the documentation for that version before you design around it. If you are still on Strapi v4, moving to Strapi 5 is a separate project with its own breaking changes, a codemod-based upgrade tool and data migration scripts. Strapi v4 reached end of life on April 30, 2026, and its final release, 4.26.2, was published on June 9, 2026, so it no longer receives updates. The migration documentation says to back up the database first, because downgrading is not supported. Plan the transaction work after the version question is settled, not during the upgrade.

How should we plan around the experimental status of transactions?

Treat the transaction API as a dependency that can change, and build the plan around that risk. Pin the Strapi version in your lockfile and upgrade on a schedule. Strapi 5 minor releases have shipped roughly weekly, so an unplanned update can arrive at any time. Keep a list of every endpoint and import that uses transactions, add integration tests that run against each candidate upgrade, and read the release notes before each minor version goes live. Also design a compensating action for each external call, so a failed step can be reversed even if the database layer changes its behavior.

Does the database engine change how Strapi transactions behave?

Yes, the engine affects locking, isolation and how concurrent writes resolve, so test on the engine you will run in production. Strapi 5 supports PostgreSQL 14 or later, MySQL 8.0 or later, MariaDB 10.3 or later and SQLite 3. SQLite is convenient for automated tests, but it does not behave like a multi-user server database under concurrent load. Run your failure tests against the production engine and version, and confirm the isolation and locking behavior in the vendor documentation for that engine. Installation requirements are listed in the Strapi CLI installation docs.

What should a fixed-scope quote for transaction work include?

A fixed-scope quote should list the work precisely enough that either side could check whether it is complete. Ask the provider to state the following in writing:

  • Each write flow, endpoint and import file included, with the records each one touches
  • The integrations in scope and the failure cases tested for each
  • The test definitions, the environments used and the retest after fixes
  • Which items are one-time work and which recur, such as upgrade testing or a support retainer
  • The assumptions about data quality and the process for changes requested later

DeployOpen works this way: most engagements are fixed-scope, and the scope, deliverables and timeline are agreed in writing before work starts. Compare any quote against that list rather than against the total alone.

How a multi-step import flows through a Strapi transaction

The import starts with an export from the source system, which a job reads and checks before any write happens. Validated records then go into a single strapi.db.transaction block where several Document Service writes run together. If every write succeeds, the transaction commits; if any write fails, it rolls back and the error is logged. The database is the trust boundary: nothing becomes visible to readers until the commit, so check that failed runs leave no partial content behind.

Import records pass validation, then commit or roll back as one unit inside the database.

How DeployOpen scopes and delivers transactional Strapi work

DeployOpen starts transactional Strapi work by drawing the unit of work on paper before any code changes. For each import or integration, the team lists every write that must succeed together, such as an entry created in one content type, its components and relations, a linked media record, and any audit or status update in a separate system. It then marks which steps Strapi can cover inside one strapi.db.transaction call, which steps call external services that cannot be rolled back, and where the process should stop and resume instead of retrying blindly. This map becomes the basis for the written scope, so the client sees the boundaries, the failure cases and the work to be delivered before engagement starts. Engagements are fixed-scope, with deliverables and timelines agreed in writing before work begins, and the client should expect the same written detail from any partner.

Inside the client's own infrastructure, the build phase covers the transaction wrapper, the rollback paths and the tests that prove them. Because strapi.db.transaction is experimental, the team checks the Strapi version the client runs and the database engine it uses (PostgreSQL, MySQL, MariaDB or SQLite, as listed in the Strapi installation requirements), then tests rollback against that same engine rather than assuming parity. Tests cover forced failures at each step, duplicate runs, partial external calls and concurrent writes. Staging runs use a copy of the production database, and the client's change process approves each release. Verification results and open risks are written down so the client's team can judge them.

Handover includes runbooks written for the people who will operate the import: how to start a run, read its logs, identify the last committed step, retry safely, and roll back when a failure is not automatic. Runbooks also name the database backup point taken before each run, since Strapi documents that downgrades are not supported and the database should be backed up first. Ongoing support, upgrades when Strapi releases change transaction behavior, and continuous retesting can be contracted as a retainer after the initial delivery. Clients should confirm who owns each runbook step, how alerts reach their on-call team and what evidence they need for their own change records.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.