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

Postgres 17 pgvector HNSW Concurrency & Autovacuum Budgeting Guardrails

Enforces deterministic table-level autovacuum budgeting, transaction batching, and resource isolation for pgvector HNSW indexes in PostgreSQL 17. Prevents OOM kills, index bloat, and catastrophic p99 vector search latency degradation caused by unthrottled concurrent inserts and autovacuum worker resource starvation.

Prohibited Anti-Pattern: Default Autovacuum Settings with Unbounded Concurrent Inserts on HNSW Vector Tables

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 pgvector HNSW Concurrency & Autovacuum Budgeting Guardrails - Enforces deterministic table-level autovacuum budgeting, transaction batching, and resource isolation for pgvector HNSW indexes in PostgreSQL 17. Prevents OOM kills, index bloat, and catastrophic p99 vector search latency degradation caused by unthrottled concurrent inserts and autovacuum worker resource starvation.
globs: src/**/*.ts, migrations/**/*.sql, src/db/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-hnsw-concurrency-autovacuum-guardrails"
---

# Postgres 17 pgvector HNSW Concurrency & Autovacuum Budgeting Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Default Autovacuum Settings with Unbounded Concurrent Inserts on HNSW Vector Tables

## System Constraints
You are a Principal Database Architect and Infrastructure Engineer enforcing PostgreSQL 17 and pgvector HNSW indexing reliability. High-throughput insertion of high-dimensional embeddings generates immense WAL traffic and graph rebalancing overhead. You must mandate table-level autovacuum cost tuning, strict insertion batching, and isolated connection-level search parameters to prevent vacuum starvation and query latency collapse.

## Strict Guidelines
- Engineers MUST ALWAYS configure dedicated table-level autovacuum parameters (`autovacuum_vacuum_cost_limit`, `autovacuum_vacuum_cost_delay`, `autovacuum_vacuum_scale_factor`) on tables hosting pgvector HNSW indexes.
- Engineers MUST NOT execute singleton `INSERT` statements for high-dimensional embeddings under production load; ingestion MUST be chunked into micro-batches (e.g., 250-1,000 vectors) to avoid transaction lock amplification and unconstrained WAL bursts.
- Engineers MUST NEVER globally raise `maintenance_work_mem` across all sessions to accommodate index builds; vector index builds and manual maintenance MUST set `maintenance_work_mem` and `max_parallel_maintenance_workers` within a dedicated, isolated session.
- Code MUST set `hnsw.ef_search` at the session or transaction scope for vector retrieval rather than modifying global configuration, guaranteeing deterministic recall without bloating memory overhead for non-vector transactions.
- Migrations creating HNSW indexes MUST use `CONCURRENTLY` in production environments and supply explicit `m` and `ef_construction` values calibrated against available shared memory.

## Bad vs Good Implementations
### HNSW Table DDL and Ingestion Batching Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default autovacuum settings cannot keep pace with high-throughput HNSW index updates, leading to catastrophic dead-tuple bloat and degraded search recall. Single-row concurrent insertions saturate PostgreSQL's WAL and lock manager while rapidly starving background autovacuum workers.
```typescript
import { Pool } from 'pg';

const pool = new Pool();

// Anti-pattern: Creating HNSW index without storage parameters,
// and running unthrottled individual inserts concurrently.
export async function ingestEmbeddingsUnbounded(records: { id: string; embedding: number[] }[]) {
  // DDL with default global autovacuum allows HNSW bloat to degrade search p99
  await pool.query(`
    CREATE TABLE IF NOT EXISTS document_embeddings (
      id UUID PRIMARY KEY,
      embedding vector(1536)
    );
    CREATE INDEX IF NOT EXISTS doc_embed_idx ON document_embeddings USING hnsw (embedding vector_cosine_ops);
  `);

  // Unbounded concurrent single-row inserts trigger heavy lock contention and WAL saturation
  await Promise.all(
    records.map(record =>
      pool.query(
        'INSERT INTO document_embeddings (id, embedding) VALUES ($1, $2)',
        [record.id, JSON.stringify(record.embedding)]
      )
    )
  );
}
```

#### Production Standard (Correct)
> **Standard**: Configures table-level autovacuum cost budgets (`autovacuum_vacuum_cost_limit = 2000`, `scale_factor = 0.05`) to prevent vacuum starvation. Inserts vectors in deterministic micro-batches via unnesting, minimizing transaction overhead and graph rebalancing contention.
```typescript
import { Pool, PoolClient } from 'pg';

const pool = new Pool({ max: 20 });
const INGESTION_BATCH_SIZE = 500;

export async function applyOptimizedHnswSchema(client: PoolClient): Promise<void> {
  // Invariant: Enforce aggressive table-level autovacuum throttling and cost limits
  await client.query(`
    CREATE TABLE IF NOT EXISTS document_embeddings (
      id UUID PRIMARY KEY,
      embedding vector(1536) NOT NULL
    )
    WITH (
      autovacuum_vacuum_scale_factor = 0.05,
      autovacuum_vacuum_cost_limit = 2000,
      autovacuum_vacuum_cost_delay = 2
    );

    CREATE INDEX CONCURRENTLY IF NOT EXISTS doc_embed_hnsw_idx 
    ON document_embeddings 
    USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 128);
  `);
}

export async function ingestEmbeddingsChunked(
  records: Array<{ id: string; embedding: number[] }>
): Promise<void> {
  const client = await pool.connect();
  try {
    for (let i = 0; i < records.length; i += INGESTION_BATCH_SIZE) {
      const chunk = records.slice(i, i + INGESTION_BATCH_SIZE);
      const ids: string[] = [];
      const vectors: string[] = [];

      for (const item of chunk) {
        ids.push(item.id);
        vectors.push(`[${item.embedding.join(',')}]`);
      }

      await client.query('BEGIN');
      await client.query(
        `INSERT INTO document_embeddings (id, embedding)
         SELECT unnest($1::uuid[]), unnest($2::vector[])`,
        [ids, vectors]
      );
      await client.query('COMMIT');
    }
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}
```

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 HNSW Concurrency & Autovacuum Budgeting Guardrails

Postgres 17 pgvector HNSW Concurrency & Autovacuum Budgeting Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic table-level autovacuum budgeting, transaction batching, and resource isolation for pgvector HNSW indexes in PostgreSQL 17. Prevents OOM kills, index bloat, and catastrophic p99 vector search latency degradation caused by unthrottled concurrent inserts and autovacuum worker resource starvation. 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: Default Autovacuum Settings with Unbounded Concurrent Inserts on HNSW Vector Tables 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 DriftDefault Autovacuum Settings with Unbounded Concurrent Inserts on HNSW Vector TablesCritical
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 configure dedicated table-level autovacuum parameters (`autovacuum_vacuum_cost_limit`, `autovacuum_vacuum_cost_delay`, `autovacuum_vacuum_scale_factor`) on tables hosting pgvector HNSW indexes.

Engineers MUST ALWAYS configure dedicated table-level autovacuum parameters (`autovacuum_vacuum_cost_limit`, `autovacuum_vacuum_cost_delay`, `autovacuum_vacuum_scale_factor`) on tables hosting pgvector HNSW indexes.

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 singleton `INSERT` statements for high-dimensional embeddings under production load

Engineers MUST NOT execute singleton `INSERT` statements for high-dimensional embeddings under production load; ingestion MUST be chunked into micro-batches (e.g., 250-1,000 vectors) to avoid transaction lock amplification and unconstrained WAL bursts.

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 NEVER globally raise `maintenance_work_mem` across all sessions to accommodate index builds

Engineers MUST NEVER globally raise `maintenance_work_mem` across all sessions to accommodate index builds; vector index builds and manual maintenance MUST set `maintenance_work_mem` and `max_parallel_maintenance_workers` within a dedicated, isolated session.

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 set `hnsw.ef_search` at the session or transaction scope for vector retrieval rather than modifying global configuration, guaranteeing deterministic recall without bloating memory overhead for non-vector transactions.

Code MUST set `hnsw.ef_search` at the session or transaction scope for vector retrieval rather than modifying global configuration, guaranteeing deterministic recall without bloating memory overhead for non-vector 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.
5

Migrations creating HNSW indexes MUST use `CONCURRENTLY` in production environments and supply explicit `m` and `ef_construction` values calibrated against available shared memory.

Migrations creating HNSW indexes MUST use `CONCURRENTLY` in production environments and supply explicit `m` and `ef_construction` values calibrated against available shared memory.

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 Concurrency & Autovacuum Budgeting Guardrails critical for AI coding assistants?

Enforces deterministic table-level autovacuum budgeting, transaction batching, and resource isolation for pgvector HNSW indexes in PostgreSQL 17. Prevents OOM kills, index bloat, and catastrophic p99 vector search latency degradation caused by unthrottled concurrent inserts and autovacuum worker resource starvation. 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 (Default Autovacuum Settings with Unbounded Concurrent Inserts on HNSW Vector Tables) 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