This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: chromadb-06-hnsw-metadata-filtering-tenant-sharding

ChromaDB 0.6 HNSW Filter Optimization & Tenant-Isolated Sharding Guardrail

Enforces strict tenant isolation, optimal metadata indexing, and post-filter recall guarantees in ChromaDB 0.6+. Prevents catastrophic HNSW graph traversal exhaustion caused by pre-filtering high-cardinality multi-tenant workloads within a single global collection.

Prohibited Anti-Pattern: Global Single-Collection Multi-Tenancy with Inefficient Pre-Filtering Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: ChromaDB 0.6 HNSW Filter Optimization & Tenant-Isolated Sharding Guardrail - Enforces strict tenant isolation, optimal metadata indexing, and post-filter recall guarantees in ChromaDB 0.6+. Prevents catastrophic HNSW graph traversal exhaustion caused by pre-filtering high-cardinality multi-tenant workloads within a single global collection.
globs: src/lib/vectorstore/**/*.{ts,js,py}, src/services/embedding/**/*.{ts,js,py}, src/repositories/vector/**/*.{ts,js,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/chromadb-06-hnsw-metadata-filtering-tenant-sharding"
---

# ChromaDB 0.6 HNSW Filter Optimization & Tenant-Isolated Sharding Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Single-Collection Multi-Tenancy with Inefficient Pre-Filtering Exhaustion

## System Constraints
You are a Principal Backend and Vector Search Architect enforcing ChromaDB 0.6 HNSW Embedding Filtering. ChromaDB 0.6 introduces granular tenant/database level separation and updated HNSW configuration schemas. Mandate hard tenant isolation via ChromaDB tenants/databases or segregated collection namespaces rather than relying purely on top-level runtime $eq metadata filtering over billions of vectors. Ensure all collection metadata adheres to supported scalar types, HNSW construction parameters (hnsw:space, hnsw:construction_ef, hnsw:M) are explicitly calibrated for metadata-filtered queries, and queries guard against empty candidate sets caused by search_ef starvation.

## Strict Guidelines
- Services MUST route vector operations using ChromaDB 0.6 client-level tenant and database abstractions (`client.get_or_create_collection(..., tenant=tenant_id, database=db_name)`) or structured per-tenant collection naming prefixes (`tenant_${tenant_id}__${collection_name}`).
- Engineers MUST NOT rely on single shared collections with `{ tenant_id: { $eq: id } }` metadata filters when tenant vector populations exceed 50,000 vectors, as HNSW graph traversals will exhaust candidate pools resulting in truncated recall.
- Collections MUST explicitly define HNSW space (`hnsw:space`: `cosine` | `l2` | `ip`) and query search depths (`hnsw:search_ef`) scaled proportionally to the selectivity of runtime metadata filters.
- Metadata filters MUST use strict, sanitized scalar values (string, integer, float, boolean) wrapped in explicit boolean operator blocks (`$and`, `$or`) and NEVER pass undefined, null, or empty string values into `$in` or `$eq` filters.
- Engineers MUST configure idempotent collection creation with explicit `metadata: { 'hnsw:M': 32, 'hnsw:construction_ef': 128 }` to prevent graph fragmentation during concurrent batch writes.

## Bad vs Good Implementations
### Tenant Sharding and HNSW Metadata-Aware Querying

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Querying a single shared collection using metadata filtering for multi-tenancy causes ChromaDB's HNSW index to prune relevant branches early (HNSW filter starvation), degrading query recall to near zero. Furthermore, a faulty filter clause risks leaking data across tenants.
```typescript
import { ChromaClient } from 'chromadb';

const client = new ChromaClient();

export async function searchTenantDocuments(tenantId: string, queryEmbedding: number[], filterCategory?: string) {
  // Anti-pattern: Shared monolithic collection relying solely on metadata filtering
  // This leads to HNSW traversal starvation and vector leakage across tenant boundaries
  const collection = await client.getOrCreateCollection({ name: 'global_documents' });

  const whereClause: Record<string, any> = { tenant_id: tenantId };
  if (filterCategory) {
    whereClause['category'] = filterCategory;
  }

  return await collection.query({
    queryEmbeddings: [queryEmbedding],
    nResults: 10,
    where: whereClause
  });
}
```

#### Production Standard (Correct)
> **Standard**: Isolates tenants via deterministic collection namespacing and initializes HNSW indexes with explicit search/construction parameters. Eliminates tenant cross-talk and avoids graph starvation caused by global pre-filtering.
```typescript
import { ChromaClient, CollectionMetadata } from 'chromadb';

const client = new ChromaClient({ path: process.env.CHROMADB_URL });

const DEFAULT_HNSW_METADATA: CollectionMetadata = {
  'hnsw:space': 'cosine',
  'hnsw:construction_ef': 128,
  'hnsw:search_ef': 64,
  'hnsw:M': 32
};

export async function getTenantCollection(tenantId: string, collectionSlug: string) {
  // Secure physical/namespace isolation per tenant with calibrated HNSW metadata
  const sanitizedTenant = tenantId.replace(/[^a-zA-Z0-9_-]/g, '_');
  const namespacedName = `tenant_${sanitizedTenant}__${collectionSlug}`;

  return await client.getOrCreateCollection({
    name: namespacedName,
    metadata: DEFAULT_HNSW_METADATA
  });
}

export async function searchTenantDocuments(
  tenantId: string,
  collectionSlug: string,
  queryEmbedding: number[],
  filterCategory?: string
) {
  const collection = await getTenantCollection(tenantId, collectionSlug);

  const where = filterCategory
    ? { category: { $eq: filterCategory } }
    : undefined;

  return await collection.query({
    queryEmbeddings: [queryEmbedding],
    nResults: 10,
    where: where
  });
}
```

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: ChromaDB 0.6 HNSW Filter Optimization & Tenant-Isolated Sharding Guardrail

ChromaDB 0.6 HNSW Filter Optimization & Tenant-Isolated Sharding Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict tenant isolation, optimal metadata indexing, and post-filter recall guarantees in ChromaDB 0.6+. Prevents catastrophic HNSW graph traversal exhaustion caused by pre-filtering high-cardinality multi-tenant workloads within a single global collection. 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: Global Single-Collection Multi-Tenancy with Inefficient Pre-Filtering Exhaustion 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 DriftGlobal Single-Collection Multi-Tenancy with Inefficient Pre-Filtering ExhaustionCritical
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

Services MUST route vector operations using ChromaDB 0.6 client-level tenant and database abstractions (`client.get_or_create_collection(..., tenant=tenant_id, database=db_name)`) or structured per-tenant collection naming prefixes (`tenant_${tenant_id}__${collection_name}`).

Services MUST route vector operations using ChromaDB 0.6 client-level tenant and database abstractions (`client.get_or_create_collection(..., tenant=tenant_id, database=db_name)`) or structured per-tenant collection naming prefixes (`tenant_${tenant_id}__${collection_name}`).

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 rely on single shared collections with `{ tenant_id

Engineers MUST NOT rely on single shared collections with `{ tenant_id: { $eq: id } }` metadata filters when tenant vector populations exceed 50,000 vectors, as HNSW graph traversals will exhaust candidate pools resulting in truncated recall.

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

Collections MUST explicitly define HNSW space (`hnsw

Collections MUST explicitly define HNSW space (`hnsw:space`: `cosine` | `l2` | `ip`) and query search depths (`hnsw:search_ef`) scaled proportionally to the selectivity of runtime metadata filters.

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

Metadata filters MUST use strict, sanitized scalar values (string, integer, float, boolean) wrapped in explicit boolean operator blocks (`$and`, `$or`) and NEVER pass undefined, null, or empty string values into `$in` or `$eq` filters.

Metadata filters MUST use strict, sanitized scalar values (string, integer, float, boolean) wrapped in explicit boolean operator blocks (`$and`, `$or`) and NEVER pass undefined, null, or empty string values into `$in` or `$eq` filters.

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

Engineers MUST configure idempotent collection creation with explicit `metadata

Engineers MUST configure idempotent collection creation with explicit `metadata: { 'hnsw:M': 32, 'hnsw:construction_ef': 128 }` to prevent graph fragmentation during concurrent batch writes.

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 ChromaDB 0.6 HNSW Filter Optimization & Tenant-Isolated Sharding Guardrail critical for AI coding assistants?

Enforces strict tenant isolation, optimal metadata indexing, and post-filter recall guarantees in ChromaDB 0.6+. Prevents catastrophic HNSW graph traversal exhaustion caused by pre-filtering high-cardinality multi-tenant workloads within a single global collection. 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 (Global Single-Collection Multi-Tenancy with Inefficient Pre-Filtering Exhaustion) 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

ChromaDB