Skip to main content

Production RAG Architecture: Crawl to Cited Answers (2026)

· 16 min read
Yassine El Haddad
Software Developer & Automation Specialist

I build production AI agents, web scrapers, and automation pipelines. Most of what I publish here comes from the actual problems they run into: proxies that get banned, anti-bot stacks that fingerprint your client, RAG that drifts when the underlying data moves. Stack: Python, TypeScript, Go, FastAPI, LangChain, Crawlee, Playwright, deployed on AWS, GCP, and Cloudflare.

A production RAG (retrieval-augmented generation) system crawls your content, splits it into section-sized chunks, embeds them in a vector database, retrieves and reranks the best matches for each question, and has an LLM answer only from those matches, with citations. Most RAG projects that disappoint in production get the model right and the plumbing wrong: chunks that cut sections in half, no reranking, and an index that silently goes stale.

This guide builds each stage with ready-to-run Python, and spends most of its time on the parts other guides skip: chunking, freshness and measurement.

StageToolKey decision
1. CrawlApify Website Content CrawlerClean Markdown per page, on a schedule
2. ChunkMarkdown RAG Chunker or LangChainOne section per chunk, ≤512 tokens, stable IDs
3. EmbedOpenAI text-embedding-3-small or local FastEmbedCost vs quality
4. StoreQdrant or pgvectorDedicated vector DB vs your existing Postgres
5. RetrieveDense search + Cohere rerank-v4.0-proTop 20 candidates, rerank to top 5
6. GenerateClaude (claude-opus-5-5)Answer only from sources, cite them
7. Stay freshStable chunk IDs + document_hash cleanupRe-embed only what changed

Install everything (latest stable versions as of October 2026; the code below targets them):

pip install apify-client==3.3.0 langchain-text-splitters==1.1.3 tiktoken==0.14.0 \
openai==3.35.1 fastembed==0.9.0 qdrant-client==1.19.1 cohere==7.2.0 anthropic==1.15.0

You need an Apify account, a Qdrant instance (docker run -p 6333:6333 qdrant/qdrant, or Qdrant Cloud's free tier), and API keys for the services you choose: OpenAI (optional), Cohere and Anthropic.

Why RAG fails: the failure modes​

Failure modeCauseImpactFix
Stale dataPages change, index doesn'tLLM cites outdated infoScheduled re-crawl + stable IDs + stale-chunk deletion (Stage 7)
Bad chunksFixed-size splitting cuts sections in halfIrrelevant retrievalSection-aware chunking (Stage 2)
Context-free chunksA chunk says "Set it to true" with no headingRetrieval can't tell what "it" isEmbed the section path with the chunk
Wrong embedding modelModel doesn't match your queriesLow recallBenchmark on your own questions
No rerankingVector similarity is approximateBest passage isn't firstCross-encoder reranking (Stage 5)
Hallucinated citationsLLM invents sourcesTrust erosionAnswer only from numbered sources, verify citations (Stage 6)

Stage 1: Crawl with Apify​

Website Content Crawler crawls a site and returns the main content of each page as Markdown. Its defaults already remove navigation, footers, cookie banners and dialogs.

from apify_client import ApifyClient

apify = ApifyClient("YOUR_APIFY_TOKEN")

run = apify.actor("apify/website-content-crawler").call(run_input={
"startUrls": [{"url": "https://docs.example.com"}],
"maxCrawlPages": 500,
"maxCrawlDepth": 5,
"crawlerType": "playwright:adaptive", # uses a browser only for pages that need it
})

documents = [
{
"url": item["url"],
"title": (item.get("metadata") or {}).get("title", ""),
"markdown": item.get("markdown") or item.get("text", ""),
"crawled_at": (item.get("crawl") or {}).get("loadedTime"),
}
for item in apify.dataset(run.default_dataset_id).iterate_items()
]
print(f"Crawled {len(documents)} pages")

In Apify Console you can put the same input on a schedule (daily for changelogs, weekly for reference docs), which Stage 7 builds on.

Alternative: Firecrawl​

For a quick, API-first crawl, Firecrawl returns the same kind of Markdown. The Firecrawl + Qdrant tutorial builds this pipeline with it, and for ad-hoc ingestion from Claude Desktop there is the Firecrawl MCP server. Apify fits better when the crawl runs on a schedule, needs logins or anti-bot handling, or you want crawling and chunking on one platform.


Stage 2: Chunking strategy​

Chunking decides what the retriever can find. Two published benchmarks set a sensible starting point:

SourceFinding
Chroma, Evaluating Chunking Strategies (2024)Recursive splitting at 400 tokens reached 89.5% recall with text-embedding-3-large; adding overlap slightly lowered it (88.1%)
NVIDIA, Finding the Best Chunking Strategy (2025)256–512 tokens for factoid questions, 1,024 for analytical ones

So: chunks of about 512 tokens, measured in tokens rather than characters, each inside one section of the page. Character counts drift with language: 2,000 characters is about 500 tokens of English, but far more for Chinese or Japanese.

Option A: Recursive splitting with LangChain (free, local)​

import hashlib
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
encoding_name="cl100k_base",
chunk_size=512, # tokens
chunk_overlap=50,
separators=["\n## ", "\n### ", "\n\n", "\n", " "],
)

chunks = []
for doc in documents:
doc_hash = hashlib.sha256(doc["markdown"].encode()).hexdigest()[:16]
for i, text in enumerate(splitter.split_text(doc["markdown"])):
chunks.append({
"id": f"{doc['url']}#{i}",
"text": text,
"source_url": doc["url"],
"title": doc["title"],
"section": "",
"document_hash": doc_hash,
})

The separators prefer heading breaks but don't enforce them, so a chunk can straddle two sections, it carries no record of its section, and its ID is a position that shifts when the page changes.

Option B: Section-aware chunks with Markdown RAG Chunker​

Markdown RAG Chunker is an Apify Actor built for this stage. It splits each page on its #, ## and ### headings first, so a chunk never crosses a section boundary, and re-splits only sections over 512 tokens. Each chunk comes back with the fields production RAG needs:

FieldProduction use
embedding_textSection path + content (Billing > Refunds\n\n...). Embed this, so "Set it to true" still knows what "it" is.
chunk_idStable ID from the source and content. Unchanged sections keep it across crawls, so upserts are idempotent.
document_hashFingerprint of the page, to delete stale chunks after it changes
header_pathSection path for metadata filters and citations
token_countExact token count, so no chunk exceeds your embedding model's limit
import hashlib
from concurrent.futures import ThreadPoolExecutor

def page_hash(markdown: str) -> str:
# The same value the chunker returns as document_hash for markdown_text input
return hashlib.sha256(markdown.encode("utf-8")).hexdigest()[:16]

def chunk_page(doc: dict) -> list[dict]:
run = apify.actor("codepoetry/markdown-rag-chunker").call(run_input={
"markdown_text": doc["markdown"],
"source_id": doc["url"], # scopes chunk IDs to this page
"max_chunks": 600, # budget guard: an oversized page fails for $0.001
})
if run is None or run.status != "SUCCEEDED":
print(f"Skipped {doc['url']}: {run.status_message if run else 'run did not start'}")
return []
return [
{
"id": item["chunk_id"],
"text": item["embedding_text"],
"content": item["content"],
"source_url": item["source"],
"title": doc["title"],
"section": item["header_path"],
"document_hash": item["document_hash"],
}
for item in apify.dataset(run.default_dataset_id).iterate_items()
]

indexed = {} # {source_url: document_hash} already in the index; see Stage 7
todo = [d for d in documents if d["markdown"] and indexed.get(d["url"]) != page_hash(d["markdown"])]

with ThreadPoolExecutor(max_workers=4) as pool: # parallel runs: same cost, less waiting
chunks = [c for page_chunks in pool.map(chunk_page, todo) for c in page_chunks]

Each run chunks one page and costs $0.001, plus $0.80 per 1,000 chunks on Apify's free plan; a first pass over 500 pages producing 2,000 chunks costs about $2.10. On later crawls, pages whose Markdown hash matches the index are never sent, so they cost $0 and skip embedding too. max_chunks stops a runaway page before any chunk is billed, and the default 1 GB of memory keeps each run at a single $0.001 start event.

The Actor also takes a document URL instead of Markdown (PDF, DOCX, PPTX, XLSX, EPUB, HTML), which covers non-web sources: set markdown_file to the file's URL.

Option A: LangChainOption B: Markdown RAG Chunker
Section boundariesPreferred, not guaranteedAlways respected
Section context in the vectorNoYes (embedding_text)
Stable IDsPositionalContent-based (chunk_id)
Skip unchanged pagesCompare your own hashdocument_hash matches the local hash
CostFree$0.80 / 1,000 chunks + $0.001 / run

Use Option A for a prototype. Use Option B once the index has to stay correct on a schedule.


Stage 3: Embedding​

Option A: OpenAI​

from openai import OpenAI

openai_client = OpenAI()

def embed_texts(texts: list[str], batch_size: int = 100) -> list[list[float]]:
vectors = []
for start in range(0, len(texts), batch_size):
response = openai_client.embeddings.create(
model="text-embedding-3-small",
input=texts[start:start + batch_size],
)
vectors.extend(item.embedding for item in response.data)
return vectors

embeddings = embed_texts([c["text"] for c in chunks])

Option B: Local with FastEmbed (free, CPU)​

from fastembed import TextEmbedding

local_model = TextEmbedding(model_name="BAAI/bge-small-en-v1.5") # 384 dimensions

def embed_texts(texts: list[str]) -> list[list[float]]:
return [v.tolist() for v in local_model.embed(texts)]

embeddings = embed_texts([c["text"] for c in chunks])

Embedding model comparison​

ModelDimensionsCostRuns
OpenAI text-embedding-3-large3072$0.13 / 1M tokensAPI
OpenAI text-embedding-3-small1536$0.02 / 1M tokensAPI
BAAI/bge-small-en-v1.5 (FastEmbed)384FreeLocal CPU
sentence-transformers/all-MiniLM-L6-v2 (FastEmbed)384FreeLocal CPU

OpenAI prices are from the OpenAI API pricing page. At $0.02 per million tokens, embedding 2,000 chunks of ~500 tokens costs about two cents, so start with text-embedding-3-small and move to a local model only if volume makes the bill matter. Whichever you choose, embed queries with the same model as the documents.


Stage 4: Vector storage​

Option A: Qdrant​

import uuid
from qdrant_client import QdrantClient, models

qdrant = QdrantClient(url="http://localhost:6333")
COLLECTION = "docs"

if not qdrant.collection_exists(COLLECTION):
qdrant.create_collection(
collection_name=COLLECTION,
vectors_config=models.VectorParams(
size=1536, # 384 for the FastEmbed models
distance=models.Distance.COSINE,
),
)

points = [
models.PointStruct(
id=str(uuid.uuid5(uuid.NAMESPACE_URL, c["id"])), # Qdrant IDs are UUIDs or integers
vector=vector,
payload={k: v for k, v in c.items() if k != "id"},
)
for c, vector in zip(chunks, embeddings)
]
for start in range(0, len(points), 100):
qdrant.upsert(collection_name=COLLECTION, points=points[start:start + 100])
print(f"Indexed {len(points)} chunks")

Deriving the point ID from the chunk ID makes the upsert idempotent: running it again overwrites points instead of duplicating them. For keyword-heavy queries (error codes, product names), add BM25 sparse vectors and fuse both rankings; the Firecrawl + Qdrant tutorial and its companion repo show hybrid search end to end.

Option B: pgvector (if you already run PostgreSQL)​

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE doc_chunks (
chunk_id TEXT PRIMARY KEY,
text TEXT NOT NULL,
embedding vector(1536), -- 384 for the FastEmbed models
source_url TEXT NOT NULL,
section TEXT,
document_hash TEXT
);

CREATE INDEX ON doc_chunks USING hnsw (embedding vector_cosine_ops);

pgvector's HNSW index gives a better speed-recall tradeoff than IVFFlat and can be created on an empty table. Upsert with INSERT ... ON CONFLICT (chunk_id) DO UPDATE.


Stage 5: Retrieval with reranking​

Vector search finds candidates; a cross-encoder reranker reads each candidate against the query and orders them by actual relevance. Retrieve 20, rerank to 5.

import cohere

co = cohere.ClientV2() # reads CO_API_KEY

def retrieve_and_rerank(query: str, top_k: int = 5) -> list[dict]:
candidates = qdrant.query_points(
collection_name=COLLECTION,
query=embed_texts([query])[0],
limit=20,
with_payload=True,
).points

reranked = co.rerank(
model="rerank-v4.0-pro",
query=query,
documents=[p.payload.get("content", p.payload["text"]) for p in candidates],
top_n=top_k,
)
return [
{
"text": candidates[r.index].payload.get("content", candidates[r.index].payload["text"]),
"score": r.relevance_score,
"source_url": candidates[r.index].payload["source_url"],
"title": candidates[r.index].payload["title"],
"section": candidates[r.index].payload.get("section", ""),
}
for r in reranked.results
]

Measure the gain on your own questions (see Measuring RAG quality) before deciding reranking is worth its latency and cost for your traffic.


Stage 6: Generation with citations​

import anthropic

claude = anthropic.Anthropic() # reads ANTHROPIC_API_KEY

def answer_with_rag(query: str) -> str:
sources = retrieve_and_rerank(query, top_k=5)
context = "\n\n".join(
f"[Source {i + 1}] {s['title']} > {s['section']} ({s['source_url']})\n{s['text']}"
for i, s in enumerate(sources)
)
response = claude.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{
"role": "user",
"content": (
"Answer the question using ONLY the sources below. Cite them as [Source N]. "
"If the sources don't contain the answer, say so.\n\n"
f"Sources:\n{context}\n\nQuestion: {query}"
),
}],
)
return "".join(block.text for block in response.content if block.type == "text")

Then check the output: every [Source N] in the answer must be a number from 1 to len(sources), and the response should return the source URLs alongside the text so users can verify.


Stage 7: Keeping the index fresh​

Stale data is the most common production RAG failure, and rebuilding the whole index on every crawl is slow and wasteful. With stable chunk IDs, freshness is three steps per scheduled run:

  1. Re-crawl, then re-chunk only what changed. Load the hashes already in Qdrant and pass them to Stage 2 as indexed; unchanged pages cost nothing to chunk or embed:
def indexed_hashes() -> dict[str, str]:
if not qdrant.collection_exists(COLLECTION):
return {}
hashes, offset = {}, None
while True:
points, offset = qdrant.scroll(COLLECTION, limit=1000, offset=offset,
with_payload=["source_url", "document_hash"])
hashes.update({p.payload["source_url"]: p.payload["document_hash"] for p in points})
if offset is None:
return hashes

indexed = indexed_hashes()
  1. Upsert the new chunks by chunk_id. Sections that didn't change overwrite themselves with identical data.
  2. Delete stale chunks: for each re-chunked page, remove points with the same source_url and a different document_hash.
for url, doc_hash in {c["source_url"]: c["document_hash"] for c in chunks}.items():
qdrant.delete(
collection_name=COLLECTION,
points_selector=models.FilterSelector(filter=models.Filter(
must=[models.FieldCondition(key="source_url", match=models.MatchValue(value=url))],
must_not=[models.FieldCondition(key="document_hash", match=models.MatchValue(value=doc_hash))],
)),
)

When you do need a full rebuild (a new embedding model, a new chunk size), have your app query a collection alias such as docs_live instead of a collection name. Index into a new collection, then repoint the alias in one call, so queries never hit an empty index:

qdrant.update_collection_aliases(change_aliases_operations=[
models.CreateAliasOperation(create_alias=models.CreateAlias(
collection_name="docs_v2", alias_name="docs_live",
)),
])

Measuring RAG quality​

You can't improve what you don't measure. Write 50 to 100 real questions with the page that answers each, then track:

MetricWhat it measuresHow to compute
Recall@kIs the right chunk in the top k results?Share of questions whose answering page appears in the top 5
Answer accuracyIs the generated answer correct?Human review or an LLM judge against reference answers
FaithfulnessDoes every claim come from the retrieved sources?Check each cited claim against its source chunk

Fix retrieval before generation: if Recall@5 is low, change chunking, embeddings or reranking first. No prompt can cite a passage the retriever never returned.


Frequently Asked Questions

Seven stages: crawl content to Markdown, split it into section-sized chunks of about 512 tokens, embed each chunk, store the vectors in a database such as Qdrant or pgvector, retrieve and rerank the best matches for each question, have an LLM answer only from those matches with citations, and keep the index fresh by upserting changed chunks and deleting stale ones.

Start with about 512 tokens, measured in tokens rather than characters, and keep each chunk inside one section of the page. Chroma's 2024 evaluation found 400-token recursive chunks reached 89.5% recall, and NVIDIA's 2025 study recommends 256 to 512 tokens for factoid questions and 1,024 for analytical ones.

Re-crawl on a schedule, give every chunk a stable ID derived from its source and content, upsert by that ID, and delete chunks whose source matches a re-crawled page but whose document hash changed. Comparing each page's Markdown hash with the stored document hash before chunking skips unchanged pages, so only edited pages are re-chunked and re-embedded.

Qdrant if you want a dedicated vector database with filtering, sparse vectors for hybrid search, and collection aliases for zero-downtime rebuilds. pgvector if you already run PostgreSQL and want one less system. Pinecone if you want a fully managed service.

For production RAG with quality requirements, usually yes: retrieve about 20 candidates by vector similarity and let a cross-encoder such as Cohere rerank-v4.0-pro pick the top 5. Measure Recall@5 with and without it on your own questions to confirm the gain is worth the extra call.

Convert them to Markdown and send them through the same pipeline. Markdown RAG Chunker accepts a URL to a PDF, DOCX, PPTX, XLSX or EPUB file, converts it and returns section-aware chunks. Scanned PDFs need OCR first, because they contain no text layer.

Apify for scheduled, large or protected crawls, and when you want crawling and chunking on one platform. Firecrawl for quick, API-first crawls and interactive use through its MCP server. Both return Markdown that the rest of this pipeline accepts unchanged.

Number the sources in the prompt and instruct the model to answer only from them, check that every [Source N] in the answer refers to a source you actually sent, and return the source URLs with the answer so users can verify.

Yes. A local instruct model served by Ollama works for internal documentation QA, with lower answer quality on nuanced questions. See the Self-Host AI Stack guide for Ollama setup.


Production RAG comes down to fresh crawls, section-aware chunks, reranked retrieval and grounded answers, measured on your own questions. Get those right before reaching for more complex architectures.

Next step: crawl your site with Website Content Crawler and chunk it with Markdown RAG Chunker, or clone the Firecrawl + Qdrant companion repo for a complete pipeline you can run today.

Common mistakes and fixes

RAG responses include outdated information despite re-crawling.

Upsert chunks by a stable chunk ID, then delete points whose source URL matches a re-crawled page and whose document_hash differs from the new one (see Stage 7).

Vector search returns irrelevant chunks for specific queries.

Chunk by section instead of fixed windows, embed the section path with each chunk, rerank the top 20 candidates, and add BM25 hybrid search for exact terms like error codes.

Embedding costs are higher than expected.

Embed only changed pages: compare each page's Markdown hash with the stored document_hash before chunking (Stage 7), or switch to a local FastEmbed model, which runs on CPU for free.

Advertise on this page