DEV Community

Cover image for Building a Production-Ready RAG Pipeline with FastAPI, PGVector, and Python
AHZ Cosmic WarriorX
AHZ Cosmic WarriorX

Posted on

Building a Production-Ready RAG Pipeline with FastAPI, PGVector, and Python

Retrieval-Augmented Generation (RAG) has rapidly become the standard architectural pattern for connecting Large Language Models (LLMs) to private, real-time datasets. However, many tutorials rely on heavyweight abstractions that obscure what happens under the hood or prove difficult to deploy in production.

In this tutorial, we will build a lightweight, production-ready RAG service from scratch using FastAPI, PostgreSQL with the pgvector extension, and Python.


Architecture Overview

Our backend service handles three core tasks:

  1. Vector Storage: Utilizing PostgreSQL with the pgvector extension to store text embeddings alongside relational metadata.
  2. Document Ingestion: Chunking text and generating vector embeddings via standard vectorization models.
  3. Contextual Retrieval: Performing cosine similarity search in PostgreSQL and passing the retrieved context to an LLM to generate grounded responses.
[Client Request] 
       │
       ▼
[FastAPI Endpoint] ──(Generates Embedding)──► [pgvector / PostgreSQL]
       │                                              │
       │                                     (Cosine Distance Query)
       │                                              │
       ▼                                              ▼
[LLM Context Prompt] ◄────────────────────── [Relevant Context Chunks]
       │
       ▼
[Grounded Answer]
Enter fullscreen mode Exit fullscreen mode

1. Setting Up PostgreSQL with pgvector

We will run PostgreSQL with pgvector enabled using Docker.

Create a docker-compose.yml file:

version: '3.8'

services:
  db:
    image: pgvector/pgvector:pg16
    environment:
      POSTGRES_DB: rag_db
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password123
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
Enter fullscreen mode Exit fullscreen mode

Start the database container:

docker compose up -d
Enter fullscreen mode Exit fullscreen mode

2. Installing Dependencies

Install the required Python packages:

pip install fastapi uvicorn psycopg2-binary sentence-transformers sqlalchemy pgvector
Enter fullscreen mode Exit fullscreen mode

3. Database Schema and Vector Extension

Let's initialize the database, enable the vector extension, and create an index optimized for similarity search (Hierarchical Navigable Small World, or HNSW).

Create database.py:

import psycopg2
from pgvector.psycopg2 import register_vector

DB_PARAMS = {
    "dbname": "rag_db",
    "user": "postgres",
    "password": "password123",
    "host": "localhost",
    "port": "5432"
}

def get_db_connection():
    conn = psycopg2.connect(**DB_PARAMS)
    register_vector(conn)
    return conn

def init_db():
    conn = get_db_connection()
    cur = conn.cursor()

    # 1. Enable pgvector extension
    cur.execute("CREATE EXTENSION IF NOT EXISTS vector;")

    # 2. Create documents table (384 dimensions for all-MiniLM-L6-v2)
    cur.execute("""
        CREATE TABLE IF NOT EXISTS documents (
            id SERIAL PRIMARY KEY,
            content TEXT NOT NULL,
            metadata JSONB DEFAULT '{}',
            embedding vector(384)
        );
    """)

    # 3. Create HNSW index for fast approximate nearest neighbor search
    cur.execute("""
        CREATE INDEX IF NOT EXISTS documents_embedding_hnsw_idx 
        ON documents USING hnsw (embedding vector_cosine_ops);
    """)

    conn.commit()
    cur.close()
    conn.close()

if __name__ == "__main__":
    init_db()
    print("Database and pgvector schema initialized successfully.")
Enter fullscreen mode Exit fullscreen mode

4. Building the RAG Pipeline and API

Now, we create the FastAPI application in main.py. We will use the lightweight sentence-transformers/all-MiniLM-L6-v2 model locally to generate dense vector embeddings without incurring third-party API latency.

Create main.py:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
from database import get_db_connection, init_db
import numpy as np

app = FastAPI(title="Production RAG Service", version="1.0.0")

# Load embedding model on startup
model = SentenceTransformer('all-MiniLM-L6-v2')

class DocumentIngestRequest(BaseModel):
    content: str
    metadata: dict = {}

class QueryRequest(BaseModel):
    query: str
    top_k: int = 3

@app.on_event("startup")
def startup_event():
    init_db()

@app.post("/ingest")
def ingest_document(payload: DocumentIngestRequest):
    """Encodes text to a vector embedding and saves it to PostgreSQL."""
    try:
        embedding = model.encode(payload.content).tolist()

        conn = get_db_connection()
        cur = conn.cursor()

        cur.execute(
            """
            INSERT INTO documents (content, metadata, embedding)
            VALUES (%s, %s, %s)
            RETURNING id;
            """,
            (payload.content, str(payload.metadata).replace("'", '"'), embedding)
        )

        doc_id = cur.fetchone()[0]
        conn.commit()
        cur.close()
        conn.close()

        return {"status": "success", "document_id": doc_id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/search")
def search_similar_documents(payload: QueryRequest):
    """Performs cosine similarity search using pgvector's <=> operator."""
    try:
        query_embedding = model.encode(payload.query).tolist()

        conn = get_db_connection()
        cur = conn.cursor()

        # <=> denotes Cosine Distance in pgvector
        cur.execute(
            """
            SELECT id, content, metadata, 1 - (embedding <=> %s::vector) AS similarity
            FROM documents
            ORDER BY embedding <=> %s::vector
            LIMIT %s;
            """,
            (query_embedding, query_embedding, payload.top_k)
        )

        results = []
        for row in cur.fetchall():
            results.append({
                "id": row[0],
                "content": row[1],
                "metadata": row[2],
                "similarity_score": round(float(row[3]), 4)
            })

        cur.close()
        conn.close()

        return {"query": payload.query, "results": results}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
Enter fullscreen mode Exit fullscreen mode

5. Verification and Testing

Start your FastAPI server:

uvicorn main:app --reload --port 8000
Enter fullscreen mode Exit fullscreen mode

Ingesting Sample Data:

curl -X POST "http://localhost:8000/ingest" \
     -H "Content-Type: application/json" \
     -d '{
       "content": "PostgreSQL 16 with pgvector allows scalable vector indexing using HNSW.",
       "metadata": {"category": "database"}
     }'
Enter fullscreen mode Exit fullscreen mode

Querying Relevant Context:

curl -X POST "http://localhost:8000/search" \
     -H "Content-Type: application/json" \
     -d '{
       "query": "How do I index vectors in Postgres?",
       "top_k": 1
     }'
Enter fullscreen mode Exit fullscreen mode

Expected Response:

{
  "query": "How do I index vectors in Postgres?",
  "results": [
    {
      "id": 1,
      "content": "PostgreSQL 16 with pgvector allows scalable vector indexing using HNSW.",
      "metadata": {"category": "database"},
      "similarity_score": 0.8124
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Conclusion and Production Considerations

By combining FastAPI with pgvector, we eliminate the operational overhead of managing a separate, specialized vector database.

For high-scale production deployments, consider the following optimizations:

  1. Connection Pooling: Use PgBouncer or SQLAlchemy Async Engine to handle high concurrent load.
  2. HNSW Index Parameters: Fine-tune m (number of bi-directional links) and ef_construction (size of dynamic candidate list) during index creation for the optimal balance between indexing speed and recall accuracy.
  3. Hybrid Search: Combine pgvector cosine similarity with PostgreSQL's native Full-Text Search (tsvector / tsquery) for optimal keyword and semantic retrieval.

Top comments (0)