RAG with pgvector on Supabase

    How to build a production RAG pipeline using pgvector on Supabase — chunking strategy, embedding batches, cosine similarity search, and a cache layer to cut API costs.

    March 11, 2026
    RAG with pgvector on Supabase

    RAG with pgvector and Supabase: From Zero to Semantic Search

    Retrieval-Augmented Generation (RAG) is how you give an LLM memory without fine-tuning. This is the exact implementation we use in our Company Brain — a searchable knowledge base of 300+ Twitter bookmarks and internal docs.

    Why pgvector Over a Dedicated Vector DB

    Pinecone, Weaviate, Qdrant — all great, all add infrastructure cost and complexity. If you're already on Supabase, pgvector gives you vector search inside your existing Postgres. At <10k rows, performance is identical.

    Schema

    CREATE EXTENSION IF NOT EXISTS vector;
    
    CREATE TABLE intel.bookmarks (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      tweet_id text UNIQUE NOT NULL,
      content text NOT NULL,
      embedding vector(3072),  -- Gemini gemini-embedding-001
      metadata jsonb DEFAULT '{}',
      created_at timestamptz DEFAULT now()
    );
    
    -- Search function
    CREATE OR REPLACE FUNCTION intel.search_bookmarks(
      query_embedding vector(3072),
      match_threshold float DEFAULT 0.7,
      match_count int DEFAULT 10
    )
    RETURNS TABLE(id uuid, content text, metadata jsonb, similarity float)
    LANGUAGE sql STABLE AS $
      SELECT id, content, metadata,
        1 - (embedding <=> query_embedding) AS similarity
      FROM intel.bookmarks
      WHERE 1 - (embedding <=> query_embedding) > match_threshold
      ORDER BY embedding <=> query_embedding
      LIMIT match_count;
    $;
    

    No index needed under 1000 rows — sequential scan is fast enough and simpler.

    Embedding with Gemini (Free)

    Gemini gemini-embedding-001 produces 3072-dim embeddings and is free tier. We batch in groups of 50 (API limit is 100, we use 50 for safety):

    async def embed_batch(texts: list[str]) -> list[list[float]]:
        results = []
        for i in range(0, len(texts), 50):
            chunk = texts[i:i+50]
            for attempt in range(2):
                try:
                    resp = await gemini_client.embed_content(
                        model="models/gemini-embedding-001",
                        content=chunk,
                        task_type="RETRIEVAL_DOCUMENT",
                    )
                    results.extend([e.values for e in resp.embeddings])
                    break
                except Exception as e:
                    if attempt == 0:
                        await asyncio.sleep(2)
                        continue
                    logger.warning("Embedding chunk %d failed: %s", i, e)
                    results.extend([[0.0] * 3072] * len(chunk))  # zero-vector fallback
        return results
    

    Partial failures return zero-vectors and set metadata.needs_reembed=True — fixed on next sync without dropping the row.

    Cache Layer to Avoid Re-embedding Queries

    The same question asked twice should not hit the embedding API twice:

    CREATE TABLE intel.brain_queries (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      query_text text NOT NULL,
      query_embedding vector(3072),
      cached_answer text,
      hit_count int DEFAULT 1,
      created_at timestamptz DEFAULT now()
    );
    
    CREATE OR REPLACE FUNCTION intel.brain_cache_lookup(
      query_embedding vector(3072),
      similarity_threshold float DEFAULT 0.95
    )
    RETURNS TABLE(cached_answer text, similarity float)
    LANGUAGE sql STABLE AS $
      SELECT cached_answer,
        1 - (query_embedding <=> brain_queries.query_embedding) AS similarity
      FROM intel.brain_queries
      WHERE 1 - (query_embedding <=> brain_queries.query_embedding) > similarity_threshold
        AND cached_answer IS NOT NULL
      ORDER BY query_embedding <=> brain_queries.query_embedding
      LIMIT 1;
    $;
    

    Threshold is critical. 0.95 means only near-identical queries hit cache. Lower it and you get false matches — "what services do we offer" matching "what are the biggest AI trends". We learned this the hard way.

    Full Query Pipeline

    async def answer_query(question: str) -> str:
        q_embedding = await embed_single(question)
    
        # 1. Check cache first
        cache = await supabase.rpc("brain_cache_lookup",
            {"query_embedding": q_embedding, "similarity_threshold": 0.95}).execute()
        if cache.data:
            return cache.data[0]["cached_answer"]
    
        # 2. Retrieve relevant docs
        matches = await supabase.rpc("search_bookmarks",
            {"query_embedding": q_embedding, "match_threshold": 0.7, "match_count": 8}).execute()
    
        context = "\n\n".join(m["content"] for m in matches.data)
    
        # 3. Generate answer
        answer = await llm_generate(question, context)
    
        # 4. Cache the answer
        await supabase.table("brain_queries").insert({
            "query_text": question,
            "query_embedding": q_embedding,
            "cached_answer": answer,
        }).execute()
    
        return answer
    

    This pattern — embed → cache check → retrieve → generate → cache write — handles 90% of RAG use cases.


    We Run This in Production

    This RAG pipeline is the Company Brain behind our AI assistant — it answers questions about our services, past projects, and industry knowledge by searching a vector database of 300+ curated sources, with a cache layer that cuts API costs to near zero.

    If you want a knowledge base that actually answers questions about your business — rather than hallucinating — this is the architecture to build on.

    Talk to us about building your Company Brain →


    Related Reading

    Key Takeaway

    Vector search transforms document retrieval from keyword matching to semantic understanding. Rather than searching for exact matches, systems can now find content related by meaning, even when no shared vocabulary exists. This fundamentally changes how organizations can query their accumulated knowledge. For technical documentation, this means developers find solutions without needing to know the exact terminology used in the original content. For customer support, it enables finding relevant past tickets based on problem descriptions rather than ticket titles. The implementation using pgvector on Supabase makes this approach accessible to any team with standard PostgreSQL knowledge, removing the need for specialized vector database expertise or infrastructure.

    Work with us

    Send the brief

    Name the app, site, or WhatsApp system. Shipped work you can open: LalaRente, Khaki Post, and marine voice AI. Studio WhatsApp: 9892110925.