123DevOps··8 min read

RAG (Retrieval-Augmented Generation): giving AI secure access to your company's documents

Learn how RAG works — ingestion, embeddings, vector databases, hybrid search, and generation with citations — and how to implement it while respecting permissions, protecting sensitive data, and measuring answer quality.

AI

Ask a generic AI assistant “what is the rollback procedure for the payments service?” and it will answer confidently — and probably wrong. The model has never read your runbook. RAG (Retrieval-Augmented Generation) solves this in a simple way: before generating the answer, the system retrieves the relevant passages from your documents and hands them to the model along with the question.

The problem: the model doesn’t know your company

An LLM learns from a large volume of text up to a cutoff date (knowledge cutoff). That leads to three limitations:

  • It doesn’t know your internal documents: wikis, runbooks, postmortems, and architecture decisions were never part of its training.
  • It goes stale: whatever changed after the cutoff date doesn’t exist for the model.
  • It hallucinates: when it doesn’t know, the model tends to produce plausible text instead of admitting the gap — it was trained to predict the next token, not to check facts (see how an LLM works).

RAG tackles all three: knowledge lives outside the model, in an index you control, update, and audit.

How RAG works

The pipeline has two phases.

Ingestion: preparing the knowledge

  1. Load the documents (wiki, Git repositories, PDFs, tickets).
  2. Split them into manageable passages (chunks).
  3. Generate the embedding for each chunk.
  4. Store vector, text, and metadata (source, date, permissions) in a vector database.

Query: answering the question

  1. Generate the embedding of the question.
  2. Retrieve the top-k most similar chunks.
  3. Optionally, rerank the candidates with a more precise model.
  4. Build the prompt with instructions, chunks, and their sources.
  5. Generate the answer and cite the sources used.
INGESTION (continuous or batch)
  documents ──> load ──> split into chunks ──> embeddings ──> vector database
                                               (vector + text + source + permissions)

QUERY (on every question)
  question ──> embedding ──> top-k search ──────────> rerank (optional)
                             (filtered by permission)        │
                                                             v
  answer with citations <── LLM <── prompt (instructions + chunks + sources)

Embeddings and similarity, without the math

An embedding is a list of numbers (a vector) that represents the meaning of a text. An embedding model is trained so that texts with similar meanings produce vectors that are close to each other. “How do I revert a deploy?” and “rollback procedure” end up near each other, even without sharing a single word.

Think of a map: each chunk becomes a point, and searching means finding the points closest to the question. Closeness is usually measured with cosine similarity, which compares the direction of the vectors. Since dimensions and quality vary across embedding models, use the same model for ingestion and for queries — switching models means reindexing everything.

Where to store the vectors

The choice depends more on what you already operate than on performance differences:

  • pgvector: a PostgreSQL extension; great if you already run Postgres and want vectors next to your relational data.
  • OpenSearch: text and vector search in the same engine, handy for hybrid search.
  • Qdrant, Weaviate, and Milvus: dedicated vector databases, with metadata filters and managed options.
  • Chroma: lightweight, common in prototypes and local development.

With pgvector, a permission-filtered search fits in a single SQL query:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  id        bigserial PRIMARY KEY,
  source    text   NOT NULL,      -- URL or path of the original document
  content   text   NOT NULL,
  groups    text[] NOT NULL,      -- groups allowed to read this chunk
  embedding vector(1024)          -- the dimension depends on the embedding model
);

-- the 5 closest chunks the user is allowed to see
SELECT source, content
FROM chunks
WHERE groups && $2                -- overlap with the user's groups
ORDER BY embedding <=> $1         -- <=> is cosine distance in pgvector
LIMIT 5;

Chunking strategies

Strategy How it works When to use it
Fixed size with overlap Cuts every N tokens and repeats a piece between neighboring chunks Simple starting point; text without clear structure
By headings and sections Follows the document structure (Markdown, HTML, chapters) Wikis, runbooks, and technical documentation
Semantic Cuts where the topic changes, using similarity between sentences Long, flowing text, when the others fall short

Chunks that are too small lose context; chunks that are too large dilute the meaning. Store the section title with each chunk — “Step 3: restart the pod” means nothing unless you know which runbook it came from.

Hybrid search: keywords + vectors

Vector search handles synonyms and paraphrases well, but it stumbles on exact terms: error codes, service names, incident IDs. Keyword search (such as BM25) is the opposite. Hybrid search runs both and merges the results — a common technique is Reciprocal Rank Fusion (RRF), which scores each document by the position where it appears in each list. In technical content, full of acronyms and identifiers, this makes a difference.

The flow in Python (sketch)

The code below is illustrative: the functions marked PLACEHOLDER depend on your embedding model, vector database, and LLM provider.

def split_into_chunks(text, size=800, overlap=100):
    # simplified: splits by characters; in practice, prefer tokens or sections
    step = size - overlap
    return [text[i:i + size] for i in range(0, len(text), step)]


def embed(text):                               # PLACEHOLDER: your embedding model
    raise NotImplementedError


def save_chunk(**fields):                      # PLACEHOLDER: writes to the vector database
    raise NotImplementedError


def search_similar(vector, groups, k=5):       # PLACEHOLDER: search with permission filter
    raise NotImplementedError


def call_llm(prompt):                          # PLACEHOLDER: provider API or local server
    raise NotImplementedError


def index(document):
    for i, chunk in enumerate(split_into_chunks(document["text"])):
        save_chunk(
            id=f'{document["id"]}#{i}',
            content=chunk,
            embedding=embed(chunk),
            source=document["url"],
            groups=document["groups_with_access"],
        )


def answer(question, user):
    chunks = search_similar(embed(question), user["groups"], k=5)
    context = "\n\n".join(
        f'[{n}] ({c["source"]})\n{c["content"]}' for n, c in enumerate(chunks, start=1)
    )
    prompt = (
        "Answer using only the sources below and cite them as [n]. "
        "If the answer is not in the sources, say you could not find it.\n\n"
        f"Sources:\n{context}\n\nQuestion: {question}"
    )
    return call_llm(prompt)

The prompt restricts the answer to the sources, asks for citations, and allows “I couldn’t find it.” That reduces hallucinations, but doesn’t eliminate them.

Security: RAG must not bypass permissions

An assistant with access to “all documents” is a leak waiting to happen.

  • Filter by permission at retrieval time: apply the user’s ACL in the search, as in WHERE groups && $2, and keep permissions in sync with the source. Never rely on the prompt (“don’t show HR documents”) to hide information: if a chunk reached the model, it can show up in the answer.
  • Don’t index secrets or personal data: run documents through credential and PII detection before ingestion. A password forgotten on a wiki page becomes a password in the chatbot’s answer.
  • Indirect prompt injection: a document may contain something like “ignore the previous instructions and…”. Treat retrieved content as untrusted data, clearly separate it from instructions, and limit what the system can do based on it. More details in AI application security with the OWASP Top 10 for LLMs.
  • Auditing: record who asked what, which chunks were retrieved, and what was answered — masking sensitive data in the logs.

How to evaluate it

A RAG system can fail at two points, and you need to measure each one separately:

  • Retrieval quality: are the right chunks among the top-k? Build a set of questions with their expected documents and measure the hit rate (recall@k).
  • Answer faithfulness: is the answer grounded in the sources, or did it make something up? Do the citations point to chunks that actually say that?

Run these evaluations on every change to chunking, embedding model, or prompt. The article on LLMOps: evaluation and observability shows how to automate this in CI.

RAG, fine-tuning, or long context?

Approach Good for Limitations
RAG Changing knowledge, many sources, answers with citations and access control Depends on search quality; more moving parts to operate
Fine-tuning Teaching style, format, or a specific task Poor for facts that change; retraining is expensive; hard to “forget” information
Long context Analyzing a few large documents at once Cost and latency grow with size; doesn’t scale to an entire knowledge base

In practice, they combine; fine-tuning only comes in when the problem is behavior, not knowledge.

DevOps use cases

  • Searching runbooks and postmortems: during an incident, “have we seen this Redis connection error before?” finds the postmortem from months ago and the step that fixed it.
  • Internal platform documentation: “how do I request a new database?” answers with the right portal link instead of turning into yet another ticket.
  • Onboarding: questions about architecture and conventions answered with the source for deeper reading.

In every case, the answer is a starting point: people check the source before running any command in production.

Checklist

  • Document sources mapped, with an owner and update frequency
  • Chunking strategy defined and tested with real questions
  • Same embedding model for ingestion and queries
  • Hybrid search evaluated for technical terms and error codes
  • Permission filter applied at retrieval time and synced with the source
  • Secrets and personal data scanning before indexing
  • Retrieval and faithfulness evaluation running on every change

In RAG, the model is just the writer: the quality and security of the answers are decided in the search.

Get updates on new posts and stay in the loop!