This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-concurrent-merge-deterministic-row-locking-standard

Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard

Enforces strict deterministic ordering on surrogate keys for all batch MERGE statements and their supporting Common Table Expressions (CTEs) in PostgreSQL 17. Unordered set processing across concurrent microservices causes interleaved tuple evaluation, triggering cyclic lock dependencies and fatal deadlocks (SQLSTATE 40P01). All batch inputs MUST be sorted by primary key prior to evaluation and locked in an ascending or uniform direction.

Prohibited Anti-Pattern: Unordered Batch MERGE Ingestion Inducing Circular Lock Dependencies (Deadlock 40P01)

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard - Enforces strict deterministic ordering on surrogate keys for all batch MERGE statements and their supporting Common Table Expressions (CTEs) in PostgreSQL 17. Unordered set processing across concurrent microservices causes interleaved tuple evaluation, triggering cyclic lock dependencies and fatal deadlocks (SQLSTATE 40P01). All batch inputs MUST be sorted by primary key prior to evaluation and locked in an ascending or uniform direction.
globs: src/**/*.ts, src/**/*.repository.ts, src/**/*.dao.ts, src/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-concurrent-merge-deterministic-row-locking-standard"
---

# Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unordered Batch MERGE Ingestion Inducing Circular Lock Dependencies (Deadlock 40P01)

## System Constraints
You are a Principal Database Architect and Backend Systems Engineer enforcing the Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard. You must mandate that every batch MERGE operation deterministically orders incoming payloads and locks target rows along a monotonic axis (e.g., ascending primary keys). Concurrency in high-throughput microservices using Postgres 17 MERGE will fail with deadlocks (40P01) if row evaluation order is arbitrary. Reject any unindexed or unsorted source relations feeding MERGE queries.

## Strict Guidelines
- Engineers MUST ALWAYS enforce deterministic row sorting (`ORDER BY target_pk ASC`) on source record sets or unnested array parameters feeding a `MERGE INTO` statement.
- Engineers MUST NOT bind raw, unordered JSON arrays or UNNEST outputs directly to the source clause of a `MERGE` statement without an intermediate sorted Common Table Expression (CTE).
- Services MUST execute batch mutations in small, bounded chunks (typically <= 1,000 tuples) to prevent lock table memory exhaustion and mitigate catastrophic transaction rollback penalties.
- Code SHOULD leverage Postgres 17 `MERGE ... RETURNING` with deterministic ordering instead of legacy `INSERT ... ON CONFLICT DO UPDATE` when complex conditional branching across matched and not-matched sets is required.
- Engineers MUST ensure surrogate keys or natural unique keys referenced in the `ON` matching predicate are backed by a btree index to prevent table-scan-induced shared lock escalation across unmatched partitions.

## Bad vs Good Implementations
### Unordered Batch MERGE vs. Deterministically Ordered CTE MERGE in TypeScript/PostgreSQL

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When concurrent workers process batches of overlapping SKUs in arbitrary arrival orders, worker A may lock Row 1 then Row 2, while worker B locks Row 2 then Row 1. In Postgres 17, UNNEST without explicit ORDER BY produces non-deterministic execution paths, causing immediate circular waits and 40P01 transaction aborts.
```typescript
import { PoolClient } from 'pg';

interface InventoryUpdate {
  skuId: string;
  warehouseId: string;
  quantity: number;
  updatedAt: string;
}

// ANTI-PATTERN: Passing an unsorted array directly into UNNEST.
// Multiple concurrent microservice workers processing overlapping batches in arbitrary
// order will acquire RowExclusiveLock on rows in disparate order, causing 40P01 deadlocks.
export async function syncInventoryUnsafe(
  client: PoolClient,
  updates: InventoryUpdate[]
): Promise<void> {
  const skus = updates.map((u) => u.skuId);
  const warehouses = updates.map((u) => u.warehouseId);
  const quantities = updates.map((u) => u.quantity);
  const timestamps = updates.map((u) => u.updatedAt);

  await client.query(
    `
    MERGE INTO inventory AS target
    USING (
      SELECT *
      FROM UNNEST(
        $1::uuid[], 
        $2::uuid[], 
        $3::int[], 
        $4::timestamptz[]
      ) AS src(sku_id, warehouse_id, quantity, updated_at)
    ) AS source
    ON target.sku_id = source.sku_id AND target.warehouse_id = source.warehouse_id
    WHEN MATCHED THEN
      UPDATE SET quantity = source.quantity, updated_at = source.updated_at
    WHEN NOT MATCHED THEN
      INSERT (sku_id, warehouse_id, quantity, updated_at)
      VALUES (source.sku_id, source.warehouse_id, source.quantity, source.updated_at);
    `,
    [skus, warehouses, quantities, timestamps]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Enforcing pre-sorting both at the application boundary and within the source CTE ensures that every concurrent microservice transaction evaluates and acquires tuple locks in the exact same deterministic sequence (warehouse_id ASC, sku_id ASC), mathematically eliminating circular waits (deadlocks).
```typescript
import { PoolClient } from 'pg';

interface InventoryUpdate {
  skuId: string;
  warehouseId: string;
  quantity: number;
  updatedAt: string;
}

// PRODUCTION FIX: Normalize, deduplicate, and deterministically sort inputs by
// composite surrogate/natural key (warehouse_id, sku_id) in ascending order.
// Guarantees consistent global lock acquisition order across all concurrent transactions.
export async function syncInventorySafe(
  client: PoolClient,
  updates: InventoryUpdate[]
): Promise<void> {
  if (updates.length === 0) return;

  // Deterministic in-memory sort prior to SQL binding to reduce engine sorting overhead
  const sorted = [...updates].sort((a, b) => {
    const cmpWarehouse = a.warehouseId.localeCompare(b.warehouseId);
    return cmpWarehouse !== 0 ? cmpWarehouse : a.skuId.localeCompare(b.skuId);
  });

  const skus = sorted.map((u) => u.skuId);
  const warehouses = sorted.map((u) => u.warehouseId);
  const quantities = sorted.map((u) => u.quantity);
  const timestamps = sorted.map((u) => u.updatedAt);

  await client.query(
    `
    WITH ordered_source AS (
      SELECT 
        src.sku_id,
        src.warehouse_id,
        src.quantity,
        src.updated_at
      FROM UNNEST(
        $1::uuid[], 
        $2::uuid[], 
        $3::int[], 
        $4::timestamptz[]
      ) AS src(sku_id, warehouse_id, quantity, updated_at)
      ORDER BY src.warehouse_id ASC, src.sku_id ASC
    )
    MERGE INTO inventory AS target
    USING ordered_source AS source
    ON target.warehouse_id = source.warehouse_id AND target.sku_id = source.sku_id
    WHEN MATCHED THEN
      UPDATE SET 
        quantity = source.quantity,
        updated_at = source.updated_at
    WHEN NOT MATCHED THEN
      INSERT (warehouse_id, sku_id, quantity, updated_at)
      VALUES (source.warehouse_id, source.sku_id, source.quantity, source.updated_at)
    RETURNING merge_action(), target.warehouse_id, target.sku_id;
    `,
    [skus, warehouses, quantities, timestamps]
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard

Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict deterministic ordering on surrogate keys for all batch MERGE statements and their supporting Common Table Expressions (CTEs) in PostgreSQL 17. Unordered set processing across concurrent microservices causes interleaved tuple evaluation, triggering cyclic lock dependencies and fatal deadlocks (SQLSTATE 40P01). All batch inputs MUST be sorted by primary key prior to evaluation and locked in an ascending or uniform direction. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unordered Batch MERGE Ingestion Inducing Circular Lock Dependencies (Deadlock 40P01) Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnordered Batch MERGE Ingestion Inducing Circular Lock Dependencies (Deadlock 40P01)Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce deterministic row sorting (`ORDER BY target_pk ASC`) on source record sets or unnested array parameters feeding a `MERGE INTO` statement.

Engineers MUST ALWAYS enforce deterministic row sorting (`ORDER BY target_pk ASC`) on source record sets or unnested array parameters feeding a `MERGE INTO` statement.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT bind raw, unordered JSON arrays or UNNEST outputs directly to the source clause of a `MERGE` statement without an intermediate sorted Common Table Expression (CTE).

Engineers MUST NOT bind raw, unordered JSON arrays or UNNEST outputs directly to the source clause of a `MERGE` statement without an intermediate sorted Common Table Expression (CTE).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST execute batch mutations in small, bounded chunks (typically <= 1,000 tuples) to prevent lock table memory exhaustion and mitigate catastrophic transaction rollback penalties.

Services MUST execute batch mutations in small, bounded chunks (typically <= 1,000 tuples) to prevent lock table memory exhaustion and mitigate catastrophic transaction rollback penalties.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD leverage Postgres 17 `MERGE ... RETURNING` with deterministic ordering instead of legacy `INSERT ... ON CONFLICT DO UPDATE` when complex conditional branching across matched and not-matched sets is required.

Code SHOULD leverage Postgres 17 `MERGE ... RETURNING` with deterministic ordering instead of legacy `INSERT ... ON CONFLICT DO UPDATE` when complex conditional branching across matched and not-matched sets is required.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Engineers MUST ensure surrogate keys or natural unique keys referenced in the `ON` matching predicate are backed by a btree index to prevent table-scan-induced shared lock escalation across unmatched partitions.

Engineers MUST ensure surrogate keys or natural unique keys referenced in the `ON` matching predicate are backed by a btree index to prevent table-scan-induced shared lock escalation across unmatched partitions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Postgres 17 Concurrent MERGE Deterministic Row-Locking Standard critical for AI coding assistants?

Enforces strict deterministic ordering on surrogate keys for all batch MERGE statements and their supporting Common Table Expressions (CTEs) in PostgreSQL 17. Unordered set processing across concurrent microservices causes interleaved tuple evaluation, triggering cyclic lock dependencies and fatal deadlocks (SQLSTATE 40P01). All batch inputs MUST be sorted by primary key prior to evaluation and locked in an ascending or uniform direction. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unordered Batch MERGE Ingestion Inducing Circular Lock Dependencies (Deadlock 40P01)) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Postgres