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

pgvector 0.8 HNSW Iterative Scan Bounded Multi-Tenant RLS Isolation

Mandates explicit iterative scan configuration (hnsw.iterative_scan and hnsw.max_scan_tuples) and tenant partitioning bounds when performing approximate nearest-neighbor searches under Row-Level Security (RLS). Prevents post-filtering graph starvation, unbounded index traversal latency spikes, and silent query truncation in multi-tenant vector workloads.

Prohibited Anti-Pattern: Executing unconstrained HNSW vector queries against RLS-protected tables without iterative scan tuning and tuple traversal budgets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: pgvector 0.8 HNSW Iterative Scan Bounded Multi-Tenant RLS Isolation - Mandates explicit iterative scan configuration (hnsw.iterative_scan and hnsw.max_scan_tuples) and tenant partitioning bounds when performing approximate nearest-neighbor searches under Row-Level Security (RLS). Prevents post-filtering graph starvation, unbounded index traversal latency spikes, and silent query truncation in multi-tenant vector workloads.
globs: src/db/**/*.ts, src/repositories/**/*.ts, src/services/**/*.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pgvector-hnsw-iterative-scan-rls-guardrail"
---

# pgvector 0.8 HNSW Iterative Scan Bounded Multi-Tenant RLS Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing unconstrained HNSW vector queries against RLS-protected tables without iterative scan tuning and tuple traversal budgets

## System Constraints
You are a Principal Database Architect enforcing pgvector 0.8+ HNSW query invariants. In multi-tenant environments using PostgreSQL Row-Level Security (RLS), naive vector search retrieves ef_search candidates globally before applying RLS post-filtering. This causes graph starvation (returning fewer than LIMIT k results) or severe latency degradation. You must mandate pgvector 0.8 iterative scan controls ('relaxed' or 'strict') bounded by hnsw.max_scan_tuples and strict transaction-scoped statement timeouts.

## Strict Guidelines
- Engineers MUST ALWAYS configure 'SET LOCAL hnsw.iterative_scan = relaxed' (or 'strict') inside transactions querying RLS-protected vector tables in pgvector 0.8+.
- Engineers MUST ALWAYS set an explicit 'SET LOCAL hnsw.max_scan_tuples' traversal budget (e.g., 20000) to cap CPU consumption during sparse candidate traversal.
- Engineers MUST NOT rely on default PostgreSQL HNSW global index traversal when multi-tenant RLS filters select less than 10% of total table rows without iterative scan enabled.
- Code SHOULD enforce partition-pruned table architectures (e.g., declarative partitioning by tenant_id) when individual tenant sizes exceed 1,000,000 vectors to bypass cross-tenant HNSW graph traversal entirely.
- Services MUST enforce strict transaction-level statement timeouts (e.g., 'SET LOCAL statement_timeout = 250') around vector searches to guarantee deterministic bounded latency.

## Bad vs Good Implementations
### Tenant Vector Search with Iterative Scan Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default HNSW search traverses a fixed global candidate pool. When RLS discards non-matching tenant records, the query frequently starves the result set or triggers unbounded fallback scans without explicit pgvector 0.8 iterative scan bounds, resulting in severe latency spikes and degraded recall.
```typescript
import { Pool } from 'pg';

export async function searchTenantEmbeddings(
  pool: Pool,
  tenantId: string,
  queryEmbedding: number[],
  limit: number
) {
  // Anti-pattern: Relies on default HNSW traversal under RLS.
  // If tenant has low density in the global index, ef_search candidates
  // get filtered out by RLS post-filter, returning 0 or partial results,
  // or causing severe index traversal penalties without bounds.
  const client = await pool.connect();
  try {
    await client.query('SET app.current_tenant_id = $1', [tenantId]);
    const result = await client.query(
      `SELECT id, content, 1 - (embedding <=> $1::vector) AS similarity
       FROM document_embeddings
       ORDER BY embedding <=> $1::vector
       LIMIT $2`,
      [JSON.stringify(queryEmbedding), limit]
    );
    return result.rows;
  } finally {
    client.release();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Enables pgvector 0.8 iterative scanning (`relaxed`) with an explicit tuple traversal budget (`hnsw.max_scan_tuples = 20000`) and a defensive statement timeout within an atomic transaction. This guarantees full recall up to the limit while strictly capping query latency and CPU saturation.
```typescript
import { Pool } from 'pg';

interface VectorSearchResult {
  id: string;
  content: string;
  similarity: number;
}

export async function searchTenantEmbeddings(
  pool: Pool,
  tenantId: string,
  queryEmbedding: number[],
  limit: number
): Promise<VectorSearchResult[]> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Establish RLS tenant context
    await client.query('SET LOCAL app.current_tenant_id = $1', [tenantId]);

    // Bound latency and activate pgvector 0.8 iterative index scan
    await client.query("SET LOCAL statement_timeout = '250ms'");
    await client.query("SET LOCAL hnsw.iterative_scan = 'relaxed'");
    await client.query('SET LOCAL hnsw.max_scan_tuples = 20000');
    await client.query('SET LOCAL hnsw.ef_search = 100');

    const embeddingLiteral = JSON.stringify(queryEmbedding);
    const result = await client.query<VectorSearchResult>(
      `SELECT id, content, 1 - (embedding <=> $1::vector) AS similarity
       FROM document_embeddings
       WHERE tenant_id = current_setting('app.current_tenant_id')::uuid
       ORDER BY embedding <=> $1::vector
       LIMIT $2`,
      [embeddingLiteral, limit]
    );

    await client.query('COMMIT');
    return result.rows;
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: pgvector 0.8 HNSW Iterative Scan Bounded Multi-Tenant RLS Isolation

pgvector 0.8 HNSW Iterative Scan Bounded Multi-Tenant RLS Isolation defines an industrial-grade behavioral standard for backend engineering. Mandates explicit iterative scan configuration (hnsw.iterative_scan and hnsw.max_scan_tuples) and tenant partitioning bounds when performing approximate nearest-neighbor searches under Row-Level Security (RLS). Prevents post-filtering graph starvation, unbounded index traversal latency spikes, and silent query truncation in multi-tenant vector 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: Executing unconstrained HNSW vector queries against RLS-protected tables without iterative scan tuning and tuple traversal budgets 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 DriftExecuting unconstrained HNSW vector queries against RLS-protected tables without iterative scan tuning and tuple traversal budgetsCritical
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 'SET LOCAL hnsw.iterative_scan = relaxed' (or 'strict') inside transactions querying RLS-protected vector tables in pgvector 0.8+.

Engineers MUST ALWAYS configure 'SET LOCAL hnsw.iterative_scan = relaxed' (or 'strict') inside transactions querying RLS-protected vector tables in pgvector 0.8+.

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 set an explicit 'SET LOCAL hnsw.max_scan_tuples' traversal budget (e.g., 20000) to cap CPU consumption during sparse candidate traversal.

Engineers MUST ALWAYS set an explicit 'SET LOCAL hnsw.max_scan_tuples' traversal budget (e.g., 20000) to cap CPU consumption during sparse candidate traversal.

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 NOT rely on default PostgreSQL HNSW global index traversal when multi-tenant RLS filters select less than 10% of total table rows without iterative scan enabled.

Engineers MUST NOT rely on default PostgreSQL HNSW global index traversal when multi-tenant RLS filters select less than 10% of total table rows without iterative scan enabled.

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 SHOULD enforce partition-pruned table architectures (e.g., declarative partitioning by tenant_id) when individual tenant sizes exceed 1,000,000 vectors to bypass cross-tenant HNSW graph traversal entirely.

Code SHOULD enforce partition-pruned table architectures (e.g., declarative partitioning by tenant_id) when individual tenant sizes exceed 1,000,000 vectors to bypass cross-tenant HNSW graph traversal entirely.

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

Services MUST enforce strict transaction-level statement timeouts (e.g., 'SET LOCAL statement_timeout = 250') around vector searches to guarantee deterministic bounded latency.

Services MUST enforce strict transaction-level statement timeouts (e.g., 'SET LOCAL statement_timeout = 250') around vector searches to guarantee deterministic bounded latency.

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 pgvector 0.8 HNSW Iterative Scan Bounded Multi-Tenant RLS Isolation critical for AI coding assistants?

Mandates explicit iterative scan configuration (hnsw.iterative_scan and hnsw.max_scan_tuples) and tenant partitioning bounds when performing approximate nearest-neighbor searches under Row-Level Security (RLS). Prevents post-filtering graph starvation, unbounded index traversal latency spikes, and silent query truncation in multi-tenant vector 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 (Executing unconstrained HNSW vector queries against RLS-protected tables without iterative scan tuning and tuple traversal budgets) 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

pgvector