tutorial··5 min read·WoWSQL Team

Build a RAG App Backend on Postgres and pgvector

Build a RAG backend on Postgres: chunk and embedding tables, hybrid retrieval SQL, per-user RLS, an ingest and answer API, and a no-pgvector fallback.

A RAG (retrieval-augmented generation) backend on Postgres needs three tables (documents, chunks with an embedding and a full-text column, and chat messages), an ingest job that splits and embeds text, one SQL function that retrieves the best chunks, and Row Level Security so each user only ever retrieves their own data. WoWSQL gives you the Postgres database, auth, RLS and a REST API in one project. pgvector itself is listed as "optional (if installed on the server)" and enabling extensions needs a paid plan, so check your dashboard first. If vector isn't offered, the full-text fallback in this guide works on any Postgres.

Everything below was run on 28 November 2026: the SQL on PostgreSQL 17.12 with pgvector 0.8.0, and the TypeScript ingest and answer code against a local PostgREST 16.6 server behind a small gateway that mimics WoWSQL's key handling, with a fake 3-dimension embedder. It was not run on a live WoWSQL project, and we did not confirm that pgvector can be enabled on WoWSQL today.

Key facts

  • Extensions on WoWSQL (docs, checked 28 November 2026): enabling extensions needs Pro ($25/month) or Scale ($99/month). Tier 1 is pgcrypto, uuid-ossp and pg_stat_statements; Tier 2 includes pg_trgm, unaccent and citext; vector, postgis and pg_cron are "optional (if installed on the server)". Check Database → Extensions in your project.
  • pgvector: latest tag v0.8.7 on GitHub when checked. Each vector takes 4 × dimensions + 8 bytes, so one 1,536-dimension embedding is about 6 KB before indexes. Iterative index scans arrived in 0.8.0.
  • REST: PostgREST at https://<project>.wowsqlconnect.com/rest/v1. SQL functions are called at /rest/v1/rpc/<name> in standard PostgREST; test this on your own project. Send the user's token as Authorization: Bearer so RLS applies.
  • Auth: email and password, magic links, email or phone OTP, OAuth with 19 working providers, TOTP two-factor and optional Turnstile CAPTCHA (auth docs).
  • Plans: Free $0 (256 MB database, no extensions), Pro $25/month (10 GB database, 100,000 MAU, daily backups kept 7 days, Edge Functions), Scale $99/month (pricing). Regions: Mumbai, US East and Frankfurt.

How the pieces fit

  1. Ingest (server, service key): take a document, split it into chunks, call your embedding model, insert the document and its chunks. The service key bypasses RLS, so this code never runs in a browser.
  2. Ask (server, user token): verify the user's token, embed the question with the same model, call the retrieval function as the user so RLS filters the chunks, send the top chunks to your LLM, store the answer with its citations.
  3. Client: signs the user in with WoWSQL Auth and calls your ask endpoint. It never sees the embedding or LLM API keys.

The ask step can live on your own server or in an Edge Function on Pro.

Step 0: Check that pgvector is available

select name, default_version, installed_version
from pg_available_extensions
where name = 'vector';

If the row is there, enable it (create extension if not exists vector; or the dashboard toggle). If there's no row, the extension isn't installed on that server. You can still ship: skip the embedding column and use the search_chunks_text function from Step 3, which uses Postgres's built-in full-text search. For many FAQ, docs and support-bot use cases, keyword retrieval over well-cut chunks gets you surprisingly far, and you can add vectors later without changing the rest of the backend.

Step 1: The schema

create extension if not exists vector;

create table documents (
  id          bigint generated always as identity primary key,
  owner_id    uuid not null,
  title       text not null,
  source_url  text,
  content_sha text not null,              -- hash of the source text, for re-ingest
  created_at  timestamptz not null default now(),
  unique (owner_id, content_sha)
);

create table chunks (
  id           bigint generated always as identity primary key,
  document_id  bigint not null references documents(id) on delete cascade,
  owner_id     uuid not null,             -- copied from documents so RLS is a cheap check
  chunk_index  int not null,
  content      text not null,
  embedding    vector(1536),              -- must match your embedding model's output size
  embed_model  text not null,             -- which model produced the vector
  fts          tsvector generated always as (to_tsvector('english', content)) stored,
  unique (document_id, chunk_index)
);

create index chunks_embedding_hnsw on chunks using hnsw (embedding vector_cosine_ops);
create index chunks_fts_gin on chunks using gin (fts);
create index chunks_owner on chunks (owner_id);

create table chat_messages (
  id              bigint generated always as identity primary key,
  owner_id        uuid not null,
  role            text not null check (role in ('user', 'assistant')),
  content         text not null,
  cited_chunk_ids bigint[] not null default '{}',
  created_at      timestamptz not null default now()
);

Three choices worth copying. content_sha with a unique constraint makes re-ingesting the same file a no-op instead of a pile of duplicates. embed_model lets you re-embed gradually when you switch models, because vectors from different models can't be compared. And copying owner_id onto every chunk keeps the RLS check to one indexed column instead of a join.

Step 2: Row Level Security, and the trap with vector indexes

alter table documents     enable row level security;
alter table chunks        enable row level security;
alter table chat_messages enable row level security;

create policy "read own documents" on documents for select using (owner_id = auth.uid());
create policy "read own chunks"    on chunks    for select using (owner_id = auth.uid());
create policy "own messages"       on chat_messages for all
  using (owner_id = auth.uid()) with check (owner_id = auth.uid());
-- documents and chunks are written by your server with the service key

Here's the trap. An HNSW index finds approximate nearest neighbours first, and filters (including RLS policies) are applied afterwards. pgvector's README gives the example that if a filter matches 10% of rows, the default search returns only about 4 matching rows on average. In a multi-user app, each user owns a small slice of the table, so their searches can come back nearly empty.

We measured it: 20,000 rows, of which one user owned 200 (1%), with the HNSW index forced on. Asking for that user's 10 nearest chunks through the RLS policy returned 0 rows with iterative scans off and 10 rows with hnsw.iterative_scan = relaxed_order. That setting needs pgvector 0.8.0 or later, so check installed_version. The retrieval function below sets it for you. For a few very large tenants, the README also suggests partial indexes or partitioning by tenant.

Step 3: The retrieval function

This combines vector similarity with keyword search using reciprocal rank fusion, which catches both "meaning" matches and exact terms such as product codes and names:

create or replace function match_chunks(
  query_embedding vector(1536),
  query_text      text,
  match_count     int default 6
)
returns table (chunk_id bigint, document_id bigint, title text, content text, score float8)
language sql stable security invoker
set hnsw.iterative_scan = relaxed_order  -- keep scanning when RLS filters rows out
as $$
  with semantic as (
    select c.id, row_number() over (order by c.embedding <=> query_embedding) as r
    from chunks c
    order by c.embedding <=> query_embedding
    limit 30
  ),
  keyword as (
    select c.id, row_number() over (order by ts_rank_cd(c.fts, q) desc) as r
    from chunks c, websearch_to_tsquery('english', query_text) q
    where c.fts @@ q
    order by ts_rank_cd(c.fts, q) desc
    limit 30
  )
  select c.id, c.document_id, d.title, c.content,
         coalesce(1.0 / (60 + s.r), 0) + coalesce(1.0 / (60 + k.r), 0) as score
  from semantic s
  full join keyword k on k.id = s.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 match_count;
$$;

-- Fallback with no extension at all
create or replace function search_chunks_text(query_text text, match_count int default 6)
returns table (chunk_id bigint, document_id bigint, title text, content text, score float4)
language sql stable security invoker
as $$
  select c.id, c.document_id, d.title, c.content, ts_rank_cd(c.fts, q)
  from chunks c
  join documents d on d.id = c.document_id,
       websearch_to_tsquery('english', query_text) q
  where c.fts @@ q
  order by ts_rank_cd(c.fts, q) desc
  limit match_count;
$$;

security invoker means the function runs with the caller's rights, so the RLS policies on chunks and documents still apply. In our test, one user's search returned only her chunks, another user's returned only his, and a call with no signed-in user returned nothing.

Step 4: Ingest documents

// rag.ts (server only, Node 18+)
import { createHash } from 'node:crypto'
import { ProjectAuthClient } from '@wowsql/sdk'

const PROJECT_URL = process.env.WOWSQL_URL!         // https://myproject.wowsqlconnect.com
const ANON_KEY = process.env.WOWSQL_ANON_KEY!       // wowsql_anon_...
const SERVICE_KEY = process.env.WOWSQL_SERVICE_KEY! // wowsql_service_... (bypasses RLS)
const REST = `${PROJECT_URL}/rest/v1`

export type Embed = (texts: string[]) => Promise<number[][]> // your embedding provider
export type Generate = (prompt: string) => Promise<string>   // your LLM

const auth = new ProjectAuthClient({ projectUrl: PROJECT_URL, apiKey: ANON_KEY })
const asService = { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}`, 'Content-Type': 'application/json' }
const asUser = (token: string) => ({ apikey: ANON_KEY, Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' })
const vec = (v: number[]) => `[${v.join(',')}]` // pgvector text format

async function post(path: string, headers: Record<string, string>, body: unknown, prefer?: string) {
  const res = await fetch(`${REST}/${path}`, {
    method: 'POST',
    headers: prefer ? { ...headers, Prefer: prefer } : headers,
    body: JSON.stringify(body),
  })
  if (!res.ok) throw Object.assign(new Error(`${path}: ${res.status} ${await res.text()}`), { status: res.status })
  const text = await res.text() // inserts without Prefer return an empty body
  return text ? JSON.parse(text) : null
}

// Split on paragraphs, then pack paragraphs into chunks of about maxChars
export function chunkText(text: string, maxChars = 1500): string[] {
  const chunks: string[] = []
  let current = ''
  for (const para of text.split(/\n{2,}/).map(p => p.trim()).filter(Boolean)) {
    if (current && current.length + para.length > maxChars) { chunks.push(current); current = '' }
    current = current ? `${current}\n\n${para}` : para
  }
  if (current) chunks.push(current)
  return chunks
}

export async function ingestDocument(ownerId: string, title: string, text: string, embed: Embed, model: string) {
  const sha = createHash('sha256').update(text).digest('hex')
  let doc: { id: number }
  try {
    ;[doc] = await post('documents', asService, { owner_id: ownerId, title, content_sha: sha }, 'return=representation')
  } catch (e) {
    if ((e as { status?: number }).status === 409) return { skipped: true } // same text already ingested
    throw e
  }
  const pieces = chunkText(text)
  const vectors = await embed(pieces)
  await post('chunks', asService, pieces.map((content, i) => ({
    document_id: doc.id, owner_id: ownerId, chunk_index: i, content, embedding: vec(vectors[i]), embed_model: model,
  })))
  return { skipped: false, documentId: doc.id, chunks: pieces.length }
}

Embeddings travel as pgvector's text format ([0.1,0.2,...]), which Postgres casts into the vector column. The paragraph chunker is deliberately simple. For long technical documents, split on headings first, and add the document title to each chunk's text before embedding so a chunk still makes sense on its own.

Step 5: Answer questions

type Match = { chunk_id: number; document_id: number; title: string; content: string; score: number }

export async function ask(userToken: string, question: string, embed: Embed, generate: Generate) {
  const user = await auth.getUser(userToken) // rejects a bad or expired token
  const [qv] = await embed([question])
  // runs as the signed-in user, so RLS limits matches to their own chunks
  const matches: Match[] = await post('rpc/match_chunks', asUser(userToken), {
    query_embedding: vec(qv), query_text: question, match_count: 6,
  })
  if (matches.length === 0) return { answer: "I couldn't find that in your documents.", sources: [] }

  const context = matches.map((m, i) => `[${i + 1}] ${m.title}\n${m.content}`).join('\n\n')
  const answer = await generate(
    `Answer using only the sources below. Cite them like [1]. If the answer is not there, say so.\n\n${context}\n\nQuestion: ${question}`,
  )
  await post('chat_messages', asUser(userToken), [
    { owner_id: user.id, role: 'user', content: question, cited_chunk_ids: [] }, // bulk inserts need identical keys
    { owner_id: user.id, role: 'assistant', content: answer, cited_chunk_ids: matches.map(m => m.chunk_id) },
  ])
  return { answer, sources: matches.map(m => ({ title: m.title, chunkId: m.chunk_id })) }
}

We call the REST API with fetch instead of the SDK's WowSQLClient, because in @wowsql/sdk 3.10.0 the client always sends the API key as the bearer token, so RLS would see an anonymous caller. The empty cited_chunk_ids on the user message isn't decoration: PostgREST rejects a bulk insert whose objects have different keys.

Sizing it

At about 6 KB per 1,536-dimension vector, 100,000 chunks hold roughly 600 MB of raw vectors, and the HNSW index adds more on top. That fits within Pro's 10 GB database. If space gets tight, pgvector's halfvec type halves the vector size, or choose a model with fewer dimensions. Retrieval quality usually depends more on clean chunks than on the database, so measure answers on 30 to 50 real questions before tuning anything.

Where to run a Postgres RAG backend

pgvector Free plan Auth and RLS in the same project Notes
WoWSQL Listed as optional "if installed on the server"; extensions need Pro or Scale 256 MB DB, no extensions Yes Full-text fallback works on every plan
Supabase Documented: enable vector in Database → Extensions (guide) 500 MB DB, paused after 1 week idle (pricing) Yes Storage, Edge Functions and auth in the same project
Neon Available on every plan (docs) 1 GB storage per project, 100 CU-hours a month (pricing) Managed Better Auth listed on its plans Serverless Postgres with branching
Your own Postgres Install the package or build it (README) Your hardware You build it Full control, full responsibility

Checked 28 November 2026. If pgvector on day one is a hard requirement and you want it on a free plan, Supabase and Neon are ahead today. WoWSQL makes sense when you want the RAG tables next to your app's auth, REST API, storage and realtime in one place, or a database in Mumbai, US East or Frankfurt, and you can confirm vector in your project or start with full-text retrieval.

Related guides

FAQ

How do I build a RAG app backend on Postgres?

Create a documents table, a chunks table with an embedding column and a full-text tsvector column, and a chat messages table. Ingest documents on a server by chunking and embedding them, retrieve with one SQL function that ranks chunks by vector distance and keyword match, and enable Row Level Security so users only retrieve their own chunks.

Does WoWSQL support pgvector?

WoWSQL's docs list vector as "optional (if installed on the server)", and enabling any extension needs the Pro or Scale plan. We have not confirmed it is available on every project, so check Database → Extensions or run select * from pg_available_extensions where name = 'vector' in your project before you plan around it.

Can I build RAG on Postgres without pgvector?

Yes. Postgres has built-in full-text search: a generated tsvector column, a GIN index and websearch_to_tsquery give you ranked keyword retrieval with no extension. It misses paraphrased questions that embeddings would catch, but it is a solid start, and you can add vectors later.

Why does my pgvector search return fewer results than LIMIT?

Approximate indexes such as HNSW apply filters, including RLS policies, after scanning the index. When a user owns a small share of the rows, most candidates get filtered out. Set hnsw.iterative_scan = relaxed_order (pgvector 0.8.0 or later) so the index keeps scanning, or use partial indexes or partitioning per tenant.

How do I keep each user's documents private in a RAG app?

Store an owner_id on every chunk, enable RLS with using (owner_id = auth.uid()), and call the retrieval function as the signed-in user with their token, not with the service key. Mark the function security invoker so the policies apply inside it.

What embedding dimension should I use in Postgres?

Use exactly the output size of your embedding model, because vector(n) must match it. pgvector indexes vector columns up to 2,000 dimensions and halfvec up to 4,000. Each vector takes 4 × dimensions + 8 bytes, so smaller models save storage.

Create a free WoWSQL project · Pricing · Docs