Repository navigation
perf: make bulk delete O(1) database queries instead of O(N) - #17934
Conversation
`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.
📦 esbuild Bundle Analysis for payloadThis analysis was generated by esbuild-bundle-analyzer. 🤖
Largest pathsThese visualization shows top 20 largest paths in the bundle.Meta file: packages/next/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js
Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js
DetailsNext to the size is how much the size has increased or decreased compared with the base branch of this PR.
|
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 |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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.
| } 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. |
There was a problem hiding this comment.
When we get to this catch, we still continue the operation and so commit the transaction then - is that intentional?
There was a problem hiding this comment.
Good catch, it was not intentional. The transaction now rolls back when deleteMany fails and prevents the later commit
There was a problem hiding this comment.
should we add some regression testing when deleteMany throws?
… 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
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 adeleteOne. 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. ThedeleteOnealso re-reads a rowdb.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.tsbecomes 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.deleteCollectionVersionsanddeleteScheduledPublishJobsgain an optional pluralids. Two batched lock helpers sit besidecheckDocumentLockStatus, which is itself untouched, soupdate,deleteByIDand 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:Error attribution
Unchanged for every framework-level failure: locks,
beforeDelete, file cleanup,afterReadandafterDeleteall still report the exact document. Access control never produced per-document errors here, sinceaccess.deleteis merged into the query beforedb.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