HomeBlogHow to Use Vector Databases for...

Engineering Guide · 9 min read · June 21, 2026

How to Use Vector Databases for AI-Powered Applications

AI prototypes look effortless on fifty test documents, then fail in production when exact SKUs miss semantic search, unindexed vectors stall latency, or missing tenant filters leak private data. This startup guide covers pgvector vs dedicated vector stores, hybrid retrieval, HNSW memory sizing, and cost control.

Author
Smit Desai
Published
June 21, 2026
Read time
9 min read
Topic
Data & Databases
Services
Custom Web · Mobile Apps · All Services

Every week I speak with founders whose AI demo worked brilliantly on 30 sample PDFs—and completely broke when real customers uploaded 40,000 messy support docs, invoices, and contracts. Searches returned irrelevant paragraphs, exact SKU lookups missed completely, responses slowed to four seconds, and engineers panicked about how to make sure Workspace A could never retrieve chunks belonging to Workspace B.

Vector databases are not magic AI brains; they are specialized nearest-neighbor indexes over high-dimensional arrays of floats. Having built production backends across 170+ shipped engagements since 2017, the teams that win with AI features treat vector storage with the same discipline as relational schema design: clear source-of-truth boundaries, hybrid retrieval, predictable memory budgets, and strict tenant isolation.

Vector Database and Hybrid Search Architecture


What Vector Databases Actually Do (and Where They Fail Alone)

An embedding model converts text, code, or images into a fixed-length array of numbers—typically 512, 768, or 1,536 dimensions—where semantically similar concepts sit close together in vector space. A vector database stores these arrays alongside metadata and builds an Approximate Nearest Neighbor (ANN) index such as HNSW (Hierarchical Navigable Small World) so similarity queries run in milliseconds instead of brute-forcing every row.

Why Pure Semantic Search Is Never Enough

Dense embeddings excel at intent ("how do I reset billing permissions?") and terrible at exact identifiers ("error ERR_TLS_104", contract ID #8841, or "iPhone 15 Pro Max 256GB"). If your users search both concepts and exact strings, pure vector search will frustrate them. You need hybrid retrieval combining full-text keyword matching with vector distance.


pgvector vs. Dedicated Vector Databases vs. Redis

Startups often rush into a separate managed vector SaaS on day one, creating a distributed sync problem before they even have product-market fit. Compare the main architectural options honestly:

Evaluation Factor PostgreSQL (pgvector) Dedicated Vector DB (Qdrant / Pinecone / Weaviate) Redis Vector Search
Operational Overhead Very low (lives in existing Postgres) Medium–High (new vendor, sync pipeline) Low if already running Redis
Transactional Consistency Full ACID with relational tables Eventual consistency (requires sync jobs) In-memory persistence trade-offs
Metadata Pre-Filtering Native SQL WHERE + joins Payload indexes (fast at high scale) Tag / numeric filters
Hybrid Search Native (tsvector + vector + RRF) Built-in sparse + dense support Built-in BM25 + vector
Cost & Scale Sweet Spot < 5M vectors 5M – 1B+ vectors or high QPS Ultra-low-latency semantic cache

For 90% of B2B startups building through custom web application development, pgvector keeps your architecture simple, cheap, and transactionally consistent. You can always extract vectors into Qdrant or Pinecone later once your scale genuinely outgrows single-node or partitioned Postgres RAM.


Schema Design and Hybrid Search in PostgreSQL

When implementing RAG or semantic search in Postgres, design the schema around document ownership, content hashing, and indexed filtering.

Production Table Schema With Content Hashing and HNSW

Store a content_hash on each chunk so background re-indexing workers skip unchanged paragraphs instead of paying embedding API fees repeatedly:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE document_chunks (
    id BIGSERIAL PRIMARY KEY,
    tenant_id BIGINT NOT NULL,
    document_id BIGINT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
    chunk_index INTEGER NOT NULL,
    content TEXT NOT NULL,
    content_tsv TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
    content_hash CHAR(64) NOT NULL,
    embedding VECTOR(1536) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Standard B-tree for strict tenant scoping and cascade deletes
CREATE INDEX idx_chunks_tenant_doc ON document_chunks (tenant_id, document_id);

-- Full-text GIN index for exact keywords, SKUs, and error codes
CREATE INDEX idx_chunks_tsv ON document_chunks USING GIN (content_tsv);

-- HNSW index for fast cosine similarity search
CREATE INDEX idx_chunks_embedding_hnsw
    ON document_chunks USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

Combining Vector Similarity and Lexical Ranks in Application Code

Rather than calibrating incompatible float scales between BM25 text rank and cosine distance, fetch top-40 candidates from both indexes in parallel and combine them with lightweight Reciprocal Rank Fusion (RRF) right inside your Python retrieval service:

def fuse_rankings(semantic_ids: list[str], lexical_ids: list[str], k: int = 60, top_n: int = 8) -> list[str]:
    scores: dict[str, float] = {}
    for pos, chunk_id in enumerate(semantic_ids, start=1):
        scores[chunk_id] = scores.get(chunk_id, 0.0) + 1.0 / (k + pos)
    for pos, chunk_id in enumerate(lexical_ids, start=1):
        scores[chunk_id] = scores.get(chunk_id, 0.0) + 1.0 / (k + pos)
    return [cid for cid, _ in sorted(scores.items(), key=lambda pair: pair[1], reverse=True)[:top_n]]

Executing pre-filtered tenant_id index scans for each list keeps latency predictable as tables scale. Consult the PostgreSQL performance tips documentation when sizing work memory and index maintenance settings for large pgvector workloads.


Chunking, Filtering, and Memory Pitfalls That Break Production AI

Most "bad LLM answers" are actually retrieval bugs caused by sloppy ingestion pipelines.

Respect Document Structure When Chunking

Fixed 500-character splitting slices markdown tables, code blocks, and legal clauses right in half. Split along structural boundaries first (headings, paragraphs, table rows), target 300–600 tokens with a 10–15% overlap, and prepend contextual metadata (document title and section heading) into the embedded text so a chunk reading "This fee is waived after 90 days" still knows which plan it describes.

Avoid the Post-Filtering Trap

With HNSW indexes, if a query requests LIMIT 10 for tenant_id = 99 and that tenant only owns 0.2% of rows in a shared index, HNSW can traverse 40 candidates, find zero matches for tenant 99, and return empty results—unless your engine supports iterative HNSW scans (available in newer pgvector releases via hnsw.iterative_scan) or partitions large tenants cleanly. For strict SaaS isolation guidelines, review multi-tenant SaaS architecture patterns.

Size RAM for HNSW Up Front

HNSW indexes must fit largely in RAM (shared_buffers + OS page cache) to stay sub-30ms. A single million 1,536-dimensional float32 vectors occupies ~6 GB of raw data plus index graph overhead. Storing half-precision (halfvec in pgvector) or truncating Matryoshka embeddings to 512 dimensions slashes memory footprint and cloud DB bills dramatically with minimal recall loss.

Cache Query Embeddings and Repeat Prompts in Redis

Every time a user types a common question or repeats a filter query, calling an external embedding API adds 80–250ms of network latency. Hash the normalized query string and cache the embedding vector (or the complete RAG answer when source documents have not changed) in Redis. Check the Redis developer documentation for TTL and eviction policies that protect cache hit rates.


Shipping AI Retrieval Without Over-Building

Startups win by getting accurate, secure AI workflows into customers' hands quickly—not by managing five specialized databases for ten thousand documents. Start with clean ingestion, hybrid search, strict tenant boundaries, and observable retrieval evaluation sets.

Teams win with AI search when retrieval precision, ingestion cleanliness, and per-tenant security are engineered as first-class backend primitives rather than fragile glue scripts. SmitDev designs and deploys fast PostgreSQL/Redis retrieval systems at $55/day (8–9 hours of hands-on implementation) or $1,999/month dedicated retainer, alongside our $399 7-day marketing website package when you are gearing up for public launch. Want a senior backend review of your chunking pipeline or vector infrastructure? Schedule an engineering discussion or engage a dedicated full-stack developer.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

data & databases

Should an early-stage startup use pgvector or a dedicated vector database like Pinecone or Qdrant?

If you already run PostgreSQL and store under 1 to 5 million vectors, start with pgvector. You avoid syncing a second database, get ACID transactions when documents are deleted or updated, and can enforce strict SQL tenant permissions in the same query.

Why does pure vector similarity search fail on product codes, names, or legal clauses?

Dense embeddings capture conceptual meaning, not exact token matches. Searching for part number XJ-904-B or an exact error code often returns conceptually similar noise unless you combine vector similarity with keyword/BM25 search (hybrid search).

What is the biggest security risk when building multi-tenant RAG applications?

Cross-tenant data leakage from missing or post-filtered permissions. If you retrieve the top-20 global vectors first and filter by workspace_id afterward, a customer can receive zero valid results—or worse, leak context if a filter bug occurs. Always pre-filter or partition by tenant.

How do you keep embedding API bills and latency low in production?

Cache normalized query embeddings in Redis with a TTL, only re-embed document chunks whose content SHA-256 hash actually changed, and test smaller embedding dimensions (such as 512 or 768 via Matryoshka truncation) to cut RAM usage in half.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.