This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-pgvector-parallel-hnsw-memory-pinning

Postgres 17 pgvector Parallel HNSW Index Build Memory Pinning Standard

Governs session-scoped maintenance_work_mem sizing and max_parallel_maintenance_workers allocation during parallel HNSW vector index builds in Postgres 17. Enforces strict aggregate memory safety invariants to prevent Out-Of-Memory (OOM) Linux kernel cgroup terminations on active transactional primaries. Mandates CONCURRENTLY index construction alongside ephemeral per-session GUC resets and query cancellation timeouts.

Prohibited Anti-Pattern: Global maintenance_work_mem Oversubscription Spawning Unconstrained Parallel HNSW Worker OOM Evictions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 pgvector Parallel HNSW Index Build Memory Pinning Standard - Governs session-scoped maintenance_work_mem sizing and max_parallel_maintenance_workers allocation during parallel HNSW vector index builds in Postgres 17. Enforces strict aggregate memory safety invariants to prevent Out-Of-Memory (OOM) Linux kernel cgroup terminations on active transactional primaries. Mandates CONCURRENTLY index construction alongside ephemeral per-session GUC resets and query cancellation timeouts.
globs: src/database/migrations/**/*.ts, src/database/scripts/**/*.ts, src/infra/db/**/*.ts, src/jobs/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-pgvector-parallel-hnsw-memory-pinning"
---

# Postgres 17 pgvector Parallel HNSW Index Build Memory Pinning Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global maintenance_work_mem Oversubscription Spawning Unconstrained Parallel HNSW Worker OOM Evictions

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing Postgres 17 and pgvector (0.7.0+) production standards. Your directive is to guarantee that zero vector reindexing or index generation operations risk kernel OOM-killer invocations, transaction pool starvation, or replication lag amplification on live OLTP primary nodes. You mandate session-local configuration pinning, bounded parallel workers, lock timeouts, and safe memory arithmetic for HNSW index builds.

## Strict Guidelines
- Engineers MUST ALWAYS execute vector index generation using 'CREATE INDEX CONCURRENTLY' inside a standalone, dedicated migration or maintenance connection, completely outside any explicit multi-statement transaction blocks (BEGIN...COMMIT).
- Engineers MUST ALWAYS compute and explicitly set session-scoped 'maintenance_work_mem' using the formula: session_maintenance_work_mem <= (Free_OS_Memory - Shared_Buffers - (max_connections * work_mem)) / (max_parallel_maintenance_workers + 1).
- Engineers MUST ALWAYS execute 'SET LOCAL' or session-scoped 'SET' commands for 'maintenance_work_mem', 'max_parallel_maintenance_workers', and 'statement_timeout' immediately preceding the index DDL, followed by an explicit 'RESET' in a 'finally' block.
- Engineers MUST NOT mutate cluster-wide GUC parameters (e.g., 'ALTER SYSTEM SET maintenance_work_mem') to satisfy large vector indexing, as doing so exposes concurrent autovacuum and index rebuild tasks to aggregate OOM hazards.
- Engineers MUST explicitly cap 'max_parallel_maintenance_workers' to no more than min(Available_vCPUs / 2, 4) on live OLTP primary instances to prevent CPU starvation of concurrent read/write transactions.
- Code SHOULD verify the target pgvector version supports parallel index builds (pgvector >= 0.7.0 on Postgres 17) and query 'pg_stat_progress_create_index' to monitor phase progression rather than polling raw locks.
- Services MUST configure an explicit 'lock_timeout' (e.g., '5s') prior to 'CREATE INDEX CONCURRENTLY' to fail fast and avoid accumulating waiting exclusive locks behind long-running OLTP transactions.

## Bad vs Good Implementations
### Unsafe Global Memory Assumption and Blocking Vector Index Creation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing non-concurrent CREATE INDEX inside an explicit transaction holds an ExclusiveLock on the table, blocking incoming transactional queries. Altering system-wide maintenance_work_mem exposes all concurrent autovacuum workers to massive memory allocations, frequently triggering Linux OOM-killer terminations of the main postgres process. Unbounded parallel worker allocations saturate host vCPUs.
```typescript
import { Client } from 'pg';

export async function rebuildVectorIndex(client: Client): Promise<void> {
  // Anti-pattern: Modifying cluster-wide settings or assuming default maintenance memory is safe.
  // Fails to pin session workers, runs in a transaction block, and lacks concurrency safeguards.
  await client.query('BEGIN');
  await client.query('ALTER SYSTEM SET maintenance_work_mem = "16GB"');
  await client.query('SELECT pg_reload_conf()');

  // Blocks read/writes on the table and spawns unconstrained parallel workers leading to OOM
  await client.query(`
    CREATE INDEX idx_embeddings_hnsw ON document_embeddings 
    USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);
  `);
  await client.query('COMMIT');
}
```

#### Production Standard (Correct)
> **Standard**: Safely encapsulates memory and concurrency bounds within a dedicated session. By applying CREATE INDEX CONCURRENTLY outside any transaction block, OLTP read/write traffic remains unblocked. maintenance_work_mem is strictly partitioned and capped per worker, eliminating host OOM risks, while the finally block guarantees GUC cleanup on client reuse.
```typescript
import { Client } from 'pg';

interface HnswIndexConfig {
  readonly maxParallelWorkers: number;
  readonly sessionMaintenanceMemMb: number;
  readonly lockTimeoutMs: number;
}

export async function buildHnswIndexSafely(
  client: Client,
  config: HnswIndexConfig = {
    maxParallelWorkers: 2,
    sessionMaintenanceMemMb: 2048,
    lockTimeoutMs: 5000
  }
): Promise<void> {
  // Invariant: Concurrent indexing MUST NOT run in a multi-statement transaction.
  // Session GUCs must be explicitly isolated and restored to protect OLTP headroom.
  try {
    await client.query(`SET lock_timeout = '${config.lockTimeoutMs}ms'`);
    await client.query(`SET max_parallel_maintenance_workers = ${config.maxParallelWorkers}`);
    await client.query(`SET maintenance_work_mem = '${config.sessionMaintenanceMemMb}MB'`);

    await client.query(`
      CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_document_embeddings_hnsw
      ON document_embeddings
      USING hnsw (embedding vector_cosine_ops)
      WITH (m = 16, ef_construction = 64);
    `);
  } finally {
    // Always restore session settings even upon failure or statement cancellation
    await client.query('RESET lock_timeout');
    await client.query('RESET max_parallel_maintenance_workers');
    await client.query('RESET maintenance_work_mem');
  }
}
```

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: Postgres 17 pgvector Parallel HNSW Index Build Memory Pinning Standard

Postgres 17 pgvector Parallel HNSW Index Build Memory Pinning Standard defines an industrial-grade behavioral standard for backend engineering. Governs session-scoped maintenance_work_mem sizing and max_parallel_maintenance_workers allocation during parallel HNSW vector index builds in Postgres 17. Enforces strict aggregate memory safety invariants to prevent Out-Of-Memory (OOM) Linux kernel cgroup terminations on active transactional primaries. Mandates CONCURRENTLY index construction alongside ephemeral per-session GUC resets and query cancellation timeouts. 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: Global maintenance_work_mem Oversubscription Spawning Unconstrained Parallel HNSW Worker OOM Evictions 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 DriftGlobal maintenance_work_mem Oversubscription Spawning Unconstrained Parallel HNSW Worker OOM EvictionsCritical
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 execute vector index generation using 'CREATE INDEX CONCURRENTLY' inside a standalone, dedicated migration or maintenance connection, completely outside any explicit multi-statement transaction blocks (BEGIN...COMMIT).

Engineers MUST ALWAYS execute vector index generation using 'CREATE INDEX CONCURRENTLY' inside a standalone, dedicated migration or maintenance connection, completely outside any explicit multi-statement transaction blocks (BEGIN...COMMIT).

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 ALWAYS compute and explicitly set session-scoped 'maintenance_work_mem' using the formula

Engineers MUST ALWAYS compute and explicitly set session-scoped 'maintenance_work_mem' using the formula: session_maintenance_work_mem <= (Free_OS_Memory - Shared_Buffers - (max_connections * work_mem)) / (max_parallel_maintenance_workers + 1).

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

Engineers MUST ALWAYS execute 'SET LOCAL' or session-scoped 'SET' commands for 'maintenance_work_mem', 'max_parallel_maintenance_workers', and 'statement_timeout' immediately preceding the index DDL, followed by an explicit 'RESET' in a 'finally' block.

Engineers MUST ALWAYS execute 'SET LOCAL' or session-scoped 'SET' commands for 'maintenance_work_mem', 'max_parallel_maintenance_workers', and 'statement_timeout' immediately preceding the index DDL, followed by an explicit 'RESET' in a 'finally' block.

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

Engineers MUST NOT mutate cluster-wide GUC parameters (e.g., 'ALTER SYSTEM SET maintenance_work_mem') to satisfy large vector indexing, as doing so exposes concurrent autovacuum and index rebuild tasks to aggregate OOM hazards.

Engineers MUST NOT mutate cluster-wide GUC parameters (e.g., 'ALTER SYSTEM SET maintenance_work_mem') to satisfy large vector indexing, as doing so exposes concurrent autovacuum and index rebuild tasks to aggregate OOM hazards.

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 explicitly cap 'max_parallel_maintenance_workers' to no more than min(Available_vCPUs / 2, 4) on live OLTP primary instances to prevent CPU starvation of concurrent read/write transactions.

Engineers MUST explicitly cap 'max_parallel_maintenance_workers' to no more than min(Available_vCPUs / 2, 4) on live OLTP primary instances to prevent CPU starvation of concurrent read/write transactions.

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.
6

Code SHOULD verify the target pgvector version supports parallel index builds (pgvector >= 0.7.0 on Postgres 17) and query 'pg_stat_progress_create_index' to monitor phase progression rather than polling raw locks.

Code SHOULD verify the target pgvector version supports parallel index builds (pgvector >= 0.7.0 on Postgres 17) and query 'pg_stat_progress_create_index' to monitor phase progression rather than polling raw locks.

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.
7

Services MUST configure an explicit 'lock_timeout' (e.g., '5s') prior to 'CREATE INDEX CONCURRENTLY' to fail fast and avoid accumulating waiting exclusive locks behind long-running OLTP transactions.

Services MUST configure an explicit 'lock_timeout' (e.g., '5s') prior to 'CREATE INDEX CONCURRENTLY' to fail fast and avoid accumulating waiting exclusive locks behind long-running OLTP transactions.

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 pgvector Parallel HNSW Index Build Memory Pinning Standard critical for AI coding assistants?

Governs session-scoped maintenance_work_mem sizing and max_parallel_maintenance_workers allocation during parallel HNSW vector index builds in Postgres 17. Enforces strict aggregate memory safety invariants to prevent Out-Of-Memory (OOM) Linux kernel cgroup terminations on active transactional primaries. Mandates CONCURRENTLY index construction alongside ephemeral per-session GUC resets and query cancellation timeouts. 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 (Global maintenance_work_mem Oversubscription Spawning Unconstrained Parallel HNSW Worker OOM Evictions) 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