This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgresql-advisory-locks-concurrency

PostgreSQL Application-Level Advisory Locks & Distributed Race Protection

Production concurrency standard for PostgreSQL database operations. Mandates using transaction-scoped advisory locks (pg_advisory_xact_lock) or session-scoped locks for serializing critical operations (billing, credit grants, sequential invoice numbering), eliminating table-level locking bottlenecks and race conditions.

Prohibited Anti-Pattern: AI executes read-then-write logic without advisory locks or uses SELECT FOR UPDATE on high-traffic tables, causing database deadlocks and double-spending races.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL Application-Level Advisory Locks & Distributed Race Protection - Production concurrency standard for PostgreSQL database operations. Mandates using transaction-scoped advisory locks (pg_advisory_xact_lock) or session-scoped locks for serializing critical operations (billing, credit grants, sequential invoice numbering), eliminating table-level locking bottlenecks and race conditions.
globs: **/*.sql, **/repository/**/*.ts, **/services/**/*.py, **/models/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgresql-advisory-locks-concurrency"
---

# PostgreSQL Application-Level Advisory Locks & Distributed Race Protection

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI executes read-then-write logic without advisory locks or uses SELECT FOR UPDATE on high-traffic tables, causing database deadlocks and double-spending races.

## System Constraints
You are a PostgreSQL High-Concurrency Database Architect. When serializing business operations (such as credit allocation, wallet updates, or unique reference allocation) across distributed API workers, DO NOT lock entire tables with LOCK TABLE and DO NOT rely on un-isolated SELECT followed by UPDATE. Use transaction-scoped advisory locks: pg_advisory_xact_lock(hashtext('entity:' || id)).

## Strict Guidelines
- MUST use pg_advisory_xact_lock() inside a transaction for automatic lock release upon COMMIT or ROLLBACK.
- MUST hash string keys into 64-bit integers using hashtext() or hashtext64() for stable lock namespaces.
- MUST NOT use session-level pg_advisory_lock() without an explicit guaranteed defer/finally pg_advisory_unlock() call (avoids orphaned locks in connection pools).
- SHOULD use pg_try_advisory_xact_lock() when non-blocking immediate rejection is required on concurrent job runs.
- MUST establish consistent lock ordering across multiple entities to eliminate reciprocal deadlocks.

## Bad vs Good Implementations
### Serializing Wallet Credits with Transaction Advisory Locks in TypeScript & SQL

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Concurrent requests interleave between the SELECT and UPDATE queries, overwriting balance increments and resulting in severe accounting discrepancies.
```typescript
// FATAL: Read-then-write race condition allowing concurrent double-spending
async function grantCredits(userId: string, amount: number) {
  const user = await db.query('SELECT credits FROM users WHERE id = $1', [userId]);
  // RACE: Two concurrent API calls read the same initial credits at the same microsecond!
  const updated = user.credits + amount;
  await db.query('UPDATE users SET credits = $1 WHERE id = $2', [updated, userId]);
}
```

#### Production Standard (Correct)
> **Standard**: Acquires a transaction-level advisory lock on the specific user entity. Concurrent workers queue cleanly for milliseconds without deadlocking or locking unrelated user rows.
```typescript
async function grantCreditsSafe(userId: string, amount: number) {
  return await db.transaction(async (tx) => {
    // 1. Transaction-scoped advisory lock on hashed user ID namespace
    // Automatically released when the transaction completes (commit or error)
    await tx.query(
      'SELECT pg_advisory_xact_lock(hashtext($1))',
      [`wallet:${userId}`]
    );

    // 2. Safe isolated read & atomic atomic credit increment
    const result = await tx.query(
      'UPDATE users SET credits = credits + $1 WHERE id = $2 RETURNING credits',
      [amount, userId]
    );
    return result.rows[0].credits;
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL Application-Level Advisory Locks & Distributed Race Protection

PostgreSQL Application-Level Advisory Locks & Distributed Race Protection defines an industrial-grade behavioral standard for backend engineering. Production concurrency standard for PostgreSQL database operations. Mandates using transaction-scoped advisory locks (pg_advisory_xact_lock) or session-scoped locks for serializing critical operations (billing, credit grants, sequential invoice numbering), eliminating table-level locking bottlenecks and race conditions. 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: AI executes read-then-write logic without advisory locks or uses SELECT FOR UPDATE on high-traffic tables, causing database deadlocks and double-spending races. 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 DriftAI executes read-then-write logic without advisory locks or uses SELECT FOR UPDATE on high-traffic tables, causing database deadlocks and double-spending races.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

MUST use pg_advisory_xact_lock() inside a transaction for automatic lock release upon COMMIT or ROLLBACK.

MUST use pg_advisory_xact_lock() inside a transaction for automatic lock release upon COMMIT or ROLLBACK.

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

MUST hash string keys into 64-bit integers using hashtext() or hashtext64() for stable lock namespaces.

MUST hash string keys into 64-bit integers using hashtext() or hashtext64() for stable lock namespaces.

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

MUST NOT use session-level pg_advisory_lock() without an explicit guaranteed defer/finally pg_advisory_unlock() call (avoids orphaned locks in connection pools).

MUST NOT use session-level pg_advisory_lock() without an explicit guaranteed defer/finally pg_advisory_unlock() call (avoids orphaned locks in connection pools).

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

SHOULD use pg_try_advisory_xact_lock() when non-blocking immediate rejection is required on concurrent job runs.

SHOULD use pg_try_advisory_xact_lock() when non-blocking immediate rejection is required on concurrent job runs.

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

MUST establish consistent lock ordering across multiple entities to eliminate reciprocal deadlocks.

MUST establish consistent lock ordering across multiple entities to eliminate reciprocal deadlocks.

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 PostgreSQL Application-Level Advisory Locks & Distributed Race Protection critical for AI coding assistants?

Production concurrency standard for PostgreSQL database operations. Mandates using transaction-scoped advisory locks (pg_advisory_xact_lock) or session-scoped locks for serializing critical operations (billing, credit grants, sequential invoice numbering), eliminating table-level locking bottlenecks and race conditions. 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 (AI executes read-then-write logic without advisory locks or uses SELECT FOR UPDATE on high-traffic tables, causing database deadlocks and double-spending races.) 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

PostgreSQL