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

Postgres 17 pgvector HNSW Index Build Memory Fence and Graph Ceilings

Enforces session-scoped maintenance_work_mem bounds, explicit worker ceilings, and bounded graph connectivity (m, ef_construction) during concurrent pgvector HNSW index creation on PostgreSQL 17. Prevents Linux cgroup kernel OOM-killer invocations caused by parallel maintenance worker multiplicative memory allocation under concurrent write-heavy hybrid workloads.

Prohibited Anti-Pattern: Unbounded Global maintenance_work_mem with High Hyperparameters Triggering Parallel Worker Cgroup OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 pgvector HNSW Index Build Memory Fence and Graph Ceilings - Enforces session-scoped maintenance_work_mem bounds, explicit worker ceilings, and bounded graph connectivity (m, ef_construction) during concurrent pgvector HNSW index creation on PostgreSQL 17. Prevents Linux cgroup kernel OOM-killer invocations caused by parallel maintenance worker multiplicative memory allocation under concurrent write-heavy hybrid workloads.
globs: migrations/**/*.sql, prisma/migrations/**/*.sql, src/db/migrations/**/*.ts, src/infrastructure/database/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-pgvector-hnsw-memory-fence"
---

# Postgres 17 pgvector HNSW Index Build Memory Fence and Graph Ceilings

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Global maintenance_work_mem with High Hyperparameters Triggering Parallel Worker Cgroup OOM

## System Constraints
You are a Principal Database Reliability Architect enforcing Postgres 17 pgvector HNSW Index Build Memory Thrashing Fences. Mandate strict session-scoped allocation bounds for maintenance_work_mem, cap parallel maintenance workers to fit available container memory headroom, and constrain graph connectivity parameters (m, ef_construction) during CREATE INDEX CONCURRENTLY invocations to avoid OOM killer process termination.

## Strict Guidelines
- Engineers MUST ALWAYS isolate HNSW index creation using session-scoped `SET LOCAL maintenance_work_mem` rather than altering global cluster settings.
- Engineers MUST ALWAYS explicitly bound parallel worker multiplication such that `(max_parallel_maintenance_workers + 1) * maintenance_work_mem` does not exceed 40% of available container cgroup RAM.
- Engineers MUST ALWAYS execute pgvector index construction using `CREATE INDEX CONCURRENTLY` to prevent prolonged write locks and buffer cache starvation.
- Code MUST enforce graph connectivity ceilings of `m <= 32` and `ef_construction <= 128` during online migration windows, unless isolated on dedicated offline nodes with strict memory validation.
- Migrations MUST NOT execute HNSW index builds inside standard transactional blocks (`BEGIN ... COMMIT`) when using `CONCURRENTLY`.
- Database connection pooling configurations MUST NOT route long-running vector index builds through transaction-mode proxies like PgBouncer without session-level bypass mechanisms.

## Bad vs Good Implementations
### Safe Programmatic HNSW Migration with Worker and Memory Fencing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits CONCURRENTLY (locking all table writes), leaves maintenance_work_mem unmanaged against worker concurrency, and sets extreme m/ef_construction values. When PostgreSQL 17 spawns parallel workers, memory consumption multiplies beyond container limits, triggering Linux cgroup OOM-killer on the Postgres postmaster.
```typescript
import { Client } from 'pg';

export async function runMigration(client: Client): Promise<void> {
  // Anti-pattern: Default maintenance_work_mem, no worker ceiling, aggressive parameters
  // When max_parallel_maintenance_workers is default (e.g. 4), memory usage scales
  // multiplicatively: 5 workers * maintenance_work_mem, easily exceeding container RAM.
  await client.query(`
    CREATE INDEX idx_document_embeddings_hnsw
    ON document_embeddings USING hnsw (embedding vector_cosine_ops)
    WITH (m = 64, ef_construction = 256);
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Applies explicit worker bounds (`max_parallel_maintenance_workers = 2`), caps session memory (`maintenance_work_mem = '1GB'`), uses non-blocking `CREATE INDEX CONCURRENTLY`, and sets conservative graph hyperparameters (`m = 24, ef_construction = 100`), guaranteeing stable indexing without risking OOM aborts.
```typescript
import { Client } from 'pg';

export async function runMigration(client: Client): Promise<void> {
  // Invariant: CREATE INDEX CONCURRENTLY cannot run within an outer transaction block.
  // Bound maintenance memory strictly for this session based on container headroom.
  // Formula: (max_parallel_maintenance_workers + 1) * maintenance_work_mem <= 40% CGroup Memory Limit.
  
  await client.query('SET max_parallel_maintenance_workers = 2;');
  await client.query("SET maintenance_work_mem = '1GB';");

  try {
    await client.query(`
      CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_document_embeddings_hnsw
      ON document_embeddings USING hnsw (embedding vector_cosine_ops)
      WITH (
        m = 24,
        ef_construction = 100
      );
    `);
  } finally {
    // Reset session variables to connection pool defaults
    await client.query('RESET maintenance_work_mem;');
    await client.query('RESET max_parallel_maintenance_workers;');
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 pgvector HNSW Index Build Memory Fence and Graph Ceilings

Postgres 17 pgvector HNSW Index Build Memory Fence and Graph Ceilings defines an industrial-grade behavioral standard for backend engineering. Enforces session-scoped maintenance_work_mem bounds, explicit worker ceilings, and bounded graph connectivity (m, ef_construction) during concurrent pgvector HNSW index creation on PostgreSQL 17. Prevents Linux cgroup kernel OOM-killer invocations caused by parallel maintenance worker multiplicative memory allocation under concurrent write-heavy hybrid workloads. 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: Unbounded Global maintenance_work_mem with High Hyperparameters Triggering Parallel Worker Cgroup OOM 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 DriftUnbounded Global maintenance_work_mem with High Hyperparameters Triggering Parallel Worker Cgroup OOMCritical
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 isolate HNSW index creation using session-scoped `SET LOCAL maintenance_work_mem` rather than altering global cluster settings.

Engineers MUST ALWAYS isolate HNSW index creation using session-scoped `SET LOCAL maintenance_work_mem` rather than altering global cluster settings.

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 explicitly bound parallel worker multiplication such that `(max_parallel_maintenance_workers + 1) * maintenance_work_mem` does not exceed 40% of available container cgroup RAM.

Engineers MUST ALWAYS explicitly bound parallel worker multiplication such that `(max_parallel_maintenance_workers + 1) * maintenance_work_mem` does not exceed 40% of available container cgroup RAM.

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 pgvector index construction using `CREATE INDEX CONCURRENTLY` to prevent prolonged write locks and buffer cache starvation.

Engineers MUST ALWAYS execute pgvector index construction using `CREATE INDEX CONCURRENTLY` to prevent prolonged write locks and buffer cache starvation.

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 MUST enforce graph connectivity ceilings of `m <= 32` and `ef_construction <= 128` during online migration windows, unless isolated on dedicated offline nodes with strict memory validation.

Code MUST enforce graph connectivity ceilings of `m <= 32` and `ef_construction <= 128` during online migration windows, unless isolated on dedicated offline nodes with strict memory validation.

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

Migrations MUST NOT execute HNSW index builds inside standard transactional blocks (`BEGIN ... COMMIT`) when using `CONCURRENTLY`.

Migrations MUST NOT execute HNSW index builds inside standard transactional blocks (`BEGIN ... COMMIT`) when using `CONCURRENTLY`.

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

Database connection pooling configurations MUST NOT route long-running vector index builds through transaction-mode proxies like PgBouncer without session-level bypass mechanisms.

Database connection pooling configurations MUST NOT route long-running vector index builds through transaction-mode proxies like PgBouncer without session-level bypass mechanisms.

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 HNSW Index Build Memory Fence and Graph Ceilings critical for AI coding assistants?

Enforces session-scoped maintenance_work_mem bounds, explicit worker ceilings, and bounded graph connectivity (m, ef_construction) during concurrent pgvector HNSW index creation on PostgreSQL 17. Prevents Linux cgroup kernel OOM-killer invocations caused by parallel maintenance worker multiplicative memory allocation under concurrent write-heavy hybrid workloads. 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 (Unbounded Global maintenance_work_mem with High Hyperparameters Triggering Parallel Worker Cgroup OOM) 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