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.

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.