Labs › ai-foundations

Build Your Own RAG System

Build a RAG system from naive dense retrieval to hybrid BM25+dense with RRF fusion to cross-encoder reranking. Wire it into Spring via LangChain4j's ContentRetriever interface so any Java AI application can use your Python backend as its knowledge source.

python 3.12 advanced ~8h build · ~3h read ~500 LoC (v3)
v0: Naive RAG — chunk, embed, retrieve, generatev1: Hybrid retrieval — BM25 + dense with RRF fusionv2: Reranking — cross-encoder for precision
☕ Java/Spring integration included service client

Why this lab exists

Every AI assistant that “knows about your documents” is a RAG system. Notion AI, GitHub Copilot’s codebase context, customer support bots that answer from internal wikis — they all share the same fundamental architecture: retrieve relevant context, then generate an answer conditioned on that context.

You’ve read that RAG stands for Retrieval-Augmented Generation. You’ve seen the diagram: embed the query, find similar chunks, stuff them into the prompt. But until you’ve implemented the chunking overlap, until you’ve watched hybrid retrieval fail to beat dense retrieval because of a one-line tokenizer, until you’ve measured a cross-encoder reranker lift hit@3 from 68% to 73% on a real benchmark and paid for it in latency — you don’t know it.

This lab builds RAG from the simplest possible baseline to the two-stage retrieval pattern used in production. Each version is a targeted fix for a measured weakness of the previous one.

What we’re building

A RAG system in Python, implemented across three stages. Each stage adds one layer and measures its impact on retrieval quality (Recall@3).

We build:

  • Document chunking with configurable size and overlap
  • Dense retrieval via sentence-transformers bi-encoder (all-MiniLM-L6-v2, 384-dim)
  • BM25 sparse retrieval via rank-bm25
  • Reciprocal Rank Fusion to combine both retrievers
  • Cross-encoder reranking (cross-encoder/ms-marco-MiniLM-L-6-v2)
  • FastAPI server with /ingest, /query, /stats, and /health endpoints
  • A simple Recall@3 evaluator to measure retrieval quality
  • scripts/bench.py, which runs all three versions on two public BEIR datasets with human relevance labels and times every stage

We explicitly skip (and why):

  • Vector databases (FAISS, Pinecone) — covered in “What the Toy Misses”; our numpy approach is O(N) which is fine for demonstration but won’t scale to 1M chunks
  • Document parsing (PDF, HTML) — we take plain text; real ingestion pipelines need structure-aware parsers
  • Persistent storage — the index lives in memory; restart wipes it
  • Fine-tuned embeddings — all-MiniLM-L6-v2 is a general model; domain-specific fine-tuning can help on narrow corpora, but this lab doesn’t measure it

Mental model

RAG is a two-step process. The goal is to answer questions about a document corpus without fine-tuning the LLM on it.

Step 1 — Retrieval: find the chunks of text most likely to contain the answer.

Step 2 — Generation: pass those chunks to the LLM as context. Answer the question using ONLY that context.

The framing that makes it concrete: an LLM without retrieval is like a doctor answering questions from memory alone — the doctor might be brilliant, but they can only recall what they learned during training. With retrieval, the doctor has access to the patient’s chart in front of them. The chart is accurate, current, and specific to this patient. The doctor’s job is to interpret the chart, not to recall facts from memory.

                        Ingestion (offline)
                        ─────────────────
  Documents
      │
      ▼
  Chunk (512 tokens, 50 overlap)
      │
      ▼
  Embed each chunk (bi-encoder)
      │
      ▼
  Store: numpy array + BM25 index

                        Query (online)
                        ─────────────
  Question
      │
      ├──► Embed question (bi-encoder) ──► cosine sim ──► dense top-20
      │
      └──► Tokenize (BM25)             ──► BM25 scores ──► sparse top-20
                        │
                        ▼
                   RRF fusion
                        │
                        ▼
              (v2) Cross-encoder rerank top-20
                        │
                        ▼
                  Top-3 chunks
                        │
                        ▼
              LLM (with chunks as context)
                        │
                        ▼
                    Answer

The retrieval step is what makes the answer trustworthy. The LLM is instructed to answer from the provided context only. If the context is wrong, the answer will be wrong — so retrieval quality is the critical path.

Prerequisites

  • Python 3.12
  • Basic understanding of transformers — specifically what “embedding” means (the transformer lab covers this)
  • Familiarity with BM25 is helpful but not required (explained inline)
  • An OpenAI-compatible LLM endpoint for the generation step (the transformer lab’s FastAPI server works)

Stage-by-stage build

Stage 0 Naive RAG — chunk, embed, retrieve, generate ~120 LoC ›
  • Implement chunk_document() with fixed-size chunks and overlap
  • Implement embed_texts() using sentence-transformers, L2-normalized
  • Implement cosine_similarity_top_k() using numpy matrix multiply
  • Wire into NaiveRag with ingest() and query() methods
  • Write tests: chunking preserves content, embed returns (N, 384), cosine similarity = 1.0 for identical text

The core insight of dense retrieval: convert both documents and queries to the same vector space, then measure distance. Similar meaning → small distance → high cosine similarity.

Why 512 tokens?

LLMs have a context window limit. GPT-4o’s is 128k tokens; a local model might be 4k. You need to fit the top-k chunks plus the question plus the answer in that window. With 512-token chunks and top-3 retrieval, you’re using about 1,500 tokens for context — comfortable even for a 4k context model. (We chunk by characters: 2,048 characters ≈ 512 tokens at ~4 characters per token.)

The embedder doesn’t read the whole chunk. all-MiniLM-L6-v2 has max_seq_length = 256 word pieces and silently truncates the rest. On BEIR SciFact our chunker produces 5,852 chunks with a median of 302 tokens; 65% of them are longer than 256, and 24% of all chunk tokens are never embedded (NFCorpus: 71% and 28%). The text past the cut still goes to BM25, the reranker (max_length 512) and the LLM, but dense retrieval can’t match on it. Chunk size is a property of the embedder, not just the LLM’s context window.

Why 50-token overlap?

This is the most counterintuitive part of chunking. Consider a document where the answer to a query appears at characters 1900–2100. If you chunk at 2048 characters with no overlap, the relevant passage straddles the boundary: characters 1900–2048 go into chunk N, characters 2048–2100 go into chunk N+1. When you embed chunk N, the answer is only partially there — the embedding may not match the query. Chunk N+1 starts in the middle of a sentence and also won’t match well.

With 200-character overlap, chunk N goes from 0 to 2048. Chunk N+1 goes from 1848 to 3896. The relevant passage (1900–2100) is now fully contained in chunk N+1’s first ~250 characters. The overlap ensures that a passage shorter than the overlap always lands whole in at least one chunk.

Two details in our chunk_document() change this picture. First, it snaps each chunk end back to the last sentence boundary in the final 20% of the window, so a single sentence is rarely cut even without overlap; overlap matters for answers that span sentences. Second, the embedding model doesn’t read the whole chunk (next section).

Dense retrieval is O(N):

For each query, we embed it (once) and compute dot products with all N chunk embeddings:

scores = chunk_vecs @ query_vec   # (N,) — one dot product per chunk

Measured on the M1 Ultra (numpy, top-20): 0.035 ms per query at 1,000 chunks, 0.38 ms at 10,000, 4.8 ms at 100,000 and 48 ms at 1,000,000 (a 1.5 GB matrix). At this lab’s scale the matmul is noise; embedding the query (6–17 ms depending on device and load) is what you wait for. The “What the Toy Misses” section covers HNSW and IVF for the large-N case.

Why L2-normalize embeddings?

After normalization, each embedding has unit length. This means:

cosine_similarity(a, b) = a · b / (|a| |b|) = a · b

Because |a| = |b| = 1, the dot product is the cosine similarity. This turns the similarity computation into a simple matrix multiply, which numpy and BLAS accelerate heavily.

def embed_texts(model, texts):
    embeddings = model.encode(texts, convert_to_numpy=True)
    norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
    return (embeddings / norms).astype(np.float32)

v0 on a real benchmark — measured:

Run python -m src.eval --version v0 --k 3 on the bundled sample corpus and you get 5/5 hits. That says nothing: five short documents become five chunks, so top-3 retrieval can barely miss (v1 and v2 also score 5/5, and v0 scores 5/5 even at k=1).

To see real differences you need a real benchmark. scripts/bench.py runs the lab’s own classes on two BEIR datasets with human relevance labels: SciFact (300 test queries over 5,183 paper abstracts) and NFCorpus (323 queries over 3,633 medical documents). It reports hit@3, the lab’s “Recall@3”: the share of queries where at least one of the top-3 chunks comes from a relevant document. Dense v0 scores 69.3% on SciFact and 57.6% on NFCorpus; a third or more of queries send the LLM no relevant chunk at all. As a sanity check, v0’s nDCG@10 is 0.649 on SciFact and 0.312 on NFCorpus, against 0.645 and 0.316 for the same model in the MTEB results repository, so the harness isn’t broken.

Stage 1 Hybrid retrieval — BM25 + dense with RRF fusion ~200 LoC ›
  • Implement tokenize_for_bm25() (lowercase, split on whitespace)
  • Build BM25Okapi index from chunk corpus using rank-bm25
  • Implement reciprocal_rank_fusion(ranked_lists, k=60)
  • Run both retrievers, fuse with RRF, return top-3
  • Measure the change on a real benchmark: python scripts/bench.py --only quality (the 5-document sample can't show it)

Dense retrieval fails on exact keyword queries. If you ask “what is RRF?”, the dense retriever must find a chunk whose embedding is similar to the embedding of “what is RRF?”. If the chunk uses the phrase “Reciprocal Rank Fusion” — the full name — its embedding may be different enough from “RRF” that it doesn’t rank in the top 3.

BM25 doesn’t have this problem. BM25 is a bag-of-words scoring function. If the query contains “RRF” and the chunk contains “RRF”, BM25 gives that chunk a high score regardless of semantic distance.

The reverse is also true: BM25 fails on semantic queries. “How do I combine retrieval results?” and “what is Reciprocal Rank Fusion?” are semantically equivalent but share no keywords. Dense retrieval handles this; BM25 won’t find the RRF chunk from the semantic query.

BM25 scoring (brief):

BM25 scores a document d for query q as:

score(d, q) = sum over query terms t of:
    IDF(t) * tf(t, d) * (k1 + 1) / (tf(t, d) + k1 * (1 - b + b * |d| / avgdl))

Where:

  • IDF(t) = inverse document frequency — rare terms score higher
  • tf(t, d) = term frequency in document d
  • |d| = document length, avgdl = average document length
  • k1=1.5, b=0.75 are BM25 parameters controlling term saturation and length normalization

You don’t need to implement this. rank-bm25 handles it. What you do need to understand: BM25 scores are not comparable to cosine similarity scores. A BM25 score of 3.2 means nothing compared to a cosine similarity of 0.87. This is why we use RRF for fusion — it uses only rank positions.

Reciprocal Rank Fusion:

The RRF formula: for document d, across all retrieval systems:

rrf_score(d) = sum over systems s of: 1 / (k + rank_s(d))

Where:

  • rank_s(d) is the 1-indexed rank of document d in system s
  • k = 60 prevents the top-ranked document from completely dominating

Example: document X is ranked 1st by dense (score: 1/61 = 0.0164) and 2nd by BM25 (score: 1/62 = 0.0161). Its total RRF score is 0.0325. Document Y is ranked 1st by BM25 (score: 1/61) and not in dense’s top results (score: 0). Its RRF score is 0.0164. Document X wins.

The constant k=60 was found empirically in the original RRF paper (Cormack et al., 2009). It prevents the case where a document ranked 1st by one system gets an overwhelming advantage: 1/(60+1) = 0.0164 vs 1/(60+20) = 0.0125 for rank 20. Rank 1 is worth only about 31% more than rank 20, not 20x (which is what k=0 would give). This makes the fusion more robust to outliers.

Implementation note on BM25 index updates:

BM25Okapi doesn’t support incremental updates. When you call ingest() with new documents, you must rebuild the entire BM25 index from all chunks. This is fine for demonstration; production systems use Elasticsearch or Solr with incremental indexing.

# After adding new chunks:
self.bm25 = BM25Okapi(self._tokenized_chunks)  # rebuild from all chunks

v1 vs v0 — measured:

hit@3SciFact (300 q)NFCorpus (323 q)
v0 dense69.3%57.6%
BM25 alone (lab tokenizer)58.3%50.5%
v1 hybrid RRF68.3%58.8%
v1 − v0, paired 95% CI−1.0pp [−5.0, +3.0]+1.2pp [−2.5, +5.0]

Hybrid didn’t measurably help on either dataset. The reason is the BM25 half. tokenize_for_bm25() splits on whitespace, so punctuation stays attached: “cells,” and “cells” are different terms, and so are “(RRF)” and “RRF”. Change that one line to re.findall(r"\w+", text.lower()) and BM25-only nDCG@10 on SciFact goes from 0.566 to 0.650, and hybrid hit@3 from 68.3% to 73.7% (+4.3pp over dense, CI [+0.7, +8.0]); on NFCorpus, 61.0% (+3.4pp, CI [−0.3, +7.1]). The bench runs this as an ablation; the lab code keeps the naive tokenizer so you can make the change and watch the number move.

Hybrid retrieval only pays when both retrievers are decent and fail on different queries. A weak BM25 mostly adds noise to the fused ranking.

The intervals come from a paired bootstrap over queries (10,000 resamples). With ~300 queries, differences under ~4 points are within noise; don’t read the decimals.

Stage 2 Reranking — cross-encoder for precision ~180 LoC ›
  • Load cross-encoder/ms-marco-MiniLM-L-6-v2 with CrossEncoder()
  • Stage 1: hybrid retrieval for top-20 candidates
  • Stage 2: cross-encoder reranking — reranker.predict([(query, chunk), ...])
  • Return top-3 from reranked candidates to LLM
  • Measure the change on a real benchmark: python scripts/bench.py --only quality (the 5-document sample can't show it)

Both bi-encoders (dense) and BM25 have a structural weakness: they score query and document independently. The bi-encoder embeds the query, embeds the document, and measures cosine distance between the two vectors. The document embedding was created without knowing what query it would be compared against — it’s a general-purpose representation of that document’s meaning.

A cross-encoder is different. It receives the (query, document) pair as a single sequence and processes both together:

Input:  [CLS] query tokens [SEP] document tokens [SEP]
Output: single relevance logit

Because the transformer can attend from every query token to every document token simultaneously, it can model interactions that a bi-encoder cannot. The query “what is RRF?” can attend to the document phrase “Reciprocal Rank Fusion” and score it highly — even if the two phrases have different embeddings in isolation.

Why not use the cross-encoder for all retrieval?

A bi-encoder embeds each document once (offline) and stores the embeddings. At query time, you embed the query once and compute N dot products. This is fast: the document embeddings are cached; you only compute one embedding per query.

A cross-encoder must process each (query, document) pair at query time. For N=1,000,000 chunks, that’s 1,000,000 forward passes per query. Our reranker scored 40–120 (query, chunk) pairs per second on this machine’s CPU across three runs (up to ~380 on MPS when the GPU was quiet), so one query over 1M chunks would take hours: 2–7 on CPU. This is completely infeasible.

Two-stage retrieval:

The production solution uses both:

Stage 1 (fast, bi-encoder + BM25):  retrieve top-20 candidates
Stage 2 (accurate, cross-encoder):  rerank those 20 candidates
Final:  top-3 → LLM

Stage 1 is O(N). The dense half is a numpy matmul (0.36 ms at 5,852 chunks). The BM25 half is the slower one by far: rank-bm25 loops over documents in Python for every query term, 28 ms at the same size, roughly 80x the matmul, and linear in corpus size. Stage 2 is O(k) where k=20. The cross-encoder only scores 20 pairs per query, not N.

The 20 candidates from stage 1 define the recall ceiling: if the relevant chunk isn’t in the top-20, the cross-encoder can’t rescue it. This is why stage 1 retrieves more than the final k=3 — we’re trading a bit of stage-1 cost for a bigger candidate pool for stage 2.

Cross-encoder implementation:

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

# At query time:
pairs = [(question, chunk.text) for chunk in candidates]
scores = reranker.predict(pairs)   # shape (20,) — one logit per pair

# Sort by score (higher = more relevant)
ranked = np.argsort(scores)[::-1]
top_3 = [candidates[i] for i in ranked[:3]]

The model was fine-tuned on MS MARCO (a large passage ranking dataset from Bing search). The logits it outputs are not calibrated probabilities — only their relative ordering matters.

v2 vs v1 — measured:

SciFact hit@3SciFact hit@20NFCorpus hit@3NFCorpus hit@20
v1 hybrid RRF68.3%86.3%58.8%76.2%
v2 hybrid + rerank72.7%86.3%61.3%76.2%
v2 − v1 (hit@3), paired 95% CI+4.3pp [+0.7, +8.3]+2.5pp [−0.9, +5.9]

Reranking is the lab’s change that helps most reliably: clearly on SciFact, and in the same direction (within noise) on NFCorpus. Hit@20 doesn’t move at all, which is the recall ceiling in action: the cross-encoder only reorders the 20 candidates, so every gain is a relevant chunk promoted from rank 4–20 into the top 3. Hit@1 moves more (SciFact 52.7% → 58.3%, NFCorpus 44.6% → 48.6%).

The cost is latency. Scoring 20 candidates of ~1,360 characters each took a median 412 ms on CPU and 173 ms on MPS in the final run (163–519 ms and 53–333 ms across three runs on a shared machine), against 21–34 ms for the whole hybrid retrieve(). Reranking costs 8–12x everything else in retrieval combined. Next to an LLM call of a second or more that may still be acceptable, but it isn’t negligible, and it’s the first thing to batch, cache or move to a GPU.

Run it yourself

Run it yourself labs/rag ↗
Prereqs: Python 3.12+pip or uv
  1. 1
    Clone and install dependencies
    git clone https://github.com/pushkarkumar-dev/system-design-labs
    cd system-design-labs/labs/rag
    pip install -e '.[dev]'
  2. 2
    Run tests (no LLM needed)
    python -m pytest tests/test_rag.py -v
  3. 3
    Evaluate Recall@3 on the 5-document sample (v0 → v1 → v2; all score 5/5)
    python -m src.eval --version v0 --k 3
    python -m src.eval --version v1 --k 3
    python -m src.eval --version v2 --k 3
  4. 4
    Measure v0/v1/v2 on BEIR SciFact (downloads 3 MB; about a minute on an M1)
    python scripts/bench.py --only quality --datasets scifact
  5. 5
    Start the RAG server (v1 hybrid)
    RAG_VERSION=v1 uvicorn src.server:app --port 8000
  6. 6
    Ingest sample documents
    curl -s -X POST http://localhost:8000/ingest \
      -H 'Content-Type: application/json' \
      -d '{"docs": ["WAL ensures durability by writing changes before applying them.", "Raft uses leader election for consensus."]}' | python -m json.tool
  7. 7
    Query (no LLM — answer will show LLM unavailable)
    curl -s -X POST http://localhost:8000/query \
      -H 'Content-Type: application/json' \
      -d '{"question": "What is WAL?", "top_k": 3}' | python -m json.tool
Expected output
$ python -m src.eval --version v2 --k 3
Ingesting 5 documents...
Indexed 5 chunks.

=== Recall@3 Evaluation Report ===

Overall Recall@3: 100.0%  (5/5 hits)

[1] [HIT] Q: 'What is a Write-Ahead Log?'
   Expected: 'WAL'
   Result:   rank 1

[2] [HIT] Q: 'How does consistent hashing handle node addition or removal?'
   Expected: 'consistent hash ring'
   Result:   rank 1

[3] [HIT] Q: 'What is an LSM-tree and what workload is it optimized for?'
   Expected: 'write-heavy workloads'
   Result:   rank 1

[4] [HIT] Q: 'What is Reciprocal Rank Fusion?'
   Expected: 'Reciprocal Rank Fusion'
   Result:   rank 1

[5] [HIT] Q: 'How does Raft handle leader failure?'
   Expected: 'elections'
   Result:   rank 1

{
"version": "v2",
"k": 3,
"recall": 1.0,
"hits": 5,
"total": 5
}

Benchmarks

Benchmark results on Apple M1 Ultra, 64 GB RAM, macOS 27, Python 3.13.7, torch 2.14.1, sentence-transformers 6.1.0, rank-bm25 0.2.2 — quality on MPS, latency on CPU and MPS as labelled, 2026-10-11
Metric Result Notes
hit@3 SciFact — dense v0 69.3 % measured — 300 queries; nDCG@10 0.649 (MTEB lists 0.645 for this model)
hit@3 SciFact — hybrid RRF v1 68.3 % measured — −1.0pp vs dense, CI [−5.0, +3.0]
hit@3 SciFact — hybrid + rerank v2 72.7 % measured — +4.3pp vs hybrid, CI [+0.7, +8.3]
hit@3 SciFact — hybrid, \w+ BM25 tokenizer 73.7 % measured — ablation; +4.3pp vs dense, CI [+0.7, +8.0]
hit@3 NFCorpus — dense / hybrid / rerank 57.6 / 58.8 / 61.3 % measured — 323 queries; no step clears its CI on its own
Chunks truncated by the embedder (SciFact) 65 % measured — 24.5% of chunk tokens never embedded (256-token window)
Query embedding, 1 query (CPU / MPS) 11.8 / 8.6 ms measured — 7.4–17 / 5.9–11 ms across three runs
Dense scoring, numpy, 5,852 chunks / 1M vectors 0.36 / 48 ms measured — top-20 via argpartition; 1M × 384 float32 = 1.5 GB
BM25 scoring, rank-bm25, 5,852 chunks 28 ms measured — 11–28 ms across runs; pure Python, linear in N
Cross-encoder rerank, 20 candidates (CPU / MPS) 412 / 173 ms measured — 163–519 / 53–333 ms across three runs
retrieve() v1 hybrid / v2 rerank (MPS) 21 / 176 ms measured — CPU: 34 / 446 ms

Quality rows come from scripts/bench.py running the lab’s own classes on two public BEIR test sets with human relevance labels. They’re small (300 and 323 queries), so every difference is reported with a paired-bootstrap 95% CI over queries; differences under ~4 points are within noise. They are also specific to these corpora: short scientific and medical abstracts, where most documents fit in one chunk.

Latency rows are medians of 5 rounds of 50 queries, with the stages interleaved within each round. The machine was shared with other workloads (the raw JSON records the load average), and absolute numbers moved up to 2–3x between three runs of the script on the same day; the notes give the range. The ratios held steadier: reranking 20 candidates cost 8–12x the whole hybrid retrieval in every run, and pure-Python BM25 cost 70–80x the numpy matmul.

Stress tests

Corpus size scaling: numpy dense scoring on random 384-dim vectors took 0.035 ms per query at 1,000 vectors, 0.38 ms at 10,000, 4.8 ms at 100,000 and 48 ms at 1,000,000 (a 1.5 GB matrix): linear, as expected, and still fine for a toy at a million. BM25 is the real scaling problem here: rank-bm25 went from 3.4 ms at 1,000 chunks to 28 ms at 5,852, and it is linear in N in pure Python, so a million chunks would be seconds per query. That, more than the matmul, is where Elasticsearch/Lucene and a vector index (FAISS, HNSW) take over.

Chunk size and overlap: scripts/bench.py re-chunks the corpora with the lab’s chunk_document() at four settings and measures dense hit@3. At 2,048 characters, 200 characters of overlap vs none changed hit@3 by +0.3pp on SciFact (CI [−1.0, +1.7]) and +0.9pp on NFCorpus (CI [−0.9, +2.8]): no measurable effect, because most abstracts fit in one chunk and the chunker already ends chunks on sentence boundaries. Halving the chunks to 1,024 characters, so that nearly all of each chunk fits the embedder’s 256-token window, didn’t help either: hit@3 fell 1.5–3.4 points (CIs reaching zero), probably because more, smaller chunks per document crowd the top 3 with fragments. On long documents with answers that span sentences you may see the opposite; measure on your own corpus.

Cross-encoder latency under load: scripts/bench.py --server starts the FastAPI server with v2 and a 1,000-chunk index and sends 100 queries. One client at a time: p50 217 ms, 4.6 requests/s. Ten concurrent clients: p50 2,014 ms, 4.1 requests/s, the same throughput with ten times the latency. The /query handler is async def but calls the blocking pipeline directly, so the event loop runs one query at a time and everyone else waits. A production deployment would make the handler a plain def (FastAPI then runs it in a thread pool), batch rerank requests, or move the models behind an inference server such as Triton.

BM25 exact-match edge case: BM25 with no query terms in the corpus returns all-zero scores. rank-bm25 handles this gracefully (every score is 0), but the ranked order will be deterministic-but-meaningless. The RRF fusion blends this with the dense ranking, so the degradation is bounded.

What the toy misses

What the toy misses Honest gaps vs. production
  • Vector database for large corpora Our numpy cosine similarity is O(N) per query: 48 ms at 1M chunks on the M1 Ultra, and our pure-Python BM25 grows the same way from a much higher base (28 ms at 5,852 chunks). At millions of chunks and real QPS, that's too slow. Vector databases (FAISS, Pinecone, Weaviate) use HNSW or IVF for approximate nearest neighbor search — O(log N) or O(sqrt N). The tradeoff: approximate recall (HNSW misses some true nearest neighbours; how many depends on its parameters) vs exact recall (numpy never misses).
  • Chunking strategy Fixed-size chunking splits mid-sentence. Semantic chunking (split on paragraph/section boundaries) and recursive splitting (try sentence, then paragraph, then larger) produce better chunks. LangChain's RecursiveCharacterTextSplitter and LlamaIndex's SentenceSplitter implement production-grade chunking. Our fixed-size approach is a transparent baseline.
  • Contextual compression Large chunks contain relevant sentences buried in irrelevant context. LLM Lingua and similar compression methods extract only the relevant sentences from each retrieved chunk before sending to the LLM, cutting the tokens you pay for. Our chunks are sent verbatim.
  • Contamination detection Eval datasets can be contaminated if the model was trained on the test questions. Our eval harness does not check for contamination. The MMLU contamination problem (models memorizing eval sets) is real and makes published RAG numbers hard to compare.
  • Multi-hop retrieval Some questions require chaining retrievals. 'Who founded the company that made the product?' needs: retrieve about the product, then retrieve about the founder. Our RAG does a single retrieval. FLARE and IRCoT do iterative retrieval guided by the LLM's intermediate reasoning steps.
  • Document structure awareness Chunking a PDF loses table structure, figure captions, and section hierarchy. Production RAG systems parse document structure (headings, tables, lists) and use it to create semantically coherent chunks. A chunk that splits a table in half produces misleading context.

Wiring it into a Java/Spring service

☕

Wiring it into a Java/Spring service

service client langchain4j-spring-boot-starter
Maven dependencies
dev.langchain4j:langchain4j-spring-boot-starter:0.30.0
dev.langchain4j:langchain4j-open-ai:0.30.0
org.springframework.boot:spring-boot-starter-web:3.3.0

Part A — RagClient: the HTTP bridge

RagClient.java wraps our Python FastAPI server using Spring Framework 6.1’s RestClient. Two operations:

public class RagClient {
    private final RestClient http;

    public IngestResponse ingest(List<String> docs) {
        return http.post()
                .uri("/ingest")
                .contentType(MediaType.APPLICATION_JSON)
                .body(new IngestRequest(docs))
                .retrieve()
                .body(IngestResponse.class);
    }

    public RagResult query(String question, int topK) {
        return http.post()
                .uri("/query")
                .contentType(MediaType.APPLICATION_JSON)
                .body(new QueryRequest(question, topK))
                .retrieve()
                .body(RagResult.class);
    }

    public record RagResult(String answer, List<String> sources, String version) {}
}

The Python server speaks snake_case JSON (top_k, chunks_added, total_chunks), so the request and response records in RagClient.java map those fields with @JsonProperty. Without that, Jackson silently sends topK (ignored, so you always get the default 3) and reads chunksAdded as 0.

Part B — OurRetriever: the LangChain4j plug-in

ContentRetriever is LangChain4j’s retriever interface. Any class that implements it becomes a retriever that AiServices can use. This is the plug-in point: our Python service becomes a first-class retriever in any LangChain4j application.

public class OurRetriever implements ContentRetriever {

    private final RagClient client;
    private final int topK;

    @Override
    public List<Content> retrieve(Query query) {
        try {
            RagClient.RagResult result = client.query(query.text(), topK);
            return result.sources().stream()
                    .map(sourceText -> {
                        Metadata meta = Metadata.from(
                                "source", "python-rag-backend",
                                "version", result.version()
                        );
                        return Content.from(TextSegment.from(sourceText, meta));
                    })
                    .toList();
        } catch (Exception e) {
            log.warn("RAG backend unavailable: {}", e.getMessage());
            return Collections.emptyList();
        }
    }
}

The key design: OurRetriever catches all exceptions and returns an empty list rather than propagating them. This makes our Python service a “best-effort” retriever — if it’s unavailable, the LLM still receives the query, just without context. This is the correct degradation behavior for most production scenarios.

Part C — RagService: wiring LangChain4j

@Service
public class RagService {
    interface Assistant {
        @UserMessage("Answer based on context: {{it}}")
        String answer(String question);
    }

    private final Assistant assistant;

    public RagService(ChatLanguageModel chatModel, ContentRetriever retriever, RagClient client) {
        this.assistant = AiServices.builder(Assistant.class)
                .chatLanguageModel(chatModel)
                .contentRetriever(retriever)   // our Python RAG backend
                .build();
    }

    public String answer(String question) {
        return assistant.answer(question);
    }
}

AiServices.builder() creates a dynamic proxy for the Assistant interface. When you call assistant.answer(question):

  1. LangChain4j calls retriever.retrieve(query) to get context chunks
  2. It injects the chunks into the @UserMessage template
  3. It calls the ChatLanguageModel (our OpenAI-compatible LLM) with the augmented prompt
  4. It returns the answer as a String

From RagService’s perspective, the retriever is just an interface. Swapping our Python service for a FAISS retriever or a Weaviate retriever requires only changing the RagAutoConfiguration — this class is unchanged.

application.yml

rag:
  base-url: http://localhost:8000        # Python RAG server
  open-ai-base-url: http://localhost:8080 # OpenAI-compatible LLM
  model: local-model

Run it

# Terminal 1: start the Python RAG server (v1 hybrid retrieval)
cd labs/rag
RAG_VERSION=v1 uvicorn src.server:app --port 8000

# Terminal 2: run the Spring Boot demo
cd labs/rag/java-integration
mvn spring-boot:run

Expected output (the answers come from whatever LLM you point it at, so yours will be worded differently; each of the five demo documents is shorter than one chunk, so they index as 5 chunks):

=== RAG Spring Integration Demo ===

RAG backend health: ok (chunks indexed: 0, version: v1-hybrid)

Ingested 5 documents → 5 chunks indexed.

Answering questions (retrieval: Python RAG, generation: LLM):

Q1: What is a Write-Ahead Log and which databases use it?
A1: A Write-Ahead Log ensures durability by writing changes to a log before
    applying them. PostgreSQL, MySQL InnoDB, and RocksDB all use WAL.

Q2: How does Reciprocal Rank Fusion work?
A2: RRF combines ranked lists by scoring each document as 1/(k + rank_i).
    The constant k=60 prevents top-ranked documents from dominating.

Q3: What is consistent hashing used for?
A3: Consistent hashing distributes data across nodes using a hash ring,
    minimizing reorganization when nodes are added or removed.

Done. The Python RAG backend acted as a LangChain4j ContentRetriever.
Any Java AI application can use it identically.

What surprised me

Where to go deeper

  • RAG paper (Lewis et al., 2020): the original paper introducing the term — arxiv.org
  • BEIR benchmark: 18 diverse IR datasets for evaluating retrieval — github.com/beir-cellar/beir
  • Hybrid search explained: Weaviate’s deep dive on BM25 + dense + RRF — weaviate.io/blog
  • Sentence Transformers: the library behind all embedding models here — sbert.net
  • LangChain4j: Java’s LangChain — ContentRetriever, AiServices, chat memory — docs.langchain4j.dev
  • FLARE: Iterative retrieval guided by the LLM’s confidence — arxiv.org
  • LLM Lingua: compressing retrieved chunks before sending to the LLM — github.com/microsoft/LLMLingua
  • Previous in AI: Transformer From Scratch (lab transformer) — the LLM that generates the answer in v0 onward
  • Previous in AI: BPE Tokenizer (lab tokenizer) — the tokenization concepts behind chunk size estimation
  • Next in AI: Local GenAI stack — running the full pipeline (embedding + reranking + generation) offline with Ollama
  • System design companion: How would you design a RAG system that supports real-time document updates? (The BM25 index can’t be updated incrementally — you need Elasticsearch or a vector DB with upsert support.)
  • System design companion: At what corpus size does the two-stage retrieval approach break down, and what replaces it?