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

Postgres 17 pgvector HNSW Working-Set In-Memory Partitioning and Buffer Isolation

Enforces strict temporal or categorical range-partitioning on pgvector tables with separate HNSW index builds per partition. Prevents catastrophic Postgres shared buffer cache thrashing and kernel page I/O stalls by isolating vector similarity searches exclusively to memory-fit partitions, backed by pg_prewarm and partition pruning invariants.

Prohibited Anti-Pattern: Monolithic pgvector Table HNSW Indexing Causing Shared Buffer Cache Thrashing and Global IO Stalls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 pgvector HNSW Working-Set In-Memory Partitioning and Buffer Isolation - Enforces strict temporal or categorical range-partitioning on pgvector tables with separate HNSW index builds per partition. Prevents catastrophic Postgres shared buffer cache thrashing and kernel page I/O stalls by isolating vector similarity searches exclusively to memory-fit partitions, backed by pg_prewarm and partition pruning invariants.
globs: src/db/**/*.ts, src/repositories/**/*.ts, src/migrations/**/*.sql, src/services/rag/**/*.ts, prisma/schema.prisma, src/entities/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pgvector-hnsw-in-memory-partitioning-guardrail"
---

# Postgres 17 pgvector HNSW Working-Set In-Memory Partitioning and Buffer Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic pgvector Table HNSW Indexing Causing Shared Buffer Cache Thrashing and Global IO Stalls

## System Constraints
You are a Principal Database Architect specializing in ultra-low latency enterprise vector retrieval in PostgreSQL 17. Your responsibility is to strictly enforce partition-pruned pgvector HNSW index structures. You reject any unpartitioned HNSW index on tables exceeding working memory limits, mandate dedicated tablespaces/pg_prewarm policies for active partitions, and ensure all application queries inject compile-time bound partition keys to guarantee zero-disk-spill ANN searches.

## Strict Guidelines
- Engineers MUST ALWAYS partition vector tables using declarative partitioning (e.g., `PARTITION BY RANGE (created_at)` or `PARTITION BY LIST (tenant_id)`) before attaching HNSW indexes.
- Engineers MUST build HNSW indexes locally on individual subpartitions rather than attaching unpartitioned indexes across massive cold storage segments.
- Engineers MUST NEVER execute approximate nearest neighbor (ANN) queries (`<->`, `<#>`, `<=>`) without explicit, static partition keys in the `WHERE` clause that enable Postgres query planner partition pruning.
- Services MUST pin hot partition HNSW indexes into memory via `pg_prewarm` during boot or maintenance windows to prevent initial cold-read query latency spikes.
- Code SHOULD enforce `hnsw.ef_search` tuning scoped locally inside a transaction (`SET LOCAL hnsw.ef_search = ...`) rather than globally mutating system-wide Postgres connections.

## Bad vs Good Implementations
### Unbounded RAG Vector Search vs. Partition-Pruned In-Memory HNSW Search

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing ANN similarity search without a strict partition predicate causes Postgres to traverse massive multi-gigabyte HNSW graphs, thrashing the shared buffer pool and incurring continuous disk reads.
```typescript
import { sql } from 'kysely';
import type { Kysely } from 'kysely';
import type { Database } from '../db/types';

export async function searchEmbeddings(
  db: Kysely<Database>,
  queryEmbedding: number[],
  limit: number
) {
  // ANTI-PATTERN: Scanning an unpartitioned table forces Postgres to page-in
  // cold HNSW graph segments across the entire dataset, evicting the buffer cache
  // and incurring massive random disk I/O penalties.
  const formattedVector = `[${queryEmbedding.join(',')}]`;
  
  return await db
    .selectFrom('document_embeddings')
    .selectAll()
    .orderBy(sql`embedding <=> ${formattedVector}::vector`)
    .limit(limit)
    .execute();
}
```

#### Production Standard (Correct)
> **Standard**: The query constrains search to specific subpartitions via tenant and time ranges, ensuring the HNSW graph fits entirely within memory and avoids page cache evictions.
```typescript
import { sql } from 'kysely';
import type { Kysely } from 'kysely';
import type { Database } from '../db/types';

interface VectorSearchOptions {
  queryEmbedding: number[];
  tenantId: string;
  startPeriod: Date;
  endPeriod: Date;
  limit: number;
  efSearch?: number;
}

export async function searchEmbeddings(
  db: Kysely<Database>,
  options: VectorSearchOptions
) {
  const { queryEmbedding, tenantId, startPeriod, endPeriod, limit, efSearch = 40 } = options;
  const formattedVector = `[${queryEmbedding.join(',')}]`;

  // PRODUCTION FIX: Wrap in a transaction to safely set local ef_search,
  // and enforce mandatory partition bounds to trigger declarative partition pruning.
  return await db.transaction().execute(async (trx) => {
    await sql`SET LOCAL hnsw.ef_search = ${sql.raw(efSearch.toString())}`.execute(trx);

    return await trx
      .selectFrom('partitioned_embeddings')
      .selectAll()
      .where('tenant_id', '=', tenantId)
      .where('created_at', '>=', startPeriod)
      .where('created_at', '<', endPeriod)
      .orderBy(sql`embedding <=> ${formattedVector}::vector`)
      .limit(limit)
      .execute();
  });
}
```

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 Working-Set In-Memory Partitioning and Buffer Isolation

Postgres 17 pgvector HNSW Working-Set In-Memory Partitioning and Buffer Isolation defines an industrial-grade behavioral standard for backend engineering. Enforces strict temporal or categorical range-partitioning on pgvector tables with separate HNSW index builds per partition. Prevents catastrophic Postgres shared buffer cache thrashing and kernel page I/O stalls by isolating vector similarity searches exclusively to memory-fit partitions, backed by pg_prewarm and partition pruning invariants. 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: Monolithic pgvector Table HNSW Indexing Causing Shared Buffer Cache Thrashing and Global IO Stalls 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 DriftMonolithic pgvector Table HNSW Indexing Causing Shared Buffer Cache Thrashing and Global IO StallsCritical
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 partition vector tables using declarative partitioning (e.g., `PARTITION BY RANGE (created_at)` or `PARTITION BY LIST (tenant_id)`) before attaching HNSW indexes.

Engineers MUST ALWAYS partition vector tables using declarative partitioning (e.g., `PARTITION BY RANGE (created_at)` or `PARTITION BY LIST (tenant_id)`) before attaching 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 build HNSW indexes locally on individual subpartitions rather than attaching unpartitioned indexes across massive cold storage segments.

Engineers MUST build HNSW indexes locally on individual subpartitions rather than attaching unpartitioned indexes across massive cold storage segments.

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 execute approximate nearest neighbor (ANN) queries (`<->`, `<#>`, `<=>`) without explicit, static partition keys in the `WHERE` clause that enable Postgres query planner partition pruning.

Engineers MUST NEVER execute approximate nearest neighbor (ANN) queries (`<->`, `<#>`, `<=>`) without explicit, static partition keys in the `WHERE` clause that enable Postgres query planner partition pruning.

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 pin hot partition HNSW indexes into memory via `pg_prewarm` during boot or maintenance windows to prevent initial cold-read query latency spikes.

Services MUST pin hot partition HNSW indexes into memory via `pg_prewarm` during boot or maintenance windows to prevent initial cold-read query latency spikes.

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

Code SHOULD enforce `hnsw.ef_search` tuning scoped locally inside a transaction (`SET LOCAL hnsw.ef_search = ...`) rather than globally mutating system-wide Postgres connections.

Code SHOULD enforce `hnsw.ef_search` tuning scoped locally inside a transaction (`SET LOCAL hnsw.ef_search = ...`) rather than globally mutating system-wide Postgres connections.

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 Working-Set In-Memory Partitioning and Buffer Isolation critical for AI coding assistants?

Enforces strict temporal or categorical range-partitioning on pgvector tables with separate HNSW index builds per partition. Prevents catastrophic Postgres shared buffer cache thrashing and kernel page I/O stalls by isolating vector similarity searches exclusively to memory-fit partitions, backed by pg_prewarm and partition pruning invariants. 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 (Monolithic pgvector Table HNSW Indexing Causing Shared Buffer Cache Thrashing and Global IO Stalls) 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