Vector database patterns

From FerroxLabs/wayland · View interactive version

Vector database patterns is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level vector database patterns implementation: ai-ml and database decision frameworks, production-ready patterns, and concrete templates for vector database patterns workflows. Use when the user asks about vector database patterns, vector database patterns configuration, or ai-ml best

How to use this skill

Skill file

Vector Database Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Characterize the Workload and Requirements

Before recommending any vector database or index configuration, gather concrete requirements:

2. Select the Vector Database Engine

Apply this decision framework based on requirements gathered in Step 1:

3. Choose and Configure the Index Algorithm

ANN algorithm selection is the highest-leverage configuration decision:

4. Design the Data Model and Schema

Poor schema design causes correctness bugs and performance cliffs that are expensive to fix post-deployment:

5. Build the Ingestion Pipeline

Ingestion errors silently corrupt the vector space and are hard to detect later:

6. Implement Query Patterns

Query implementation determines whether theoretical recall translates to actual retrieval quality:

7. Instrument, Monitor, and Evaluate

Vector database performance degrades silently as data distribution shifts -- monitoring is not optional:

8. Plan for Production Operations

Operational patterns prevent the most common production failures:


Output Format

For each vector database design engagement, produce the following structured output:

## Vector Database Design Document

### Requirements Summary
| Dimension          | Value                          | Source         |
|--------------------|-------------------------------|----------------|
| Corpus size        | e.g., 2.5M vectors            | Stated         |
| Dimensionality     | e.g., 1536 (text-embedding-3) | Stated         |
| Query latency SLA  | e.g., p95 < 75ms              | Stated         |
| Recall target      | e.g., recall@10 >= 0.95       | Stated/Default |
| Update pattern     | e.g., append-only, ~10K/day   | Stated         |
| Filter patterns    | e.g., tenant_id, date range   | Stated         |
| Scale horizon      | e.g., 3x in 18 months         | Estimated      |
| Deployment model   | e.g., self-hosted on K8s      | Stated         |

### Engine Selection
**Recommended:** [Engine name]
**Rationale:** [2--4 sentences explaining why this engine was selected over alternatives]
**Alternatives considered:**
- [Engine A]: Rejected because [specific reason]
- [Engine B]: Rejected because [specific reason]

### Index Configuration

Production index configuration

index_config = {

"index_type": "HNSW", # or IVF_HNSW, IVF_PQ, etc.

"metric_type": "COSINE", # or L2, IP

"params": {

"M": 16, # bidirectional link count

"ef_construction": 128, # build-time quality (set once)

}

}

search_params = {

"ef": 64, # query-time recall-speed tradeoff

# increase to 128 if recall < 0.95

}


### Schema Design

Collection/index schema

schema = {

"collection_name": "documents_v2",

"fields": [

{"name": "doc_id", "type": "VARCHAR(64)", "is_primary": True},

{"name": "embedding", "type": "FLOAT_VECTOR", "dim": 1536},

{"name": "tenant_id", "type": "VARCHAR(32)", "indexed": True},

{"name": "content_hash", "type": "VARCHAR(64)", "indexed": False},

{"name": "created_at", "type": "INT64", "indexed": True},

{"name": "chunk_index", "type": "INT16", "indexed": False},

]

}


### Ingestion Pipeline

async def ingest_documents(

documents: list[Document],

collection: VectorCollection,

embedding_client: EmbeddingClient,

batch_size: int = 500,

) -> IngestionResult:

"""

Idempotent ingestion with deduplication and retry.

Batches at batch_size to balance throughput and memory.

Skips documents whose content_hash already exists.

Retries embedding API calls with exponential backoff.

"""

results = IngestionResult()

for batch in chunk_list(documents, batch_size):

# Deduplication check

existing_hashes = await collection.get_existing_hashes(

[doc.content_hash for doc in batch]

)

new_docs = [d for d in batch if d.content_hash not in existing_hashes]

if not new_docs:

results.skipped += len(batch)

continue

# Embed with retry

embeddings = await embed_with_retry(

texts=[doc.text for doc in new_docs],

client=embedding_client,

max_retries=5,

initial_delay=1.0,

)

# Normalize for cosine similarity

embeddings = normalize_l2(embeddings)

# Upsert (overwrite on duplicate ID)

await collection.upsert(

ids=[doc.doc_id for doc in new_docs],

vectors=embeddings,

payloads=[doc.metadata for doc in new_docs],

)

results.inserted += len(new_docs)

return results


### Query Implementation

async def semantic_search(

query: str,

collection: VectorCollection,

embedding_client: EmbeddingClient,

top_k: int = 10,

filters: dict | None = None,

ef_search: int = 64,

) -> list[SearchResult]:

"""

Semantic search with optional pre-filtering.

Increases ef_search to 128 when filters reduce candidate

pool to < 20% of corpus to maintain recall target.

"""

query_embedding = await embed_with_retry(

texts=[query],

client=embedding_client,

)

query_embedding = normalize_l2(query_embedding)[0]

# Adaptive ef_search for filtered queries

effective_ef = ef_search

if filters:

estimated_filtered_fraction = estimate_filter_selectivity(filters)

if estimated_filtered_fraction < 0.20:

effective_ef = min(ef_search * 4, 512)

results = await collection.search(

query_vector=query_embedding,

top_k=top_k,

filter=filters,

search_params={"ef": effective_ef},

)

return results


### Monitoring Plan
| Metric                  | Alert Threshold         | Measurement Method         |
|-------------------------|------------------------|----------------------------|
| recall@10               | < 0.90                 | Weekly offline eval         |
| p95 query latency       | > 150ms                | APM traces                 |
| p99 query latency       | > 500ms                | APM traces                 |
| Index memory usage      | > 80% of allocation    | Prometheus metric           |
| Ingestion error rate    | > 1%                   | Dead-letter queue depth     |
| Delete ratio            | > 20% of total vectors | Index health check         |

### Capacity Estimate
| Component              | Current     | 18-Month Projection  | Instance Type          |
|------------------------|-------------|----------------------|------------------------|
| HNSW index memory      | ~16 GB      | ~48 GB               | 64 GB RAM node         |
| Storage (raw vectors)  | ~15 GB      | ~45 GB               | 100 GB SSD             |
| Query throughput       | 500 QPS     | 1500 QPS             | 3 replicas             |

Rules

  1. Never mix embedding models in a single collection. Cosine similarity between embeddings from different models is mathematically meaningless. If you upgrade models, rebuild the entire index. Use model_version in metadata and enforce that all vectors in a collection share a version.
  1. Always normalize vectors before insertion when using cosine similarity. Many clients do not auto-normalize. Un-normalized vectors with cosine distance silently produce wrong rankings. Verify normalization by checking that ||embedding|| ≈ 1.0 for 10 random samples after insertion.
  1. Never use HNSW with a delete ratio above 20% without rebuilding. Deleted nodes become "tombstones" that remain in the graph, degrading recall. Monitor the ratio of deleted to total vectors. Rebuild the index when this ratio crosses 15--20%.
  1. Never tune ef_construction after building the index. It is a build-time parameter. Changing it requires dropping and rebuilding the entire index, which may take hours for large corpora. Set it correctly from the start: 128 for most production cases, 200 for very high recall requirements.
  1. Always benchmark recall on your actual data, not synthetic benchmarks. ANN-Benchmarks results are on specific datasets (SIFT, GloVe) that may not reflect your data distribution. Maintain a golden retrieval dataset of 500--1000 queries with human-annotated relevant documents for your domain.
  1. Never store display-only fields as indexed metadata in the vector database. Fields like article body text, author bio, or image URLs should live in your primary database, referenced by vector ID. Storing them inflates memory and write amplification with zero query benefit.
  1. Avoid using metadata filtering as the primary access control mechanism. Metadata filters are soft filters -- bugs or injection vulnerabilities can expose cross-tenant data. For strict multi-tenancy, use separate collections or namespaces per tenant. Use metadata filtering only for performance optimization within a collection.
  1. Never configure nlist below sqrt(n_vectors) for IVF indexes. Too few clusters means each cluster contains too many vectors, making nprobe expensive and recall poor. Recalculate nlist as the corpus grows. An index built with nlist = 100 on 100K vectors will perform poorly once the corpus reaches 5M vectors.
  1. Always implement ingestion as idempotent upserts with content-addressed deduplication. Re-running a failed ingestion job should produce the same result as running it once. Non-idempotent ingestion pipelines create duplicate embeddings that inflate index size and reduce recall precision.
  1. Never expose raw vector scores to users as relevance percentages. Cosine similarity scores between 0.7 and 1.0 are not linearly interpretable. A score of 0.85 is not "85% relevant." Use score thresholds calibrated on your dataset, or convert to ranking positions. For user-facing relevance, use click-through rate or explicit feedback to calibrate score interpretation.

Edge Cases

Extremely High Filter Selectivity (< 1% of corpus)

When a query applies a filter that matches fewer than 1% of vectors (e.g., search within a tiny tenant, or a very narrow date range), standard HNSW pre-filtering will return almost no results because the graph traversal rarely lands in the tiny filtered subset. Solutions in order of preference:

Corpus Size Exceeds Available RAM

When the HNSW index no longer fits in RAM (typically when corpus exceeds memory budget), queries begin page-faulting and latency spikes to seconds. Do not simply add RAM indefinitely:

Embedding Model Version Migration

When upgrading from one embedding model to another (e.g., text-embedding-ada-002 to text-embedding-3-large), you cannot incrementally replace vectors in a mixed index:

Real-Time Vector Updates (User Profile Embeddings)

When vectors must be updated in near-real-time (e.g., user interest embeddings updated on every interaction), HNSW's update behavior becomes a bottleneck:

Catastrophic Recall Degradation After Ingestion Spike

After a large bulk ingestion (e.g., 10M new documents), recall can drop significantly and queries that previously worked return irrelevant results:

Multi-Language Corpora

When the corpus contains documents in many languages, single-language embedding models (including most English-trained models) produce a fragmented semantic space where similar concepts in different languages occupy different regions:

Query Latency Regression After Schema Changes

Adding a new metadata field with an index, or changing a filter from unindexed to indexed, can cause query latency to spike 3--5x in engines that rebuild indexes synchronously:


Example

Input: "We're building a customer support knowledge base search for a SaaS product. We have 800K support articles, each ~400--600 words. We need users to search in natural language and get relevant articles back in real time. We're using Postgres already and running on AWS. Expected query load is 200 QPS peak. Articles are updated about 500 per day, no deletes. We want to keep operational complexity low."

Output:

Requirements Summary

| Dimension | Value | Source |

|--------------------|-------------------------------------|----------------|

| Corpus size | 800K vectors, growing ~500/day | Stated |

| Dimensionality | 1536 (text-embedding-3-small rec.) | Derived |

| Query latency SLA | p95 < 100ms (real-time UX) | Derived |

| Recall target | recall@10 >= 0.95 | Default prod |

| Update pattern | Append/update, 500/day, no deletes | Stated |

| Filter patterns | None stated (single tenant implied) | Stated |

| Scale horizon | ~1M vectors in 14 months | Estimated |

| Deployment model | AWS, low operational complexity | Stated |

Engine Selection

Recommended: pgvector on RDS PostgreSQL 16 (or Aurora PostgreSQL 16.2+)

Rationale: With Postgres already deployed on AWS, pgvector eliminates a second operational dependency. 800K vectors at 1536 dims is approximately 5GB for the HNSW index -- well within the memory budget of an RDS db.r7g.2xlarge (64 GB RAM). At 200 QPS with HNSW ef_search=64, expected query latency is 15--40ms p95, well within the 100ms SLA. The 500 daily appends (no deletes) are ideal for HNSW -- no tombstone accumulation.

Alternatives considered:

Index Configuration

-- Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;

-- Create the knowledge base articles table
CREATE TABLE kb_articles (
    article_id      UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    external_id     VARCHAR(64) UNIQUE NOT NULL,  -- CMS article ID
    title           TEXT NOT NULL,
    content_hash    VARCHAR(64) NOT NULL,           -- SHA-256 of chunk text
    chunk_index     SMALLINT NOT NULL DEFAULT 0,
    embedding       vector(1536) NOT NULL,
    updated_at      BIGINT NOT NULL,                -- Unix timestamp
    category        VARCHAR(64),
    INDEX           (category),
    INDEX           (external_id)
);

-- HNSW index -- set parameters before data load for efficiency
-- M=16 is standard; ef_construction=128 balances build time and recall
CREATE INDEX kb_articles_embedding_idx ON kb_articles
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 128);

-- Set query-time ef_search for the session or connection pool
SET hnsw.ef_search = 64;
-- Increase to 100 if recall@10 falls below 0.93 in evaluation

Memory estimate:

Ingestion Pipeline

import hashlib
import asyncio
import asyncpg
import numpy as np
from openai import AsyncOpenAI
from typing import NamedTuple

class ArticleChunk(NamedTuple):
    external_id: str
    chunk_index: int
    text: str
    title: str
    category: str
    updated_at: int

async def ingest_articles(
    chunks: list[ArticleChunk],
    pool: asyncpg.Pool,
    openai_client: AsyncOpenAI,
    batch_size: int = 500,
) -> dict:
    """
    Idempotent ingestion pipeline for KB articles.
    
    Uses SHA-256 content hashing to skip unchanged articles.
    Normalizes embeddings for cosine similarity correctness.
    Batches at 500 to stay within OpenAI token limits per request.
    """
    stats = {"inserted": 0, "skipped": 0, "errors": 0}

    for i in range(0, len(chunks), batch_size):
        batch = chunks[i:i + batch_size]

        # Compute content hashes
        hashes = {
            chunk.external_id: hashlib.sha256(chunk.text.encode()).hexdigest()
            for chunk in batch
        }

        # Check which articles have changed
        async with pool.acquire() as conn:
            existing = await conn.fetch(
                """
                SELECT external_id, content_hash
                FROM kb_articles
                WHERE external_id = ANY($1)
                """,
                list(hashes.keys()),
            )
        existing_map = {row["external_id"]: row["content_hash"] for row in existing}
        
        changed = [
            chunk for chunk in batch
            if hashes[chunk.external_id] != existing_map.get(chunk.external_id)
        ]
        stats["skipped"] += len(batch) - len(changed)

        if not changed:
            continue

        # Embed changed articles with retry
        embeddings = await embed_with_backoff(
            texts=[chunk.text for chunk in changed],
            client=openai_client,
            model="text-embedding-3-small",
        )

        # Normalize to unit vectors (required for cosine correctness)
        embeddings_np = np.array(embeddings, dtype=np.float32)
        norms = np.linalg.norm(embeddings_np, axis=1, keepdims=True)
        embeddings_normalized = (embeddings_np / norms).tolist()

        # Upsert (insert or update on external_id conflict)
        async with pool.acquire() as conn:
            await conn.executemany(
                """
                INSERT INTO kb_articles
                    (external_id, chunk_index, title, embedding,
                     content_hash, category, updated_at)
                VALUES ($1, $2, $3, $4, $5, $6, $7)
                ON CONFLICT (external_id) DO UPDATE SET
                    embedding    = EXCLUDED.embedding,
                    content_hash = EXCLUDED.content_hash,
                    updated_at   = EXCLUDED.updated_at,
                    title        = EXCLUDED.title
                """,
                [
                    (
                        chunk.external_id,
                        chunk.chunk_index,
                        chunk.title,
                        embeddings_normalized[j],
                        hashes[chunk.external_id],
                        chunk.category,
                        chunk.updated_at,
                    )
                    for j, chunk in enumerate(changed)
                ],
            )
        stats["inserted"] += len(changed)

    return stats


async def embed_with_backoff(
    texts: list[str],
    client: AsyncOpenAI,
    model: str,
    max_retries: int = 5,
) -> list[list[float]]:
    delay = 1.0
    for attempt in range(max_retries):
        try:
            response = await client.embeddings.create(
                model=model, input=texts
            )
            return [item.embedding for item in response.data]
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            await asyncio.sleep(delay + (delay * 0.1 * asyncio.get_event_loop().time() % 1))
            delay = min(delay * 2, 60.0)

Query Implementation

async def search_kb(
    query: str,
    pool: asyncpg.Pool,
    openai_client: AsyncOpenAI,
    top_k: int = 10,
    category_filter: str | None = None,
    ef_search: int = 64,
) -> list[dict]:
    """
    Semantic search over KB articles.
    
    Returns top_k articles ranked by cosine similarity.
    Optional category filter uses Postgres WHERE clause (pre-filter).
    Category filter is safe here because categories are broad --
    each category contains > 20% of corpus, maintaining recall.
    """
    # Embed the query
    query_embeddings = await embed_with_backoff(
        texts=[query],
        client=openai_client,
        model="text-embedding-3-small",
    )
    query_vec = query_embeddings[0]
    
    # Normalize query vector
    query_np = np.array(query_vec, dtype=np.float32)
    query_normalized = (query_np / np.linalg.norm(query_np)).tolist()

    async with pool.acquire() as conn:
        # Set ef_search for this query
        await conn.execute(f"SET hnsw.ef_search = {ef_search}")
        
        if category_filter:
            results = await conn.fetch(
                """
                SELECT external_id, title, category,
                       1 - (embedding <=> $1) AS similarity
                FROM kb_articles
                WHERE category = $2
                ORDER BY embedding <=> $1
                LIMIT $3
                """,
                query_normalized,
                category_filter,
                top_k,
            )
        else:
            results = await conn.fetch(
                """
                SELECT external_id, title, category,
                       1 - (embedding <=> $1) AS similarity
                FROM kb_articles
                ORDER BY embedding <=> $1
                LIMIT $2
                """,
                query_normalized,
                top_k,
            )

    return [dict(row) for row in results]

Monitoring Plan

| Metric | Alert Threshold | Measurement Method |

|-------------------------|---------------------|-------------------------------------------|

| recall@10 | < 0.92 | Weekly eval on 500-query golden set |

| p95 query latency | > 100ms | RDS Performance Insights / APM |

| p99 query latency | > 300ms | RDS Performance Insights / APM |

| Index memory usage | > 80% shared_buffers| RDS CloudWatch FreeableMemory |

| Ingestion error rate | > 0.5% | Dead-letter queue (SQS) depth |

| Articles without vector | > 100 | Daily COUNT query vs CMS article count |

Recall measurement setup:

# Build golden dataset once: 500 queries with human-labeled relevant article IDs
# Run weekly as a cron job
async def measure_recall_at_k(
    golden_queries: list[GoldenQuery],
    search_fn,
    k: int = 10,
) -> float:
    hits = 0
    for gq in golden_queries:
        results = await search_fn(query=gq.query, top_k=k)
        retrieved_ids = {r["external_id"] for r in results}
        if gq.relevant_article_id in retrieved_ids:
            hits += 1
    return hits / len(golden_queries)
# Alert if result < 0.92

Capacity Estimate

| Component | Now (800K vectors) | 14 Months (1M vectors) | RDS Instance |

|------------------------|--------------------|------------------------|------------------------|

| HNSW index + vectors | ~5.1 GB RAM | ~6.4 GB RAM | db.r7g.xlarge (32 GB) |

| Raw vector storage | ~4.9 GB disk | ~6.1 GB disk | 100 GB gp3 volume |

| Query throughput | 200 QPS | 300 QPS (estimated) | Single instance + RO replica |

| Ingestion throughput | 500/day | 500/day | Within API rate limits |

Cost estimate (AWS us-east-1):

This design delivers production-grade semantic search at low operational cost by leveraging existing Postgres infrastructure. The HNSW index fits comfortably in RAM, delivers sub-40ms p95 query latency at 200 QPS, and requires no additional services to operate.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.