The Problem: The Demo Worked, Production Didn't

Here's a pattern that plays out on almost every team that ships a docs assistant. You point a large language model (LLM) at the help center and the internal wiki, demo it to the support team, and it nails "How do I reset two-factor authentication?" Everyone's impressed.

Then real questions arrive, and the first week of production looks like this:

  • It answers a refund question by quoting a policy page that was replaced six months ago, because both versions are still in the index.
  • A customer pastes ERR_PAYMENT_402 and the assistant returns generic payment advice. Vector search doesn't care about exact strings.
  • An agent asks about an internal escalation process and gets an answer built from an HR document they shouldn't be able to see.
  • Answers take six seconds, and nobody can tell whether a prompt change made things better or worse.

None of these are model problems. They're retrieval and data problems, and that's where most of the work in Retrieval-Augmented Generation (RAG) lives. RAG fetches relevant context at query time and hands it to the model alongside the question, so the model quotes your data instead of guessing.

This guide builds a RAG pipeline with FastAPI and PostgreSQL's pgvector extension, and designs each piece around those failures. If you already run Postgres, you get vector search next to your relational data, permissions and backups, without adding another database.

How a RAG Pipeline Works

A RAG system has two paths:

  1. Ingestion (offline): load documents, split them into chunks, embed each chunk, and store the vectors.
  2. Query (online): embed the user's question, find the nearest chunks, build a prompt with those chunks, and ask the LLM to answer only from them.
Text
Documents ──► Chunk ──► Embed ──► pgvector
                                     │
Question ──► Embed ──► Similarity search ──► Prompt + context ──► LLM ──► Answer

Most RAG quality problems come from the first half. Bad chunks and weak retrieval can't be rescued by a better model.

Setting Up PostgreSQL with pgvector

The quickest way to get started locally is the official pgvector Docker image:

Terminal
docker run -d --name rag-db \
  -e POSTGRES_PASSWORD=postgres \
  -p 5432:5432 \
  pgvector/pgvector:pg16

Enable the extension and create a table for chunks:

SQL
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
    id          BIGSERIAL PRIMARY KEY,
    source      TEXT NOT NULL,
    title       TEXT,
    created_at  TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE chunks (
    id           BIGSERIAL PRIMARY KEY,
    document_id  BIGINT REFERENCES documents(id) ON DELETE CASCADE,
    chunk_index  INT NOT NULL,
    content      TEXT NOT NULL,
    embedding    vector(1536) NOT NULL,
    tsv          tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);

-- Approximate nearest-neighbour index for cosine distance
CREATE INDEX chunks_embedding_idx
    ON chunks USING hnsw (embedding vector_cosine_ops);

-- Full-text index for keyword search (used later for hybrid retrieval)
CREATE INDEX chunks_tsv_idx ON chunks USING gin (tsv);

The vector(1536) dimension must match your embedding model. OpenAI's text-embedding-3-small produces 1536-dimensional vectors by default.

Tip: HNSW indexes give fast, high-recall search without a training step, which makes them a good default. IVFFlat indexes build faster but need data in the table before you create them.

Project Structure

Terminal
rag-service/
├── app/
│   ├── main.py        # FastAPI routes
│   ├── db.py          # asyncpg pool
│   ├── chunking.py    # text splitting
│   ├── embeddings.py  # embedding client
│   └── retrieval.py   # search + prompt building
└── pyproject.toml

Install the dependencies (with uv, or pip if you prefer):

Terminal
uv add fastapi uvicorn asyncpg pgvector openai pydantic-settings

Chunking Documents the Right Way

Chunking decides what the model can see. Chunks that are too large dilute relevance; chunks that are too small lose context. A good starting point is 300 to 500 tokens with a small overlap, split on natural boundaries.

Python
# app/chunking.py
import re

def split_into_chunks(text: str, max_chars: int = 1800, overlap: int = 200) -> list[str]:
    """Split text on paragraph boundaries, packing paragraphs into chunks.

    ~1800 characters is roughly 400-450 tokens of English text.
    """
    paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
    chunks: list[str] = []
    current = ""

    for para in paragraphs:
        if len(current) + len(para) + 2 <= max_chars:
            current = f"{current}\n\n{para}" if current else para
            continue

        if current:
            chunks.append(current)
            # Carry a tail of the previous chunk forward for context
            current = current[-overlap:] + "\n\n" + para
        else:
            # A single paragraph longer than max_chars: hard-split it
            for i in range(0, len(para), max_chars - overlap):
                chunks.append(para[i : i + max_chars])
            current = ""

    if current:
        chunks.append(current)
    return chunks

A few rules that pay off in practice:

  • Keep headings with their content. Prepend the nearest heading to each chunk so "Pricing" isn't separated from the price table.
  • Store metadata. Source URL, title and section let you filter results and show citations.
  • Re-chunk when you change strategy. Mixing chunking strategies in one index makes results hard to reason about.

Generating Embeddings

Embed chunks in batches. It's faster and cheaper than one request per chunk.

Python
# app/embeddings.py
from openai import AsyncOpenAI

client = AsyncOpenAI()
EMBEDDING_MODEL = "text-embedding-3-small"

async def embed_texts(texts: list[str], batch_size: int = 100) -> list[list[float]]:
    vectors: list[list[float]] = []
    for i in range(0, len(texts), batch_size):
        batch = texts[i : i + batch_size]
        response = await client.embeddings.create(model=EMBEDDING_MODEL, input=batch)
        vectors.extend(item.embedding for item in response.data)
    return vectors

If privacy or cost matters more than peak quality, you can swap in an open-source embedding model running locally. See running lightweight LLMs locally for the setup. Just remember to change the vector dimension to match.

Database Access with asyncpg

Register the pgvector type so you can pass Python lists straight into queries:

Python
# app/db.py
import asyncpg
from pgvector.asyncpg import register_vector

pool: asyncpg.Pool | None = None

async def init_pool(dsn: str) -> None:
    global pool
    pool = await asyncpg.create_pool(dsn, min_size=2, max_size=10, init=register_vector)

async def close_pool() -> None:
    if pool:
        await pool.close()

Connection pooling matters here because every query hits the database. The database pooling guide covers sizing in more depth.

Ingesting Documents

Python
# app/ingest.py
import numpy as np
from app import db
from app.chunking import split_into_chunks
from app.embeddings import embed_texts

async def ingest_document(source: str, title: str, text: str) -> int:
    chunks = split_into_chunks(text)
    vectors = await embed_texts([f"{title}\n\n{c}" for c in chunks])

    async with db.pool.acquire() as conn:
        async with conn.transaction():
            doc_id = await conn.fetchval(
                "INSERT INTO documents (source, title) VALUES ($1, $2) RETURNING id",
                source, title,
            )
            await conn.executemany(
                """INSERT INTO chunks (document_id, chunk_index, content, embedding)
                   VALUES ($1, $2, $3, $4)""",
                [(doc_id, i, c, np.array(v)) for i, (c, v) in enumerate(zip(chunks, vectors))],
            )
    return doc_id

Ingestion can be slow for large files. Run it outside the request cycle using background tasks or a proper job queue.

Hybrid Retrieval: Vectors Plus Keywords

Pure vector search is great at meaning and surprisingly bad at exact terms like error codes, SKUs or function names. Hybrid retrieval runs both searches and merges them with Reciprocal Rank Fusion (RRF), which only needs each result's rank.

Python
# app/retrieval.py
import numpy as np
from app import db

HYBRID_SQL = """
WITH semantic AS (
    SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1) AS rank
    FROM chunks
    ORDER BY embedding <=> $1
    LIMIT 20
),
keyword AS (
    SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, query) DESC) AS rank
    FROM chunks, plainto_tsquery('english', $2) AS query
    WHERE tsv @@ query
    ORDER BY ts_rank_cd(tsv, query) DESC
    LIMIT 20
)
SELECT c.id, c.content, d.title, d.source,
       COALESCE(1.0 / (60 + s.rank), 0) + COALESCE(1.0 / (60 + k.rank), 0) AS score
FROM semantic s
FULL OUTER JOIN keyword k ON s.id = k.id
JOIN chunks c ON c.id = COALESCE(s.id, k.id)
JOIN documents d ON d.id = c.document_id
ORDER BY score DESC
LIMIT $3;
"""

async def retrieve(question: str, query_vector: list[float], k: int = 6) -> list[dict]:
    async with db.pool.acquire() as conn:
        rows = await conn.fetch(HYBRID_SQL, np.array(query_vector), question, k)
    return [dict(r) for r in rows]

<=> is pgvector's cosine distance operator, which matches the vector_cosine_ops index we created. The constant 60 in RRF is the conventional default and works well without tuning.

Building a Grounded Prompt

The prompt has one job: force the model to answer from the context and admit when it can't.

Python
SYSTEM_PROMPT = """You answer questions using only the provided context.
Cite sources inline as [1], [2] matching the context numbers.
If the context does not contain the answer, say you don't know.
Never invent facts, links or numbers."""

def build_messages(question: str, chunks: list[dict]) -> list[dict]:
    context = "\n\n".join(
        f"[{i}] {c['title']} ({c['source']})\n{c['content']}"
        for i, c in enumerate(chunks, start=1)
    )
    return [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
    ]

The FastAPI Endpoint

Python
# app/main.py
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from openai import AsyncOpenAI
from pydantic import BaseModel, Field

from app import db
from app.embeddings import embed_texts
from app.retrieval import retrieve, build_messages

llm = AsyncOpenAI()
MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini")

@asynccontextmanager
async def lifespan(app: FastAPI):
    await db.init_pool(os.environ["DATABASE_URL"])
    yield
    await db.close_pool()

app = FastAPI(lifespan=lifespan)

class AskRequest(BaseModel):
    question: str = Field(min_length=3, max_length=2000)

class Source(BaseModel):
    title: str
    source: str

class AskResponse(BaseModel):
    answer: str
    sources: list[Source]

@app.post("/ask", response_model=AskResponse)
async def ask(req: AskRequest) -> AskResponse:
    [query_vector] = await embed_texts([req.question])
    chunks = await retrieve(req.question, query_vector)

    if not chunks:
        return AskResponse(answer="I couldn't find anything relevant.", sources=[])

    completion = await llm.chat.completions.create(
        model=MODEL,
        messages=build_messages(req.question, chunks),
        temperature=0.1,
    )
    return AskResponse(
        answer=completion.choices[0].message.content,
        sources=[Source(title=c["title"], source=c["source"]) for c in chunks],
    )

For long answers, stream the response token by token instead of making users wait. I cover that in streaming LLM responses with FastAPI.

Common Problems and How to Fix Them

The answer ignores the obvious document

Usually a chunking issue. Print the retrieved chunks for the failing question. If the right passage isn't in the top results, fix retrieval before touching the prompt. Try smaller chunks, adding headings to chunks, or hybrid search.

Results are good in testing and bad in production

Real users ask short, vague questions. Rewrite the query first by asking a cheap model to expand "refund policy?" into a full question, then embed the rewritten version.

Latency is too high

Cache embeddings for repeated questions and cache full answers for popular ones. The Redis caching guide shows the patterns. Also check that your query actually uses the HNSW index with EXPLAIN ANALYZE.

You can't tell if a change helped

You need evaluation, not vibes. Build a small set of questions with known answers and score every change against it. See how to evaluate LLM applications.

Production Gotchas (and What to Do About Them)

These are the problems that show up after launch, not in the demo.

Stale and duplicate documents

If you re-ingest a document without removing its old chunks, both versions compete in search and the model happily quotes the outdated one. Make ingestion idempotent by keying documents on their source and replacing chunks in one transaction:

Python
async def upsert_document(conn, source: str, title: str, chunks, vectors) -> None:
    async with conn.transaction():
        await conn.execute("DELETE FROM documents WHERE source = $1", source)  # cascades to chunks
        doc_id = await conn.fetchval(
            "INSERT INTO documents (source, title) VALUES ($1, $2) RETURNING id", source, title
        )
        await conn.executemany(
            "INSERT INTO chunks (document_id, chunk_index, content, embedding) VALUES ($1, $2, $3, $4)",
            [(doc_id, i, c, v) for i, (c, v) in enumerate(zip(chunks, vectors))],
        )

Also store an updated_at on documents and show it in citations. "According to Refund policy (updated March 2024)" lets users spot staleness themselves.

Permissions must be enforced at retrieval time

Once a chunk is in the prompt, the model can repeat it. Filter by tenant or access group in the SQL query, never by asking the model to ignore things. Add a column such as tenant_id or acl_groups TEXT[] to chunks and include it in every search.

Watch out for one subtle interaction: with an HNSW index, Postgres finds the nearest neighbours first and applies your WHERE filter after, so a restrictive filter can return fewer than k rows. pgvector 0.8 added iterative index scans to address this (SET hnsw.iterative_scan = relaxed_order;). On older versions, raise hnsw.ef_search or use partial indexes per tenant.

Chunkers shred tables and code

A pricing table split across three chunks is useless in all three. Chunk Markdown and HTML by headings first, keep tables and code blocks whole even if they exceed your size target, and prepend the section heading to every chunk.

Changing the embedding model means re-embedding everything

Vectors from different models aren't comparable, and dimensions often differ too. Store the model name on each row, build the new index alongside the old one, backfill, then switch queries over. Plan for this on day one, because better embedding models keep coming.

Re-ingestion cost adds up

If a nightly job re-embeds the whole wiki, you pay for every unchanged paragraph. Store a content hash per chunk and skip embedding calls for chunks whose hash hasn't changed.

"I don't know" is a feature

When the best match is weak, it's better to say so than to answer from loosely related text. Log retrieval scores, look at the distribution for questions you can't answer, and set a threshold below which the endpoint returns "I couldn't find this in the docs" along with a link to search or support.

Conclusion

A solid RAG pipeline is mostly good data engineering: thoughtful chunking, honest retrieval and a prompt that keeps the model grounded. PostgreSQL with pgvector keeps all of it in one database you already know how to back up, monitor and scale.

Start simple with paragraph chunks, hybrid search and a strict prompt. Then measure, and improve the piece that's actually failing.


Resources:

Related Articles: