payload icon indicating copy to clipboard operation
payload copied to clipboard

db-postgres: every update takes FOR UPDATE (via `INSERT … ON CONFLICT ("id") DO UPDATE SET "id" = …`), blocking concurrent inserts of rows that reference the document

Open allandelmare opened this issue 2 months ago • 1 comments

Summary

For most collections, @payloadcms/drizzle writes an update of an existing document as

insert into "parents" ("id", "title", …) values ($1, $2, …)
on conflict ("id") do update set "id" = $5, "title" = $6, … returning …

Postgres picks the row lock of ON CONFLICT DO UPDATE from the columns the SET list names, not from the values that change. "id" is always named, and it is a key column (the primary key, which foreign keys reference). So every such update locks the document's row FOR UPDATE instead of FOR NO KEY UPDATE.

FOR UPDATE conflicts with the FOR KEY SHARE lock that Postgres's foreign-key check takes on the referenced row. The consequence: from the moment a Payload update of a document runs inside a transaction until that transaction commits, any insert (or FK-changing update) of a row that references that document waits, in any other transaction. That covers a relationship field on another collection, _rels rows, and draft/autosave version rows.

A plain UPDATE … SET <non-key columns> WHERE id = $1 takes FOR NO KEY UPDATE and does not block those inserts.

This turns ordinary saves into lock waits across related collections. Where two code paths touch a document and a referencing row in opposite orders, it turns into deadlocks (40P01).

Versions

  • payload 3.90.0
  • @payloadcms/drizzle 3.90.0
  • @payloadcms/db-postgres 3.90.0
  • PostgreSQL 17.10 (Docker image pgvector/pgvector:pg17; the lock behaviour is core Postgres and the same on the official postgres:17 image)
  • Node 26

Reproduction

A minimal config. The parent collection has an array field. Any array, blocks, hasMany or localized field sends updates through upsertRow's non-optimized branch, which is the ON CONFLICT one.

import { buildConfig, getPayload } from 'payload'
import { postgresAdapter } from '@payloadcms/db-postgres'

const config = buildConfig({
  secret: 'repro-secret-repro-secret-repro-secret',
  db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URL }, push: true }),
  collections: [
    {
      slug: 'parents',
      fields: [
        { name: 'title', type: 'text' },
        { name: 'tags', type: 'array', fields: [{ name: 'label', type: 'text' }] },
      ],
    },
    {
      slug: 'children',
      fields: [
        { name: 'parent', type: 'relationship', relationTo: 'parents' },
        { name: 'body', type: 'text' },
      ],
    },
  ],
  typescript: { autoGenerate: false },
})

const payload = await getPayload({ config })

// Seed one parent (id 1) first, e.g. `await payload.create({ collection: 'parents', data: { title: 'first', tags: [{ label: 'a' }] } })`.

// Session 1: a Payload update inside a transaction, held open for a few seconds.
const transactionID = await payload.db.beginTransaction()
await payload.update({ collection: 'parents', id: 1, data: { title: 'updated' }, req: { transactionID, payload } })
await new Promise((r) => setTimeout(r, 6000))
await payload.db.commitTransaction(transactionID)

While session 1 is holding its transaction open, session 2 (psql) runs:

SET lock_timeout = '2s';
SET
INSERT INTO children (parent_id, body, updated_at, created_at) VALUES (1, 'hi', now(), now());
ERROR:  canceling statement due to lock timeout
CONTEXT:  while locking tuple (0,1) in relation "parents"
SQL statement "SELECT 1 FROM ONLY "public"."parents" x WHERE "id" OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x"

The CONTEXT line is the foreign-key check on children.parent_id. Without a lock_timeout, the insert waits until session 1 commits.

With log_statement = 'mod', the statement Payload issued in session 1 is:

insert into "parents" ("id", "title", "updated_at", "created_at") values ($1, $2, $3, $4)
on conflict ("id") do update set "id" = $5, "title" = $6, "updated_at" = $7, "created_at" = $8
returning "id", "title", "updated_at", "created_at"

The same in plain psql (two sessions, PostgreSQL 17.10, the tables above)

A. The statement Payload emits. Session 1:

BEGIN;
INSERT INTO parents (id, title, updated_at, created_at) VALUES (1, 'b', now(), now())
  ON CONFLICT (id) DO UPDATE SET id = 1, title = 'b', updated_at = now(), created_at = parents.created_at;
INSERT 0 1
-- (held open)

Session 2:

SET lock_timeout = '2s';
INSERT INTO children (parent_id, body, updated_at, created_at) VALUES (1, 'hi', now(), now());
ERROR:  canceling statement due to lock timeout
CONTEXT:  while locking tuple (0,3) in relation "parents"
SQL statement "SELECT 1 FROM ONLY "public"."parents" x WHERE "id" OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x"

B. The same write as a plain UPDATE. Session 1:

BEGIN;
UPDATE parents SET title = 'b', updated_at = now() WHERE id = 1;
UPDATE 1
-- (held open)

Session 2:

SET lock_timeout = '2s';
INSERT INTO children (parent_id, body, updated_at, created_at) VALUES (1, 'hi', now(), now());
INSERT 0 1

Why (Postgres internals)

  • For INSERT … ON CONFLICT DO UPDATE, ExecOnConflictUpdate locks the conflicting tuple with ExecUpdateLockMode(). That returns LockTupleExclusive (FOR UPDATE) whenever the statement's updated-columns set overlaps the relation's key columns: the columns of unique, non-partial, non-expression indexes, the primary key included. It looks at the column list, not whether the value changed. SET "id" = <the same id> is enough.
  • A plain UPDATE is judged by value (heap_update compares old and new key values). Naming id or a unique column at its old value keeps FOR NO KEY UPDATE, unless the table has a row-level BEFORE UPDATE trigger. In that case GetTupleForTrigger locks the row with the same list-based ExecUpdateLockMode() first. That applies even to a column-specific trigger (BEFORE UPDATE OF col), a WHEN (false) trigger, or a disabled trigger.

So Payload's optimized branch (a plain UPDATE whose SET names every main-table column of the document it is given, id and unique fields included) also takes FOR UPDATE on any table with such a trigger.

Measured matrix (PostgreSQL 17.10): a parent p(id pk, tok text unique, title, …), a child c(p_id references p(id)). Each cell is whether an open writer blocks INSERT INTO c.

Trigger on p UPDATE p SET id = id, tok = tok, title = … UPDATE p SET title = … INSERT … ON CONFLICT (id) DO UPDATE SET id = …, title = … … ON CONFLICT (id) DO UPDATE SET title = …
none no no blocks no
BEFORE UPDATE … FOR EACH ROW blocks no blocks no
BEFORE UPDATE OF <other cols> … FOR EACH ROW blocks no blocks no
BEFORE UPDATE … FOR EACH ROW WHEN (false) blocks no blocks no
BEFORE UPDATE … FOR EACH ROW, then ALTER TABLE p DISABLE TRIGGER blocks no blocks no
AFTER UPDATE … FOR EACH ROW no no blocks no
AFTER UPDATE … FOR EACH STATEMENT no no blocks no
BEFORE UPDATE … FOR EACH STATEMENT no no blocks no

Proposed fix

In upsertRow, when operation === 'update' and an id is known:

  1. Write a plain UPDATE, not INSERT … ON CONFLICT. Use db.update(table).set(row).where(and(eq(table.id, id), where)).returning().
    • Keep ON CONFLICT only for a genuine create-or-update, i.e. db.upsert() → updateOne({ options: { upsert: true } }). updateOne would need to pass that flag through to upsertRow.
    • A side benefit: today an update of a row that was deleted concurrently silently re-inserts it, because the ON CONFLICT finds no conflict and inserts. A plain UPDATE affects nothing and returns no row.
    • Payload core would then pass that null into saveVersion / afterRead, which fails with a TypeError. That already happens today in the optimized branch when an update matches nothing. We suggest one answer for both branches: when an id-only update (no where) matches nothing, throw NotFound; a conditional update (where) keeps returning null.
  2. Never name id in the SET. It is the row's identity and never changes on update.
  3. Never name a key column whose value is unchanged. A key column is one in a unique, non-partial, non-expression index, which is what Postgres treats as "key".
    • For every such column in the row, read the current values with a plain SELECT … WHERE id = $1 [AND where] (no locking clause). A stale read can only omit a column the writer did not change as of the read; a concurrent newer value then survives instead of being reverted. The UPDATE's lock mode is still decided by Postgres.
    • Do not take a lock in that read. A FOR NO KEY UPDATE pre-read followed by a key-changing UPDATE (which must then wait for FOR UPDATE) deadlocks against a transaction that inserted a referencing row and then updates the same parent. The stock statement and a plain read both commit (measured, PostgreSQL 17.10).
    • Drop the column from SET when its value is equal.
    • A key column whose value really changes stays in the SET. That update genuinely needs FOR UPDATE.
    • The key-column set can be read once per table from pg_index and cached. That also covers unique indexes created outside the schema.
    • This matters for tables with row-level BEFORE UPDATE triggers (see the matrix). Without step 3, those tables still escalate on every save.
  4. Apply steps 2–3 to the optimized branch as well: the drizzle.update(...).set(row) path used for simple data.

An abridged sketch against the published build (dist/upsertRow/index.js, v3.90.0):

-                if (id) {
-                    rowToInsert.row.id = id;
-                    [insertedRow] = await adapter.insert({
-                        db,
-                        onConflictDoUpdate: where ? { set: rowToInsert.row, target, where } : { set: rowToInsert.row, target },
-                        tableName,
-                        values: rowToInsert.row
-                    });
+                if (id && !upsert && adapter.name === 'postgres') {
+                    delete rowToInsert.row.id;
+                    // strips every key column whose value is unchanged (a plain SELECT, no locking clause)
+                    const { updateWhere } = await planPlainUpdate({ id, adapter, db, row: rowToInsert.row, tableName, where });
+                    const table = adapter.tables[tableName];
+                    [insertedRow] = Object.keys(rowToInsert.row).length
+                        ? await db.update(table).set(rowToInsert.row).where(updateWhere).returning()
+                        : await db.select({ id: table.id }).from(table).where(updateWhere);
+                    // missedUpdate(): NotFound for an id-only miss, null for a conditional one — also used
+                    // at the optimized branch's three `return null` sites.
+                    if (!insertedRow) missedUpdate({ adapter, req, where });
+                } else if (id) {
+                    rowToInsert.row.id = id;
+                    [insertedRow] = await adapter.insert({ /* unchanged: the upsert path */ });

Plus, in updateOne, pass upsert: options.upsert === true into upsertRow. The same planPlainUpdate call goes before hasDataToUpdate in the optimized branch.

With this change, the reproduction's session-2 insert returns INSERT 0 1 immediately. Payload's statement becomes:

update "parents" set "title" = $1, "updated_at" = $2, "created_at" = $3 where "parents"."id" = $4
returning "id", "title", "updated_at", "created_at"

What is unchanged:

  • array, blocks, _rels, locale, hasMany select/text/number handling (the delete-and-insert of child rows after the main row);
  • version rows;
  • select / returning shape (the document is still re-read with findFirst);
  • unique-violation mapping (handleUpsertError sees the same 23505);
  • creates.

We have run this against a large integration suite (several hundred spec files) without behavioural changes, apart from the lock mode and the no-resurrection case above.

The SQLite adapter shares upsertRow, and its locking model is different. We kept the stock path there (adapter.name !== 'postgres').

Happy to open a PR against packages/drizzle/src/upsertRow/ if this direction is acceptable.

allandelmare avatar Sep 24 '26 17:09 allandelmare

Related: #18111 changes the same upsertRow path (conditional updateOne({ where }) without an id). This proposal targets the id branch (update-by-id), so the two should compose; whichever lands second will need to account for the other.

allandelmare avatar Sep 24 '26 18:09 allandelmare