Skip to content

perf: make bulk delete O(1) database queries instead of O(N) - #17934

Merged
GermanJablo merged 5 commits into
mainfrom
germanjablo/bulk-delete-batching
Sep 2, 2026
Merged

GermanJablo merged 5 commits into
mainfrom
germanjablo/bulk-delete-batching

Conversation

@GermanJablo

@GermanJablo GermanJablo commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

payload.delete({ where }) loads the matching documents, then issues four writes per document: a lock cleanup, a version delete, a scheduled-job delete and a deleteOne. Query count grows linearly with N, which is what exhausts connection pools on large deletes, and turns one call into hundreds of requests on HTTP-backed adapters. The deleteOne also re-reads a row db.find() already loaded, for a result nobody uses (returning: false).

Change

Those writes are batched behind an id in [...] filter, so query count no longer depends on N. delete.ts becomes three phases: per-document pre-work (locks, beforeDelete, file cleanup), batched writes, per-document post-work (afterRead, afterDelete). Hooks and per-document error reporting still run per document; the result shape is unchanged.

deleteCollectionVersions and deleteScheduledPublishJobs gain an optional plural ids. Two batched lock helpers sit beside checkDocumentLockStatus, which is itself untouched, so update, deleteByID and globals are unaffected. bulkOperationsSingleTransaction (n: true) keeps the per-document path.

Measured

Query counts from the logger already used by test/database/postgres-logs.int.spec.ts:

documents before after
2 13 8
20 85 8
200 805 8

Error attribution

Unchanged for every framework-level failure: locks, beforeDelete, file cleanup, afterRead and afterDelete all still report the exact document. Access control never produced per-document errors here, since access.delete is merged into the query before db.find(), so a denied document never enters the batch.

Only the collection delete changes: it covers every id at once, so a failure is reported against the batch with a message saying so, instead of repeating a driver error against each id as though each failed independently.

Related: #13618, #15517

`payload.delete({ where })` loaded the matching documents and then issued
per-document writes: a lock cleanup and a delete for each document, plus
per-document version and scheduled-publish-job cleanup. The number of queries
therefore grew linearly with the number of matched documents, which is what
exhausts connection pools and saturates HTTP-backed adapters on large deletes.

Batch those writes so the query count no longer depends on how many documents
matched. `beforeDelete`, `afterRead` and `afterDelete` hooks, associated file
cleanup and per-document error reporting all still run per document.

Measured with the existing postgres query logger, deleting 2 / 20 / 200
documents went from 13 / 85 / 805 queries to 8 / 8 / 8.

The per-document path is preserved when `bulkOperationsSingleTransaction`
(`n: true`) is set, since that mode requires each document to be committed in
its own transaction. It now iterates sequentially rather than starting every
document's promise up front.
@github-actions

github-actions Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖

Meta File Out File Size (raw) Note
packages/next/meta_index.json esbuild/index.js 214.77 KB 🆕 Added
packages/payload/meta_index.json esbuild/index.js 1.41 MB 🆕 Added
packages/payload/meta_shared.json esbuild/exports/shared.js 213.69 KB 🆕 Added
packages/richtext-lexical/meta_client.json esbuild/exports/client_optimized/index.js 286.50 KB 🆕 Added
packages/ui/meta_client.json esbuild/exports/client_optimized/index.js 36.54 KB 🆕 Added
packages/ui/meta_shared.json esbuild/exports/shared_optimized/index.js 18.95 KB 🆕 Added
Largest paths These visualization shows top 20 largest paths in the bundle.

Meta file: packages/next/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ████████████████████████▊ }}}$ 99.0%, 210.74 KB
dist/adapters/router.js ${{\color{Goldenrod}{ }}}$ 0.3%, 718 B
dist/adapters/server.js ${{\color{Goldenrod}{ }}}$ 0.3%, 533 B
dist/adapters/layout.js ${{\color{Goldenrod}{ }}}$ 0.2%, 526 B
dist/adapters/views.js ${{\color{Goldenrod}{ }}}$ 0.2%, 409 B
dist/esbuildEntry.js ${{\color{Goldenrod}{ }}}$ 0.0%, 0 B

Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ████████████████▊ }}}$ 67.3%, 944.33 KB
dist/collections/operations ${{\color{Goldenrod}{ ▊ }}}$ 3.2%, 44.49 KB
dist/fields/hooks ${{\color{Goldenrod}{ ▊ }}}$ 3.2%, 44.39 KB
dist/utilities/configToJSONSchema.js ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 15.99 KB
dist/auth/operations ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 15.57 KB
dist/queues/operations ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 14.29 KB
dist/fields/config ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 13.63 KB
dist/globals/operations ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 13.36 KB
dist/fields/validations.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 10.69 KB
dist/collections/config ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 9.93 KB
dist/cli/commands ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 9.92 KB
dist/config/orderable ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 8.07 KB
dist/database/migrations ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 7.98 KB
dist/uploads/fetchAPI-multipart ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 7.87 KB
dist/index.js ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 7.78 KB
dist/hierarchy/utils ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 7.64 KB
dist/config/sanitize.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 7.07 KB
dist/utilities/telemetry ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 6.35 KB
dist/collections/endpoints ${{\color{Goldenrod}{ }}}$ 0.4%, 6.12 KB
dist/auth/strategies ${{\color{Goldenrod}{ }}}$ 0.4%, 5.61 KB
(other) ${{\color{Goldenrod}{ ████████▏ }}}$ 32.7%, 458.91 KB

Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js

Path Size
../../node_modules ${{\color{Goldenrod}{ █████████████████▉ }}}$ 71.8%, 150.13 KB
dist/fields/validations.js ${{\color{Goldenrod}{ █▎ }}}$ 5.1%, 10.69 KB
dist/fields/config ${{\color{Goldenrod}{ ▋ }}}$ 2.8%, 5.83 KB
dist/utilities/traverseFields.js ${{\color{Goldenrod}{ ▌ }}}$ 2.1%, 4.45 KB
dist/collections/config ${{\color{Goldenrod}{ ▍ }}}$ 1.6%, 3.33 KB
dist/config/orderable ${{\color{Goldenrod}{ ▍ }}}$ 1.5%, 3.13 KB
dist/fields/baseFields ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 2.79 KB
dist/utilities/deepCopyObject.js ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 2.69 KB
dist/config/client.js ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 2.69 KB
dist/auth/cookies.js ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 1.55 KB
dist/utilities/flattenTopLevelFields.js ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 1.41 KB
dist/utilities/getVersionsConfig.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 1.04 KB
dist/globals/config ${{\color{Goldenrod}{ }}}$ 0.4%, 939 B
dist/utilities/flattenAllFields.js ${{\color{Goldenrod}{ }}}$ 0.4%, 793 B
dist/utilities/unflatten.js ${{\color{Goldenrod}{ }}}$ 0.4%, 779 B
dist/utilities/sanitizeUserDataForEmail.js ${{\color{Goldenrod}{ }}}$ 0.3%, 713 B
dist/auth/extractJWT.js ${{\color{Goldenrod}{ }}}$ 0.3%, 696 B
dist/utilities/getFieldPermissions.js ${{\color{Goldenrod}{ }}}$ 0.3%, 651 B
dist/utilities/getSafeRedirect.js ${{\color{Goldenrod}{ }}}$ 0.3%, 632 B
dist/errors/ValidationError.js ${{\color{Goldenrod}{ }}}$ 0.3%, 577 B
(other) ${{\color{Goldenrod}{ ███████ }}}$ 28.2%, 58.98 KB

Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/features/blocks ${{\color{Goldenrod}{ ███▎ }}}$ 13.1%, 37.20 KB
dist/lexical/ui ${{\color{Goldenrod}{ ███ }}}$ 12.1%, 34.20 KB
dist/lexical/plugins ${{\color{Goldenrod}{ ██▉ }}}$ 11.7%, 33.01 KB
dist/features/table ${{\color{Goldenrod}{ ██▍ }}}$ 9.6%, 27.22 KB
dist/features/link ${{\color{Goldenrod}{ █▋ }}}$ 6.6%, 18.82 KB
dist/features/toolbars ${{\color{Goldenrod}{ █▌ }}}$ 6.2%, 17.45 KB
dist/features/upload ${{\color{Goldenrod}{ █▎ }}}$ 5.0%, 14.28 KB
dist/features/textState ${{\color{Goldenrod}{ ▉ }}}$ 3.9%, 11.08 KB
dist/lexical/utils ${{\color{Goldenrod}{ ▉ }}}$ 3.5%, 10.02 KB
dist/features/relationship ${{\color{Goldenrod}{ ▊ }}}$ 3.4%, 9.61 KB
dist/features/converters ${{\color{Goldenrod}{ ▊ }}}$ 3.0%, 8.36 KB
dist/utilities/fieldsDrawer ${{\color{Goldenrod}{ ▋ }}}$ 2.9%, 8.12 KB
dist/features/debug ${{\color{Goldenrod}{ ▋ }}}$ 2.6%, 7.40 KB
dist/lexical/config ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 5.14 KB
dist/features/lists ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 3.64 KB
dist/features/format ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 3.28 KB
dist/lexical/LexicalEditor.js ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.23 KB
dist/features/horizontalRule ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.18 KB
dist/field/Field.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 2.88 KB
dist/lexical/nodes ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 2.66 KB
(other) ${{\color{Goldenrod}{ █████████████████████▋ }}}$ 86.9%, 246.09 KB

Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/exports/client ${{\color{Goldenrod}{ █████████████████████████ }}}$ 100.0%, 26.90 KB

Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js

Path Size
dist/graphics/Logo ${{\color{Goldenrod}{ ███████▋ }}}$ 30.5%, 5.57 KB
../../node_modules ${{\color{Goldenrod}{ ███▌ }}}$ 14.5%, 2.65 KB
dist/graphics/Icon ${{\color{Goldenrod}{ ██ }}}$ 8.3%, 1.51 KB
dist/utilities/formatDocTitle ${{\color{Goldenrod}{ █▊ }}}$ 7.2%, 1.32 KB
dist/providers/TableColumns ${{\color{Goldenrod}{ █▏ }}}$ 4.7%, 866 B
dist/utilities/getGlobalData.js ${{\color{Goldenrod}{ █ }}}$ 4.2%, 762 B
dist/utilities/api.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 756 B
dist/utilities/groupNavItems.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 745 B
dist/elements/Translation ${{\color{Goldenrod}{ ▋ }}}$ 2.7%, 493 B
dist/utilities/handleTakeOver.js ${{\color{Goldenrod}{ ▌ }}}$ 2.4%, 440 B
dist/utilities/traverseForLocalizedFields.js ${{\color{Goldenrod}{ ▌ }}}$ 2.3%, 419 B
dist/elements/withMergedProps ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 339 B
dist/utilities/getNavGroups.js ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 338 B
dist/utilities/getVisibleEntities.js ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 329 B
dist/elements/WithServerSideProps ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 232 B
dist/layouts/Root ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 230 B
dist/utilities/handleGoBack.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 180 B
dist/fields/mergeFieldStyles.js ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 158 B
dist/forms/Form ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
dist/utilities/handleBackToDashboard.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
(other) ${{\color{Goldenrod}{ █████████████████▍ }}}$ 69.5%, 12.68 KB
Details

Next to the size is how much the size has increased or decreased compared with the base branch of this PR.

  • ‼️: Size increased by 20% or more. Special attention should be given to this.
  • ⚠️: Size increased in acceptable range (lower than 20%).
  • ✅: No change or even downsized.
  • 🗑️: The out file is deleted: not found in base branch.
  • 🆕: The out file is newly found: will be added to base branch.

The batched collection delete covers every id at once, so a failure there
belongs to the batch rather than to any single document. Reporting the raw
database message against each id made one batch failure read as N unrelated
per-document failures.

Per-document attribution is unchanged for every other failure source: locks,
`beforeDelete`, associated file cleanup, `afterRead` and `afterDelete` all still
report against the exact document. Access control never produced per-document
errors here, since it is merged into the query before the documents are read.
It is exported from the package root only so that Payload 2.x
`payload/versions` imports keep resolving, and it appears nowhere in the docs.
Tag it so the export is not mistaken for a supported API.
/**
* Deletes every version belonging to one parent document, or to many at once via `ids`.
*
* @internal - this may break or be removed at any time. It is exported from the package root only

@GermanJablo GermanJablo Aug 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tagged rather than removed, since it is exported from the package root. That is also why ids is additive.

It looks grandfathered rather than designed: absent from docs/ and only called by delete.ts and deleteByID.ts, yet test/import-test/import-all-2-exports.ts deliberately keeps the 2.x payload/versions import resolving.

awaitedDocs.push(await promise)

for (const doc of docs) {
awaitedDocs.push(await deleteDocumentIndividually(doc))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This mode keeps the per-document path, since it needs one transaction per document for DocumentDB and Cosmos.

It also picks up a fix. The old docs.map(async ...) invoked every callback immediately, so awaiting in order sequenced result collection but not execution, and each concurrent call shared one req. This loop runs one document at a time, which is what the mode's original comment already claimed to do.

Keep compatibility adapters on isolated per-document transactions, use
parameterized equality clauses for SQLite UUID JSON values, and assert both
configured deletion strategies in the regression test.
@GermanJablo
GermanJablo marked this pull request as ready for review August 31, 2026 19:16
Comment on lines +411 to +414
} catch (error) {
// The delete covers the whole batch, so a failure here belongs to the batch rather than to
// any single document. Say so explicitly, otherwise one batch failure reads as N unrelated
// per-document failures.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we get to this catch, we still continue the operation and so commit the transaction then - is that intentional?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, it was not intentional. The transaction now rolls back when deleteMany fails and prevents the later commit

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we add some regression testing when deleteMany throws?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, added!

@r1tsuu r1tsuu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm!

@GermanJablo
GermanJablo merged commit 21c5afb into main Sep 2, 2026
557 of 562 checks passed
@GermanJablo
GermanJablo deleted the germanjablo/bulk-delete-batching branch September 2, 2026 12:44
Dynogic added a commit to Dynogic/payload that referenced this pull request Oct 3, 2026
… instead of four per document (backport of upstream v4 payloadcms#17934, 21c5afb; locks, versions, scheduled jobs and the documents go behind one id-in filter each, hooks and per-document errors still run per document, bulkOperationsSingleTransaction keeps the per-document path; tests pass on MongoDB and SQLite)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RaEpthPEsDF9nb8STBgcLe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants