All articles

English

October 25, 20264 min read

RAG with PostgreSQL: Retrieval, Permissions, and Answers You Can Verify

A practical design for PostgreSQL-backed RAG: versioned ingestion, permission-aware retrieval, useful citations, and separate tests for search quality and answer quality.

Portrait of Tran Kim Dat

Tran Kim Dat

Software Engineer

The retrieval-augmented generation pipeline published in Neon's January 2025 pgrag article.
The retrieval-augmented generation pipeline published in Neon's January 2025 pgrag article. Image: Neon / George MacKerron. Original source - Full-size image

A useful retrieval-augmented generation system has to answer two questions before it writes a sentence: which evidence is relevant, and which evidence is this person allowed to see? A fluent answer is a weak success signal when the search quietly missed the current policy or included another customer's document.

Consider an illustrative support assistant that answers questions about a product's setup guides and internal runbooks. PostgreSQL can hold the document metadata, permissions, ingestion state, and searchable chunks together. The design below is an architectural proposal for that kind of application, rather than a claim about a particular production deployment.

Keep document identity separate from searchable chunks

A document needs a stable identity even as its text changes. Give each imported version a source identifier, a content hash, a revision, and a lifecycle state. A chunk should point back to that version and retain enough location information to recover the surrounding passage. A search result without that lineage is difficult to debug and impossible to cite precisely.

Publish ingestion results as a complete version. Parse and validate the source, build its chunks and embeddings, then switch the active revision only after the new set is ready. Otherwise a failed import can leave half of a policy available while the previous version has already disappeared. Deletion also needs a path: retire the source, exclude its chunks, and expire cached answers that depend on it.

  • documents: stable source identity, owner, and current revision.

  • document_versions: source hash, effective date, ingestion status, and canonical URL.

  • chunks: version reference, section label, text, embedding, and permission metadata.

  • retrieval_runs: request identifier, selected chunk identifiers, and configuration version; avoid retaining private text by default.

Apply access rules before evidence reaches the model

Resolve the user and tenant from an authenticated server session. Do not trust a tenant identifier supplied in the prompt or request body. Retrieval must enforce the same access rules as the document reader, including document-level restrictions inside a tenant. A tenant predicate alone is insufficient when some documents are private to a team.

Row-level security can add a database boundary, provided the runtime role is actually subject to it. Table owners and roles with bypass privileges need particular attention. Set any session-derived context within the transaction that runs the query, especially with transaction pooling. A prompt telling the model to ignore unauthorized text cannot repair an earlier disclosure.

This illustrative query assumes a pgvector embedding column and an access table maintained by trusted application code. All parameters come from the server's authorization and embedding steps; $1 is the query vector, $2 the tenant, and $3 the verified user. The deployed schema and embedding dimension must be defined separately.

SELECT c.id, c.document_version_id, c.section, c.body,
       c.embedding <=> $1::vector AS distance
FROM chunks AS c
JOIN document_versions AS v ON v.id = c.document_version_id
WHERE v.status = 'active'
  AND c.tenant_id = $2
  AND EXISTS (
    SELECT 1 FROM document_access AS a
    WHERE a.document_id = v.document_id AND a.user_id = $3
  )
ORDER BY c.embedding <=> $1::vector
LIMIT 8;

Choose search behavior from the questions

Semantic similarity is helpful for paraphrases; lexical search is useful for exact error codes, product identifiers, and names. A practical starting point is to evaluate both paths on the same question set and combine their ranked results when that improves retrieval. Avoid adding raw lexical scores to vector distances because their scales mean different things.

pgvector's documentation distinguishes exact search from approximate indexes. With an approximate index, selective filtering can reduce the number of returned neighbors. Measure recall after applying real tenant and document restrictions. Compare with an exact-search baseline before tuning scan settings or introducing partitions. An index that looks fast on an unrestricted benchmark may behave differently for a small tenant.

Make citations a server-owned mapping

Assign short evidence identifiers to the retrieved passages, such as source-1 and source-2. Ask the model to associate claims with these identifiers. The application then resolves them to the actual document revision, section, and authorized destination. Never let a generated URL become a trusted citation just because it looks plausible.

Validate that every returned evidence identifier belongs to the retrieved set. That catches invented references, but it does not prove that a passage supports a claim. Review support separately. When the evidence is incomplete, the product should explain what it can establish and ask a narrower question or decline the unsupported part.

Evaluate retrieval and generation independently

Build cases with a question, the user's access context, and expected supporting documents. Include stale versions, ambiguous product names, deleted documents, exact identifiers, and questions whose answer should be unavailable. First check whether retrieval found authorized evidence. Then judge whether the answer used it correctly.

  • Retrieval: supporting-document recall, irrelevant context, and access isolation.

  • Generation: supported claims, correct citations, and appropriate uncertainty.

  • Operations: ingestion delay, time to first useful response, end-to-end latency, and cost per request.

My starting design would favor a small, auditable retrieval pipeline over an elaborate agent loop. Keep identity, evidence selection, and citation resolution in ordinary application code. Add reranking or query rewriting only when the evaluation set exposes a problem they can solve.

Continue reading

Turn retrieval failures into release tests

Primary sources

pgvector: distance operators, filtering, indexes, and multitenancy

PostgreSQL: row security policies and role behavior

Continue reading

More field notes.

View all articles
Langfuse experiments table showing selected runs, model metadata, latency and error counts.
EnglishOct 25, 2026

LLM Evaluation as a Release Gate: From Good Demos to Regression Tests

Build an evaluation process that catches AI regressions before release: representative datasets, deterministic checks, calibrated reviewers, and explicit quality budgets.

AI · developer-tools · evaluation · reliability · testing

Read article
The AI SDK developer tools interface from Vercel's AI SDK 6 article, used to inspect model calls and their outputs.
EnglishOct 25, 2026

Structured LLM Outputs: Schemas, Validation, and Safe Application Boundaries

Move AI output into application logic safely: small schemas, explicit uncertainty, runtime validation, semantic checks, and server-owned authorization before any action.

AI · TypeScript · architecture · llm · security

Read article
Archival v0 chat interface from Vercel's September 2024 AI SDK 3.4 article; an example of an AI SDK-powered interface.
EnglishOct 25, 2026

Streaming AI Interfaces: Cancellation, Recovery, and Honest Progress

A streaming response needs more than a typing effect. Design explicit states, useful stop and retry behavior, durable message identity, and accessible progress feedback.

AI · React · UX · architecture · reliability

Read article

Have a product worth building carefully?

Start a conversation