Designing a Document Q&A Retrieval Backend with Pluggable Grading
System DesignModel answerLast updated
Design a RAG ingestion pipeline, a swappable response-grading component using dependency inversion, and an efficient top-k structure for ranking retrieved chunks.
Backend for a Document Question-Answering Service
Your team is building the backend for a service that answers questions over a large collection of uploaded PDF files. Uploaded documents are split into pieces, stored in a searchable form, and at question time the most relevant pieces are passed to a Large Language Model (LLM) so it can write a grounded answer. This pattern is commonly called Retrieval-Augmented Generation (RAG).
Answer the three parts below as you would in a technical discussion. Be concrete, state trade-offs, and tie each answer to the needs of the system.
Part 1: Ingestion and indexing
Describe an extract-transform-load (ETL) pipeline that turns uploaded PDFs into something the retrieval layer can query.
- How would you split documents into chunks so that each chunk still carries enough meaning to be useful on its own?
- What do the embedding model and the vector database each contribute, and how do they interact at ingestion time and at query time?
Part 2: Pluggable response grading
You must add an "evaluator" component that scores how good the LLM's answers are. Different teams want different grading approaches, for example one based on embedding similarity to a reference answer and another based on keyword overlap.
How would you apply the Dependency Inversion Principle so that new grading strategies can be added without changing the main retrieval/answering service? Sketch the abstractions and show how the pieces are wired together.
Part 3: Keeping the best results
While searching, the system keeps the k highest-scoring chunks seen so far.
- If these are held in a sorted linked list, what is the time complexity of inserting one new candidate?
- Which data structure would you use instead, and why? Give the cost of processing N candidates, and mention edge cases.
Hints
Hint 1
For chunking, think about what gets lost when text is cut at arbitrary character counts, and what you can add (structure, overlap, headings) to recover it.
Hint 2
For the evaluator, ask which module should own the interface: the high-level service that consumes scores, or the individual graders. Then ask who decides which concrete grader is created.
Hint 3
For top-k, you only ever need to know the weakest item currently kept. Which structure exposes its minimum cheaply and supports fast replacement?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The question covers three areas: data engineering for retrieval, object-oriented design, and a core data-structure choice. A strong answer connects each choice to the system's requirements instead of reciting definitions.
Part 1: Ingestion pipeline and chunking
Pipeline shape
- Extract. An upload event triggers a worker that reads the PDF from object storage. Use a layout-aware parser, and OCR for scanned pages. Preserve headings, page numbers, and tables rather than flattening everything to plain text.
- Transform. Remove repeated headers and footers and fix hyphenation artifacts. Then chunk the text, embed each chunk, and attach metadata: document id, chunk index, page, section title, version, and access-control tags.
- Load. Upsert vectors and metadata into the vector store, and write document and chunk records to a relational metadata store. Make every step idempotent by keying on
(doc_id, version, chunk_index), so retries and reprocessing never create duplicates. Use a queue with a dead-letter path for failures.
Chunking that keeps meaning
- Fixed-size character splits are simple but cut sentences and separate facts from the context that explains them.
- Better practice:
- Structure-aware recursive splitting: split by section, then paragraph, then sentence, and fall back to a token limit only when needed.
- Token-based sizing: roughly 300 to 800 tokens per chunk, bounded by the embedding model's input limit.
- Overlap of about 10 to 20% so a sentence that straddles a boundary appears whole in at least one chunk.
- Context enrichment: prepend document title and section heading before embedding. Optionally store a pointer to a larger parent chunk, so you retrieve small precise pieces but give the LLM the parent.
- Trade-off: small chunks give precise matches but little context; large chunks give context but dilute the embedding. Overlap helps recall but raises storage cost and can return near-duplicates, so deduplicate or diversify results.
Embedding model and vector database
- The embedding model maps text to a dense vector so that semantically similar text is close under cosine or dot-product similarity. The query must be embedded with the same model as the chunks. Changing models requires re-indexing, so version the embedding model in the metadata.
- The vector database stores the vectors and answers approximate nearest-neighbor queries using indexes such as HNSW or IVF, trading a small amount of recall for large speedups. It also applies metadata filters (tenant, permissions, document version).
- Query flow: embed the question, retrieve the top-k chunks (optionally combining keyword search with vector search, then reranking), and place them in the LLM prompt with citations.
Part 2: Dependency Inversion for the evaluator
The Dependency Inversion Principle says high-level policy should depend on abstractions, and low-level details should also depend on those abstractions. Here the quality service (policy) depends on an Evaluator interface that it owns. Each grading strategy implements that interface, and the concrete strategies are injected from outside, typically in a composition root or from configuration.
from abc import ABC, abstractmethod
from dataclasses import dataclass
import math
@dataclass(frozen=True)
class EvalResult:
strategy: str
score: float # normalized to [0, 1]
class Evaluator(ABC):
@abstractmethod
def evaluate(self, query: str, response: str, reference: str) -> EvalResult: ...
class KeywordEvaluator(Evaluator):
def evaluate(self, query, response, reference):
ref = set(reference.lower().split())
if not ref:
return EvalResult("keyword", 0.0)
hits = ref & set(response.lower().split())
return EvalResult("keyword", len(hits) / len(ref))
class SemanticEvaluator(Evaluator):
def __init__(self, embed): # embed: str -> list[float], also injected
self._embed = embed
def evaluate(self, query, response, reference):
a, b = self._embed(response), self._embed(reference)
dot = sum(x * y for x, y in zip(a, b))
norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
cos = dot / norm if norm else 0.0
return EvalResult("semantic", (cos + 1) / 2)
class ResponseQualityService:
def __init__(self, evaluators: list[Evaluator]):
self._evaluators = evaluators
def grade(self, query, response, reference):
return [e.evaluate(query, response, reference) for e in self._evaluators]
Points worth stating:
- Constructor injection keeps the choice of strategy out of the service. Adding an LLM-as-judge grader means adding a class and registering it; the service is untouched (which also satisfies Open/Closed).
- Testability: pass a fake evaluator in unit tests.
- Decoupling from vendors: the embedding function is itself injected, so the semantic grader is not bound to one provider.
- Common mistake: defining the interface inside the grader package and having the service import concrete classes. That keeps the dependency pointing the wrong way.
Part 3: Maintaining the top-k
Sorted linked list. You cannot binary search a linked list, so finding the insertion point is a linear scan. The splice is O(1), but insertion overall is O(n), or O(k) if the list is capped at k. Processing N candidates costs O(N·k).
Better choice: a min-heap of size k.
- The root is the weakest of the current top-k.
- For each candidate, compare to the root in O(1). If it is better, replace the root in O(log k); otherwise discard it.
- Total: O(N log k) time, O(k) space. Sorting the final k results costs O(k log k).
- It is simple, cache-friendly, and available in standard libraries.
A balanced BST or sorted container also gives O(log k) insertion and supports deleting arbitrary items, which helps if chunks can be withdrawn mid-stream (for example a deleted document). Otherwise the heap is the default.
import heapq
import itertools
class TopK:
def __init__(self, k: int):
if k < 0:
raise ValueError("k must be non-negative")
self.k = k
self._heap = [] # (score, seq, chunk_id)
self._seq = itertools.count() # tie-breaker, avoids comparing payloads
def push(self, score: float, chunk_id: str) -> None:
if self.k == 0:
return
item = (score, next(self._seq), chunk_id)
if len(self._heap) < self.k:
heapq.heappush(self._heap, item)
elif score > self._heap[0][0]:
heapq.heapreplace(self._heap, item)
def results(self):
return [(c, s) for s, _, c in sorted(self._heap, key=lambda t: (-t[0], t[1]))]
Edge cases
k = 0returns nothing.- Fewer than k candidates returns all of them.
- Equal scores are broken deterministically by arrival order via the sequence counter.
- In a distributed search, take the top-k per shard and merge, which is still correct because any global top-k item must be in its shard's top-k.