You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
checkDocumentLockStatus reads locked documents without req, deadlocking the Postgres pool under concurrent update/delete #18406
In [email protected], checkDocumentLockStatus (packages/payload/src/utilities/checkDocumentLockStatus.ts) looks up payload-locked-documents through payload.db.find(...)without passing req. The deleteMany call a few lines below does pass req.
With @payloadcms/db-postgres, update and delete operations with overrideLock: false (the default for REST PATCH/DELETE) run inside a transaction. Each one holds its transaction connection and then asks the pool for a second connection for this lock-status read. When about pool.max updates or deletes run at the same time, every connection is idle in transaction waiting for the pool. The server hangs indefinitely, and so does every other request, including POST /api/users/login.
pg_stat_activity shows pool.max connections idle in transaction (wait_event Client), and the last statement is the operation's own select of the document.
Postgres adapter with a small pool: pool: { max: 10 }.
Create 11+ posts.
Send PATCH /api/posts/:id for all of them in parallel (for example with Promise.all), or call Local API payload.update({ collection, id, data, overrideLock: false }) 11+ times at once.
None of the requests finishes, and the server stops answering.
Passing req to that find fixes it. It is the same change as the one already applied to deleteMany below it:
We run this as a local pnpm patch. A regression test with pool + 2 parallel updates and deletes passes with the patch, and the 423 for a document locked by another user still works inside the transaction.
Thanks for the reproduction. I confirmed the pool exhaustion on main and opened #18421 with transaction-aware lock reads and PostgreSQL regression tests, including bulk deletion.
payload.renameFile (4.0.0-beta.0) hits this with a single call, every time.
It always passes overrideLock: false to updateDocument (renameFile.js:91) inside its own transaction. So checkDocumentLockStatus runs its find without req, on a second connection. With pool: { max: 1 } (also PGlite) the call never resolves.
Repro: one upload collection with local storage, then:
Added a renameFile regression to #18421 using a real PostgreSQL pool with max: 1. Removing the transaction-aware lock read reproduces the connection timeout; with the fix, the saved filename and file bytes are correct. The lock and existing rename suites pass locally: 33 tests passed, 1 existing skip.
We ran into this class of pool deadlock in production on 3.90.2 (Postgres, default pool of 10): concurrent writes whose hooks queried outside the write's transaction left every connection idle in transaction, and the site was down for several hours until a restart.
While auditing our code for the same pattern, this lock-status read turned out to be the one remaining case inside Payload itself: it takes a second connection on every REST/admin update and delete with overrideLock: false. Passing req as in #18447 fixes it for us; we apply it as a pnpm patch for now. Would be great to see one of the two PRs merged.
Adding version-specific evidence for the PostgreSQL connection-pool starvation described here, with clarification of the historical intent and the limits of an offline experiment.
Released source and history
In both v4.0.0-beta.7 and v4.0.0-beta.8, the single checkDocumentLockStatus and bulk getLockedDocumentIds reads call payload.db.find without req. This is source inspection for both versions; the experiment below uses beta.7 only.
The omission has historical intent: 9728d805925b1c36f02bc527602dd4c6c0ee410a, from #11287, deliberately removed req from the single read to address autosave transaction errors observed against remote MongoDB. Its diff retained request propagation for non-Mongoose cleanup. This is therefore not simply an accidentally forgotten argument; the PostgreSQL consequence needs adapter- and isolation-aware handling.
Offline connection-routing experiment
Environment: Node 24.22.1; payload, @payloadcms/db-postgres, and @payloadcms/drizzle4.0.0-beta.7; pg8.20.0; pg-pool3.14.0; drizzle-orm0.45.3.
The script uses the unmodified installed single/bulk helpers and real getTransaction. Crucially, db.find is a fixture: it invokes native getTransaction, then executes SELECT 1 through real Drizzle and pg.Pool. deleteMany is a stub asserting request propagation. The Client is an in-memory, network-free substitute. Two checked-out clients and manually populated session entries represent occupied transaction connections; no real BEGIN or COMMIT occurs.
Four cases, each with multiple assertions, produced these snapshots while both pool slots remained held:
Helper
Fixture request input
Pool waiting
Completed operations
Single
As published
2
0
Single
Request-routing control
0
2
Bulk
As published
2
0
Bulk
Request-routing control
0
2
After returning the held clients, both original-helper cases also completed both operations. All cases drained their queues and ended their pools. The helper checksum was unchanged. The controls supply the request at the fixture boundary; the native helpers still omit it in all four cases.
This isolates connection routing and pool scheduling. It does not exercise the complete native adapter find pipeline, a PostgreSQL server, SQL isolation semantics, actual transactions, or REST/Admin integration, and does not independently establish a production incident's cause.
Isolation-level boundary
Under Read Committed, an enclosing write can retain a connection while an independent lock read queues for another; saturation prevents completion and release. This is pool starvation, not necessarily a database row-lock deadlock. A transaction-local read can use a fresh statement snapshot there. Repeatable Read/Serializable require additional care: a transaction snapshot may miss a subsequently committed lock.
#19551 addresses that distinction and explicitly leaves snapshot-isolation pool exhaustion unchanged. Its reported tests are upstream author results, not ours. The request-routing controls below are not an unconditional production fix or a proposal to pass req under every isolation level.
Complete offline reproduction script
Save as pool-reproduction.mjs in a directory resolving the versions above and run node pool-reproduction.mjs. The script directly imports drizzle-orm, so that package must be directly resolvable from the script directory; in a pnpm isolated dependency layout, an indirect installation alone is insufficient. It prints version metadata, the installed helper SHA256, and all four case results; it makes no network connections. The only change from the captured experiment script is removal of its JSON file-output statement.
importassertfrom'node:assert/strict'import{createHash}from'node:crypto'import{EventEmitter}from'node:events'importfsfrom'node:fs'import{createRequire}from'node:module'importpathfrom'node:path'import{setImmediate}from'node:timers/promises'import{fileURLToPath,pathToFileURL}from'node:url'import{sql}from'drizzle-orm'import{drizzle}from'drizzle-orm/node-postgres'importpgfrom'pg'constrequire=createRequire(import.meta.url)constadapterRequire=createRequire(require.resolve('@payloadcms/db-postgres'))constdrizzleDist=path.dirname(adapterRequire.resolve('@payloadcms/drizzle'))consthelperURL=newURL('./utilities/checkDocumentLockStatus.js',import.meta.resolve('payload'))const{ checkDocumentLockStatus, getLockedDocumentIds }=awaitimport(helperURL.href)const{ getTransaction }=awaitimport(pathToFileURL(path.join(drizzleDist,'utilities/getTransaction.js')).href)constchecksum=()=>createHash('sha256').update(fs.readFileSync(helperURL)).digest('hex')constoriginalChecksum=checksum()// Network-free Client; adapter find/deleteMany below are test fixtures as well.classNoNetworkClientextendsEventEmitter{_queryable=true_ending=falseconnect(callback){queueMicrotask(()=>callback(null))}query(...args){constresult={rows: [],rowCount: 0,fields: [],command: 'SELECT'}constcallback=args.at(-1)if(typeofcallback==='function')queueMicrotask(()=>callback(null,result))elsereturnPromise.resolve(result)}end(callback){this._ending=truequeueMicrotask(()=>{this.emit('end');callback?.()})}}asyncfunctionexperiment(helper,mode){constpool=newpg.Pool({max: 2,idleTimeoutMillis: 0,Client: NoNetworkClient})constheldClients=awaitPromise.all([pool.connect(),pool.connect()])constrootDB=drizzle({client: pool})constadapter={drizzle: rootDB,sessions: {}}constreads=[]constreqs=heldClients.map((client,i)=>{consttransactionID=`transaction-${i}`adapter.sessions[transactionID]={db: drizzle({ client })}return{ transactionID,user: {id: `user-${i}`}}})letcompleted=0constpending=reqs.map((req)=>{req.payload={collections: {posts: {config: {lockDocuments: true}},'payload-locked-documents': {}},db: {name: 'postgres',asyncfind(args){// The control varies one input at this test boundary; package source is untouched.constreadReq=mode==='request-routing-control' ? req : args.reqconstdb=awaitgetTransaction(adapter,readReq)reads.push({helperPassedReq: args.req===req,route: db===rootDB ? 'root-pool' : 'held-session'})awaitdb.execute(sql`SELECT 1`)return{docs: []}},asyncdeleteMany(args){assert.equal(args.req,req)},},}constargs={collectionSlug: 'posts',overrideLock: false, req }constoperation=helper==='single'
? checkDocumentLockStatus({ ...args,id: 'post-1'})
: getLockedDocumentIds({ ...args,ids: ['post-1']})returnoperation.then(()=>{completed++})})letsnapshottry{awaitsetImmediate()snapshot={ helper, mode,totalCount: pool.totalCount,idleCount: pool.idleCount,waitingCount: pool.waitingCount, completed, reads }assert.equal(pool.totalCount,2)assert.equal(pool.idleCount,0)assert.ok(reads.every((r)=>!r.helperPassedReq))assert.equal(pool.waitingCount,mode==='as-published' ? 2 : 0)assert.equal(completed,mode==='as-published' ? 0 : 2)assert.ok(reads.every((r)=>r.route===(mode==='as-published' ? 'root-pool' : 'held-session')))}finally{heldClients.forEach((client)=>client.release())awaitPromise.all(pending)assert.equal(pool.waitingCount,0)awaitpool.end()}return{ ...snapshot,completedAfterReleasingHeldClients: completed,poolEnded: true}}constcases=[]for(consthelperof['single','bulk']){for(constmodeof['as-published','request-routing-control'])cases.push(awaitexperiment(helper,mode))}assert.equal(checksum(),originalChecksum)constversion=(packageName)=>{constentry=require.resolve(packageName)constroot=path.dirname(path.dirname(entry))returnJSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).version}constreport={checkedAt: newDate().toISOString(),node: process.version,payload: version('payload'),postgresAdapter: version('@payloadcms/db-postgres'),drizzleAdapter: JSON.parse(fs.readFileSync(path.join(drizzleDist,'../package.json'),'utf8')).version,pg: version('pg'),pgPool: JSON.parse(fs.readFileSync(path.join(path.dirname(createRequire(require.resolve('pg')).resolve('pg-pool')),'package.json'),'utf8')).version,scope: 'Offline unit experiment: unmodified native lock helpers and getTransaction, real Drizzle and pg.Pool, in-memory Client, fixture adapter find/deleteMany. No native adapter find pipeline, PostgreSQL server, real transactions, SQL isolation semantics, or REST integration is exercised.',nativeSourceUnmodified: true,nativeSourceSha256: originalChecksum,
cases,}console.log(JSON.stringify(report))
Activity
drewmt commentedon Sep 30, 2026
Thanks for the reproduction. I confirmed the pool exhaustion on main and opened #18421 with transaction-aware lock reads and PostgreSQL regression tests, including bulk deletion.
maximseshuk commentedon Oct 11, 2026
payload.renameFile(4.0.0-beta.0) hits this with a single call, every time.It always passes
overrideLock: falsetoupdateDocument(renameFile.js:91) inside its own transaction. SocheckDocumentLockStatusruns itsfindwithoutreq, on a second connection. Withpool: { max: 1 }(also PGlite) the call never resolves.Repro: one upload collection with local storage, then:
lockDocumentsmax: 1max: 1max: 10)#18421 or #18447 should cover this. A
renameFileregression test withmax: 1would be a good addition.drewmt commentedon Oct 11, 2026
Added a renameFile regression to #18421 using a real PostgreSQL pool with max: 1. Removing the transaction-aware lock read reproduces the connection timeout; with the fix, the saved filename and file bytes are correct. The lock and existing rename suites pass locally: 33 tests passed, 1 existing skip.
fix: address six additional Payload v4 core and plugin issues [skip ci]
Gh05d commentedon Nov 8, 2026
We ran into this class of pool deadlock in production on 3.90.2 (Postgres, default pool of 10): concurrent writes whose hooks queried outside the write's transaction left every connection
idle in transaction, and the site was down for several hours until a restart.While auditing our code for the same pattern, this lock-status read turned out to be the one remaining case inside Payload itself: it takes a second connection on every REST/admin update and delete with
overrideLock: false. Passingreqas in #18447 fixes it for us; we apply it as a pnpm patch for now. Would be great to see one of the two PRs merged.cp7553479 commentedon Nov 13, 2026
Adding version-specific evidence for the PostgreSQL connection-pool starvation described here, with clarification of the historical intent and the limits of an offline experiment.
Released source and history
In both
v4.0.0-beta.7andv4.0.0-beta.8, the singlecheckDocumentLockStatusand bulkgetLockedDocumentIdsreads callpayload.db.findwithoutreq. This is source inspection for both versions; the experiment below uses beta.7 only.The omission has historical intent:
9728d805925b1c36f02bc527602dd4c6c0ee410a, from #11287, deliberately removedreqfrom the single read to address autosave transaction errors observed against remote MongoDB. Its diff retained request propagation for non-Mongoose cleanup. This is therefore not simply an accidentally forgotten argument; the PostgreSQL consequence needs adapter- and isolation-aware handling.Offline connection-routing experiment
Environment: Node 24.22.1;
payload,@payloadcms/db-postgres, and@payloadcms/drizzle4.0.0-beta.7;pg8.20.0;pg-pool3.14.0;drizzle-orm0.45.3.The script uses the unmodified installed single/bulk helpers and real
getTransaction. Crucially,db.findis a fixture: it invokes nativegetTransaction, then executesSELECT 1through real Drizzle andpg.Pool.deleteManyis a stub asserting request propagation. The Client is an in-memory, network-free substitute. Two checked-out clients and manually populated session entries represent occupied transaction connections; no realBEGINorCOMMIToccurs.Four cases, each with multiple assertions, produced these snapshots while both pool slots remained held:
After returning the held clients, both original-helper cases also completed both operations. All cases drained their queues and ended their pools. The helper checksum was unchanged. The controls supply the request at the fixture boundary; the native helpers still omit it in all four cases.
This isolates connection routing and pool scheduling. It does not exercise the complete native adapter find pipeline, a PostgreSQL server, SQL isolation semantics, actual transactions, or REST/Admin integration, and does not independently establish a production incident's cause.
Isolation-level boundary
Under Read Committed, an enclosing write can retain a connection while an independent lock read queues for another; saturation prevents completion and release. This is pool starvation, not necessarily a database row-lock deadlock. A transaction-local read can use a fresh statement snapshot there. Repeatable Read/Serializable require additional care: a transaction snapshot may miss a subsequently committed lock.
#19551 addresses that distinction and explicitly leaves snapshot-isolation pool exhaustion unchanged. Its reported tests are upstream author results, not ours. The request-routing controls below are not an unconditional production fix or a proposal to pass
requnder every isolation level.Complete offline reproduction script
Save as
pool-reproduction.mjsin a directory resolving the versions above and runnode pool-reproduction.mjs. The script directly importsdrizzle-orm, so that package must be directly resolvable from the script directory; in a pnpm isolated dependency layout, an indirect installation alone is insufficient. It prints version metadata, the installed helper SHA256, and all four case results; it makes no network connections. The only change from the captured experiment script is removal of its JSON file-output statement.