Skip to content

checkDocumentLockStatus reads locked documents without req, deadlocking the Postgres pool under concurrent update/delete #18406

Description

@TheVilfer

Describe the Bug

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.

Link to the code that causes the issue

https://github.com/payloadcms/payload/blob/main/packages/payload/src/utilities/checkDocumentLockStatus.ts

Reproduction Steps

  1. Postgres adapter with a small pool: pool: { max: 10 }.
  2. Create 11+ posts.
  3. 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.
  4. 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:

   const result = await payload.db.find({
     collection: lockedDocumentsCollectionSlug,
     limit: 1,
     pagination: false,
+    req: payload.db.name === 'mongoose' ? undefined : req,
     sort: '-updatedAt',
     where: lockedDocumentQuery,
   })

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.

Which area(s) are affected?

db-postgres, area: core

Environment Info

payload: 3.90.2
@payloadcms/db-postgres: 3.90.2
next: 16.x
Node: 24

Activity

  1. added
    area: core
    on Sep 30, 2026
  2. drewmt commented on Sep 30, 2026

    @drewmt

    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.

  3. removed
    area: core
    on Oct 1, 2026
  4. maximseshuk commented on Oct 11, 2026

    @maximseshuk
    Contributor

    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:

    const doc = await payload.create({
      collection: 'media',
      data: {},
      overrideAccess: true,
      file: { data: Buffer.from('hello'), mimetype: 'text/plain', name: 'a.txt', size: 5 },
    })
    
    await payload.renameFile({ collection: 'media', id: doc.id, filename: 'b.txt', overrideAccess: true }) // never resolves
    Database Pool lockDocuments Result
    Postgres 18.4 max: 1 true hangs
    Postgres 18.4 max: 1 false works
    Postgres 18.4 default (max: 10) true works
    PGlite default true hangs

    #18421 or #18447 should cover this. A renameFile regression test with max: 1 would be a good addition.

  5. drewmt commented on Oct 11, 2026

    @drewmt

    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.

  6. Gh05d commented on Nov 8, 2026

    @Gh05d

    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.

  7. cp7553479 commented on Nov 13, 2026

    @cp7553479

    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/drizzle 4.0.0-beta.7; pg 8.20.0; pg-pool 3.14.0; drizzle-orm 0.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.

    import assert from 'node:assert/strict'
    import { createHash } from 'node:crypto'
    import { EventEmitter } from 'node:events'
    import fs from 'node:fs'
    import { createRequire } from 'node:module'
    import path from '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'
    import pg from 'pg'
    
    const require = createRequire(import.meta.url)
    const adapterRequire = createRequire(require.resolve('@payloadcms/db-postgres'))
    const drizzleDist = path.dirname(adapterRequire.resolve('@payloadcms/drizzle'))
    const helperURL = new URL('./utilities/checkDocumentLockStatus.js', import.meta.resolve('payload'))
    const { checkDocumentLockStatus, getLockedDocumentIds } = await import(helperURL.href)
    const { getTransaction } = await import(pathToFileURL(path.join(drizzleDist, 'utilities/getTransaction.js')).href)
    const checksum = () => createHash('sha256').update(fs.readFileSync(helperURL)).digest('hex')
    const originalChecksum = checksum()
    
    // Network-free Client; adapter find/deleteMany below are test fixtures as well.
    class NoNetworkClient extends EventEmitter {
      _queryable = true
      _ending = false
      connect(callback) { queueMicrotask(() => callback(null)) }
      query(...args) {
        const result = { rows: [], rowCount: 0, fields: [], command: 'SELECT' }
        const callback = args.at(-1)
        if (typeof callback === 'function') queueMicrotask(() => callback(null, result))
        else return Promise.resolve(result)
      }
      end(callback) {
        this._ending = true
        queueMicrotask(() => { this.emit('end'); callback?.() })
      }
    }
    
    async function experiment(helper, mode) {
      const pool = new pg.Pool({ max: 2, idleTimeoutMillis: 0, Client: NoNetworkClient })
      const heldClients = await Promise.all([pool.connect(), pool.connect()])
      const rootDB = drizzle({ client: pool })
      const adapter = { drizzle: rootDB, sessions: {} }
      const reads = []
      const reqs = heldClients.map((client, i) => {
        const transactionID = `transaction-${i}`
        adapter.sessions[transactionID] = { db: drizzle({ client }) }
        return { transactionID, user: { id: `user-${i}` } }
      })
      let completed = 0
      const pending = reqs.map((req) => {
        req.payload = {
          collections: { posts: { config: { lockDocuments: true } }, 'payload-locked-documents': {} },
          db: {
            name: 'postgres',
            async find(args) {
              // The control varies one input at this test boundary; package source is untouched.
              const readReq = mode === 'request-routing-control' ? req : args.req
              const db = await getTransaction(adapter, readReq)
              reads.push({ helperPassedReq: args.req === req, route: db === rootDB ? 'root-pool' : 'held-session' })
              await db.execute(sql`SELECT 1`)
              return { docs: [] }
            },
            async deleteMany(args) { assert.equal(args.req, req) },
          },
        }
        const args = { collectionSlug: 'posts', overrideLock: false, req }
        const operation = helper === 'single'
          ? checkDocumentLockStatus({ ...args, id: 'post-1' })
          : getLockedDocumentIds({ ...args, ids: ['post-1'] })
        return operation.then(() => { completed++ })
      })
      let snapshot
      try {
        await setImmediate()
        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())
        await Promise.all(pending)
        assert.equal(pool.waitingCount, 0)
        await pool.end()
      }
      return { ...snapshot, completedAfterReleasingHeldClients: completed, poolEnded: true }
    }
    
    const cases = []
    for (const helper of ['single', 'bulk']) {
      for (const mode of ['as-published', 'request-routing-control']) cases.push(await experiment(helper, mode))
    }
    assert.equal(checksum(), originalChecksum)
    const version = (packageName) => {
      const entry = require.resolve(packageName)
      const root = path.dirname(path.dirname(entry))
      return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version
    }
    const report = {
      checkedAt: new Date().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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions