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

Postgres 17 Partitioned HNSW Vector Memory Budget & Worker Concurrency Invariant

Enforces deterministic memory ceiling budgeting across maintenance_work_mem, max_parallel_maintenance_workers, and shared_buffers when indexing high-dimensional HNSW vectors across partitioned tables. Prevents fatal container cgroup OOM killer panics (SIGKILL) triggered by unthrottled concurrent partition DDL operations.

Prohibited Anti-Pattern: Parallel Partition Indexing with Uncapped maintenance_work_mem Triggering Host OOM Panics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Partitioned HNSW Vector Memory Budget & Worker Concurrency Invariant - Enforces deterministic memory ceiling budgeting across maintenance_work_mem, max_parallel_maintenance_workers, and shared_buffers when indexing high-dimensional HNSW vectors across partitioned tables. Prevents fatal container cgroup OOM killer panics (SIGKILL) triggered by unthrottled concurrent partition DDL operations.
globs: src/**/*.ts, migrations/**/*.ts, infra/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-hnsw-partition-memory-budget-invariant"
---

# Postgres 17 Partitioned HNSW Vector Memory Budget & Worker Concurrency Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Parallel Partition Indexing with Uncapped maintenance_work_mem Triggering Host OOM Panics

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing strict physical memory ceilings on Postgres 17 instances utilizing pgvector. Partitioned HNSW index generation executes parallelized vector graph construction requiring substantial working memory. You must ensure that migration scripts, connection pool configurations, and real-time index builders never allow aggregate worker memory (maintenance_work_mem * max_parallel_maintenance_workers * concurrent_jobs) plus shared_buffers to exceed 80% of the host or container cgroup limit. Reject any unthrottled Promise.all or concurrent partition DDL loops.

## Strict Guidelines
- Engineers MUST ALWAYS set 'SET LOCAL maintenance_work_mem' explicitly within the dedicated indexing transaction, dynamically derived from available cgroup headrooms.
- Engineers MUST NOT execute HNSW index builds across multiple partitions concurrently using unthrottled worker pools or unrestricted Promise.all constructs.
- Code SHOULD clamp 'max_parallel_maintenance_workers' to safe bounds (typically 2-4) per partition build, ensuring (workers * maintenance_work_mem) remains strictly under host safety thresholds.
- Services MUST serialize partition index generation or gate concurrent partition builds through a concurrency semaphore of at most 1 to 2 workers depending on total system RAM.
- Components NEVER execute raw 'CREATE INDEX CONCURRENTLY' on partitioned vector tables without verifying that the cumulative memory footprint cannot exceed (Total RAM - shared_buffers - OS Overhead).

## Bad vs Good Implementations
### Partitioned HNSW Indexing Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executes concurrent partition index builds in parallel. If maintenance_work_mem is set to 2GB and max_parallel_maintenance_workers is 4, indexing 5 partitions simultaneously can demand over 40GB of resident memory, causing Linux OOM killer invocation and hard database termination.
```typescript
import { Pool } from 'pg';

export async function indexVectorPartitionsBad(pool: Pool, partitionNames: string[]) {
  // Anti-pattern: Unbounded concurrency and relying on default global maintenance_work_mem
  // When multiple partitions build HNSW graphs simultaneously, aggregate memory breaches
  // cgroup limits, causing the OS OOM killer to terminate the postmaster.
  await Promise.all(
    partitionNames.map(async (partition) => {
      const client = await pool.connect();
      try {
        await client.query(`
          CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_${partition}_embedding 
          ON ${partition} USING hnsw (embedding vector_cosine_ops)
          WITH (m = 16, ef_construction = 64);
        `);
      } finally {
        client.release();
      }
    })
  );
}
```

#### Production Standard (Correct)
> **Standard**: Enforces serialized partition indexing with scoped, bounded session parameters. Dynamically calculates maintenance_work_mem based on container physical headroom and explicit worker counts, guaranteeing deterministic memory consumption well beneath OOM thresholds.
```typescript
import { Pool, PoolClient } from 'pg';

interface MemoryBudgetConfig {
  totalContainerMemoryMb: number;
  sharedBuffersMb: number;
  safetyMarginRatio?: number;
  parallelWorkersPerIndex?: number;
}

export async function indexVectorPartitionsSafe(
  pool: Pool,
  partitionNames: string[],
  config: MemoryBudgetConfig
): Promise<void> {
  const safetyRatio = config.safetyMarginRatio ?? 0.8;
  const maxWorkers = config.parallelWorkersPerIndex ?? 2;
  
  // Calculate strictly bounded maintenance_work_mem
  // Invariant: (maintenance_work_mem * (workers + 1)) + shared_buffers <= Total * safetyRatio
  const safeBudgetMb = (config.totalContainerMemoryMb * safetyRatio) - config.sharedBuffersMb;
  const maintenanceWorkMemMb = Math.max(64, Math.floor(safeBudgetMb / (maxWorkers + 1)));

  // Serially process partitions to enforce deterministic memory isolation
  for (const partition of partitionNames) {
    const client: PoolClient = await pool.connect();
    try {
      await client.query('BEGIN');
      await client.query(`SET LOCAL maintenance_work_mem = '${maintenanceWorkMemMb}MB'`);
      await client.query(`SET LOCAL max_parallel_maintenance_workers = ${maxWorkers}`);
      await client.query('COMMIT');

      await client.query(`
        CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_${partition}_embedding 
        ON ${partition} USING hnsw (embedding vector_cosine_ops)
        WITH (m = 16, ef_construction = 64);
      `);
    } finally {
      client.release();
    }
  }
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Partitioned HNSW Vector Memory Budget & Worker Concurrency Invariant

Postgres 17 Partitioned HNSW Vector Memory Budget & Worker Concurrency Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic memory ceiling budgeting across maintenance_work_mem, max_parallel_maintenance_workers, and shared_buffers when indexing high-dimensional HNSW vectors across partitioned tables. Prevents fatal container cgroup OOM killer panics (SIGKILL) triggered by unthrottled concurrent partition DDL operations. 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: Parallel Partition Indexing with Uncapped maintenance_work_mem Triggering Host OOM Panics 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 DriftParallel Partition Indexing with Uncapped maintenance_work_mem Triggering Host OOM PanicsCritical
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 set 'SET LOCAL maintenance_work_mem' explicitly within the dedicated indexing transaction, dynamically derived from available cgroup headrooms.

Engineers MUST ALWAYS set 'SET LOCAL maintenance_work_mem' explicitly within the dedicated indexing transaction, dynamically derived from available cgroup headrooms.

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 execute HNSW index builds across multiple partitions concurrently using unthrottled worker pools or unrestricted Promise.all constructs.

Engineers MUST NOT execute HNSW index builds across multiple partitions concurrently using unthrottled worker pools or unrestricted Promise.all constructs.

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

Code SHOULD clamp 'max_parallel_maintenance_workers' to safe bounds (typically 2-4) per partition build, ensuring (workers * maintenance_work_mem) remains strictly under host safety thresholds.

Code SHOULD clamp 'max_parallel_maintenance_workers' to safe bounds (typically 2-4) per partition build, ensuring (workers * maintenance_work_mem) remains strictly under host safety thresholds.

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

Services MUST serialize partition index generation or gate concurrent partition builds through a concurrency semaphore of at most 1 to 2 workers depending on total system RAM.

Services MUST serialize partition index generation or gate concurrent partition builds through a concurrency semaphore of at most 1 to 2 workers depending on total system 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.
5

Components NEVER execute raw 'CREATE INDEX CONCURRENTLY' on partitioned vector tables without verifying that the cumulative memory footprint cannot exceed (Total RAM - shared_buffers - OS Overhead).

Components NEVER execute raw 'CREATE INDEX CONCURRENTLY' on partitioned vector tables without verifying that the cumulative memory footprint cannot exceed (Total RAM - shared_buffers - OS Overhead).

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 Partitioned HNSW Vector Memory Budget & Worker Concurrency Invariant critical for AI coding assistants?

Enforces deterministic memory ceiling budgeting across maintenance_work_mem, max_parallel_maintenance_workers, and shared_buffers when indexing high-dimensional HNSW vectors across partitioned tables. Prevents fatal container cgroup OOM killer panics (SIGKILL) triggered by unthrottled concurrent partition DDL operations. 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 (Parallel Partition Indexing with Uncapped maintenance_work_mem Triggering Host OOM Panics) 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