RAG Ingestion, SOLID Evaluation, and Top-K Retrieval

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

You are designing the backend service for an enterprise Retrieval-Augmented Generation (RAG) search platform. The platform ingests lengthy PDF manuals, divides them into searchable passages, and retrieves the best-matching passages at query time so a Large Language Model (LLM) can answer questions from authoritative source text.

Walk through your design across three areas:

  1. Ingestion Pipeline & Semantic Indexing: Describe an Extract-Transform-Load (ETL) workflow for incoming PDF files. Explain how your passage-splitting approach avoids cutting meaning across boundaries, and define the distinct responsibilities of the embedding model versus the vector database.
  2. Extensible Grading with Dependency Inversion: Suppose you add a quality-scoring module ("Evaluator") that grades generated LLM answers. Show how applying SOLID's Dependency Inversion Principle lets your system plug in multiple grading strategies (for instance, embedding-based similarity alongside exact term coverage) without editing core retrieval service code.
  3. Top-K Retrieval Complexity & Data Structures: During search, your service tracks the k highest-scoring passages. If those passages are kept in a singly or doubly linked list ordered by relevance score, what is the worst-case time complexity of inserting a newly scored passage in sorted position? What data structure would you replace it with to optimize top-k maintenance, and why?

Scope & Expectations

  • Cover practical PDF ETL reliability (layout/table preservation, overlapping structural splits, batch encoding, and idempotent versioned writes) and clearly separate vector encoding from Approximate Nearest Neighbor (ANN) indexing.
  • Demonstrate true Dependency Inversion with clean interface boundaries and dependency injection so adding a new grading rubric requires zero edits to the retrieval orchestrator.
  • Analyze sorted linked-list insertion cost accurately (explaining why binary search does not rescue pointer-based lists) and justify the time, memory, and cache trade-offs of your chosen top-k replacement structure.

Step-by-step walkthrough

  1. Overview: two paths sharing one knowledge index

    A Retrieval-Augmented Generation (RAG) system answers user questions by looking up relevant passages from an external document collection and pasting those passages into a Large Language Model (LLM) prompt, so the model answers from real source text rather than memory alone.

    A production RAG backend splits into three decoupled workflows:

    • Offline ingestion path (asynchronous, throughput-focused): turns uploaded PDFs into clean, searchable text chunks without blocking users.
    • Online query path (synchronous, latency-sensitive): embeds the user's question, fetches the top-k most relevant chunks in milliseconds, and sends them with the question to the LLM.
    • Evaluation path (asynchronous, side-by-side): grades finished (question, context, answer) records in the background so slow quality checks never add latency to user requests and new grading rules never touch retrieval code.
                   OFFLINE INGESTION                                ONLINE QUERY
     PDF upload -> job queue -> extract -> clean -> chunk          user question
                                                      |                  |
                                                embed (batches)   embed (same model)
                                                      |                  |
                            +-------------------------v------------------v-------+
                            |   Vector DB (embeddings)  +  Metadata DB (SQL)     |
                            +---------------------------------+------------------+
                                                              | top-k chunks
                                                              v
                                             prompt = question + chunks -> LLM -> answer
                                                                                    |
                                                              (async event) -> Evaluator -> scores
    
  2. Part 1A: Design a reliable ETL pipeline for PDFs

    An ETL (Extract, Transform, Load) pipeline is an automated workflow that pulls raw input data from a source, cleans and reshapes it, and writes it into target databases ready for querying.

    1. Extract (turn raw PDFs into structured text + metadata) - When a PDF lands in object storage, publish a job to a work queue so worker processes handle heavy parsing asynchronously. - Use a layout-aware PDF parser so multi-column pages, sidebars, and footnotes are read in logical reading order rather than interleaved line by line. - Run OCR (Optical Character Recognition)—software that converts scanned page images into machine-readable text—on image-only pages, and serialize tables into structured row text (such as Markdown or key-value rows) so numbers stay attached to their column headers. - Attach metadata to every extracted block: doc_id, version, title, section_path, page_number, and access-control tags (such as tenant_id or allowed roles).

    2. Transform (clean, chunk, enrich, and batch-embed) - Strip repeated page headers/footers, rejoin words hyphenated across line breaks ("infra-\nstructure" -> "infrastructure"), and normalize whitespace. - Split the document into overlapping semantic chunks (detailed in the next step). - Prepend a short context header ("Document: Refund Policy | Section: Enterprise Plans\n...") to each chunk before embedding so pronouns like "it expires after 30 days" still carry their subject. - Call the embedding model in batches (for example, 64–256 chunks per request) rather than one network call per chunk, keeping GPUs utilized and respecting API rate limits.

    3. Load (write atomically and safely) - Idempotency means running the same job twice produces the exact same stored state without duplicate rows. Assign each chunk a deterministic ID such as (doc_id, version, chunk_index) and upsert (insert if new, overwrite if existing) its vector into the vector database and its text + metadata into SQL. - Versioned cutover: write all chunks for version = 2 first, then flip active_version = 2 in one SQL transaction, and finally clean up version = 1 chunks asynchronously. Live queries filter on active_version, so users never see a half-indexed PDF. - Dead-letter queue (DLQ): a separate holding queue where jobs land after exhausting retries (for example, 3 attempts with exponential backoff), preventing one corrupt PDF from blocking healthy uploads.

  3. Part 1B: Chunk documents without slicing meaning in half

    Naive chunking—cutting every 2,000 characters regardless of punctuation—slices sentences, tables, and logical arguments down the middle. A chunk starting with "...unless the customer is on Tier 2." loses the rule it modifies, embeds poorly, and fails to answer questions accurately. Conversely, making chunks too large either dilutes a specific fact inside unrelated paragraphs or exceeds the embedding model's maximum token window (where excess tokens are often silently truncated).

    Combine two rules to preserve semantic context:

    1. Structure-first recursive splitting: split along natural boundaries first—section headings, then paragraphs, then sentences—and only fall back to token-count cuts when a single paragraph exceeds the target chunk size S.
    2. Sliding-window token overlap: let adjacent chunks share O tokens (0 <= O < S), so each new chunk advances by step = S - O tokens (chunk i starts at i * (S - O)).

    Why does overlap O guarantee context preservation? Pick any contiguous phrase starting at token a. The last chunk that began at or before a started at most S - O - 1 tokens earlier. Since that chunk has length S, the number of token positions remaining from a through the end of that chunk is at least:

    remaining positions = S - (S - O - 1) = O + 1
    

    So every phrase of up to O + 1 tokens appears completely intact inside at least one chunk. With S = 10 and O = 3 (step = 7), a 4-token sentence spanning tokens 6..9 sits whole inside Chunk 0, and a 4-token sentence spanning tokens 7..10 sits whole inside Chunk 1:

    Token index:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
    Chunk 0:     [0  1  2  3  4  5  6  7  8  9]
    Chunk 1:                          [7  8  9 10 11 12 13 14 15 16]
                                       |<--->|
                                  3-token overlap (7, 8, 9)
    
    from typing import List
    
    
    def sliding_chunks(tokens: List[str], size: int, overlap: int) -> List[List[str]]:
        """Split tokens into windows of length `size` sharing `overlap` tokens."""
        if size <= 0 or not (0 <= overlap < size):
            raise ValueError("Require size > 0 and 0 <= overlap < size")
        if not tokens:
            return []
    
        step = size - overlap
        chunks: List[List[str]] = []
        start = 0
        while True:
            chunks.append(tokens[start : start + size])
            # Stop once this window reaches or passes the end of the document.
            if start + size >= len(tokens):
                break
            start += step
        return chunks
    

    Worked numeric check on a 10,000-token PDF with size = 512: - No overlap (overlap = 0, step = 512): 20 chunks (10,000 tokens stored). A sentence at tokens 500..530 is torn across Chunk 0 (0..511) and Chunk 1 (512..1023). - With overlap (overlap = 64, step = 448): 22 full chunks of 512 tokens plus a final chunk starting at 22 * 448 = 9,856 of 144 tokens = 23 chunks (22 * 512 + 144 = 11,408 tokens, only 14.1% extra storage). That sentence at 500..530 now sits completely inside Chunk 1 (448..959).

  4. Part 1C: How embeddings and vector databases work together

    An embedding model is a neural network that converts text into a fixed-length vector of floating-point numbers (for example, 768 dimensions) so passages with similar meaning land close together in space even if they share zero words ("terminate contract" and "cancel subscription"). Crucially, the exact same embedding model and version must encode both document chunks and user queries, because two different models assign completely incompatible meanings to vector coordinates.

    Closeness is typically measured with cosine similarity, the cosine of the angle between two vectors (ranging from -1 opposite to +1 identical). When vectors are normalized to unit length (sqrt(x_1^2 + x_2^2 + ...) = 1), cosine similarity reduces to a fast dot product (sum(q_i * c_i)):

    Query q  ("cancel plan")      = [0.0, 0.8, 0.6]   (unit length: 0^2 + 0.8^2 + 0.6^2 = 1.0)
    Chunk c1 ("end subscription") = [0.0, 0.6, 0.8]   dot(q, c1) = 0 + 0.48 + 0.48 = 0.96  <- strong match
    Chunk c2 ("office parking")   = [0.8, 0.6, 0.0]   dot(q, c2) = 0 + 0.48 + 0    = 0.48  <- weak match
    

    A vector database stores these vectors alongside chunk IDs and filterable metadata, answering "find the k chunks closest to query vector q that this user has permission to read." Comparing q against all N vectors takes O(N * d) operations per query, which becomes slow at millions of chunks. Vector databases instead build Approximate Nearest Neighbor (ANN) indexes—data structures that trade a tiny, measurable fraction of recall for sub-10-millisecond search: - HNSW (Hierarchical Navigable Small World): a multi-layer proximity graph where search hops greedily from coarse upper layers down to fine local neighbors. - IVF (Inverted File Index): groups vectors into clusters ahead of time and searches only the handful of clusters closest to q.

    Sizing check: 1,000,000 chunks at 768 float32 dimensions (4 bytes per float) occupy 1,000,000 * 768 * 4 = 3,072,000,000 bytes (~3.07 GB) of raw vector data before graph links—or ~768 MB with 8-bit integer quantization (compressing 32-bit floats into 8-bit integers). Because dense embeddings can miss exact strings like SKU numbers or error codes (ERR_4091), production RAG platforms often combine vector search with classic BM25 keyword search and merge the top candidates.

  5. Part 2: Decouple the Evaluator with Dependency Inversion

    The Dependency Inversion Principle (DIP)—the "D" in SOLID—states two rules: 1. High-level modules (core business orchestration) must not depend on low-level modules (specific grading algorithms or third-party clients); both must depend on abstractions (interfaces). 2. Abstractions should be defined in terms of what the high-level module needs, not leaked details of low-level implementations.

    Notice why it is called Dependency Inversion: without DIP, the source-code import arrow points downward from RetrievalService to concrete graders; with DIP, concrete graders import and implement EvaluatorInterface, flipping the arrow upward so RetrievalService never knows which graders exist:

    WITHOUT DIP (tightly coupled — adding SemanticGrader edits RetrievalService):
      RetrievalService  ----imports---->  KeywordGrader
    
    WITH DIP (inverted — RetrievalService only knows EvaluatorInterface):
      RetrievalService  --->  EvaluatorInterface  <---  CompositeEvaluator
                                                               |
                                                               v
                                                        GradingStrategy (ABC)
                                                          ^               ^
                                                          |               |
                                                    KeywordGrader   SemanticGrader
    

    Here, RetrievalService accepts any EvaluatorInterface via constructor injection (passing the dependency in when creating the service at startup). Adding an LLM-as-judge grader tomorrow means writing one new GradingStrategy subclass and registering it in startup configuration—zero lines inside RetrievalService or CompositeEvaluator change:

    from abc import ABC, abstractmethod
    from dataclasses import dataclass
    import math
    from typing import Callable, Dict, List
    
    
    @dataclass(frozen=True)
    class EvaluationSample:
        question: str
        answer: str
        reference: str
    
    
    class GradingStrategy(ABC):
        """Abstraction for one single grading rubric returning a score in [0.0, 1.0]."""
    
        @property
        @abstractmethod
        def name(self) -> str:
            """Short metric key such as 'keyword_coverage' or 'semantic_similarity'."""
    
        @abstractmethod
        def score(self, sample: EvaluationSample) -> float:
            """Compute quality score in [0.0, 1.0]."""
    
    
    class KeywordGradingStrategy(GradingStrategy):
        """Checks what fraction of required keywords appear in the LLM answer."""
    
        def __init__(self, required_keywords: List[str]) -> None:
            if not required_keywords:
                raise ValueError("required_keywords must not be empty")
            self._keywords = [kw.lower() for kw in required_keywords]
    
        @property
        def name(self) -> str:
            return "keyword_coverage"
    
        def score(self, sample: EvaluationSample) -> float:
            lowered_answer = sample.answer.lower()
            matched = 0
            for kw in self._keywords:
                if kw in lowered_answer:
                    matched += 1
            return matched / len(self._keywords)
    
    
    class SemanticGradingStrategy(GradingStrategy):
        """Measures cosine similarity between embeddings of answer and reference."""
    
        def __init__(self, embed_fn: Callable[[str], List[float]]) -> None:
            # Inject the embedding function too so tests can pass a lightweight fake.
            self._embed_fn = embed_fn
    
        @property
        def name(self) -> str:
            return "semantic_similarity"
    
        def score(self, sample: EvaluationSample) -> float:
            vec_a = self._embed_fn(sample.answer)
            vec_b = self._embed_fn(sample.reference)
            norm_a = math.sqrt(sum(x * x for x in vec_a))
            norm_b = math.sqrt(sum(y * y for y in vec_b))
            if norm_a == 0.0 or norm_b == 0.0:
                return 0.0
            cosine = sum(x * y for x, y in zip(vec_a, vec_b)) / (norm_a * norm_b)
            return max(0.0, min(1.0, cosine))
    
    
    class EvaluatorInterface(ABC):
        """High-level contract owned by the retrieval layer."""
    
        @abstractmethod
        def evaluate(self, sample: EvaluationSample) -> Dict[str, float]:
            """Grade a sample (or enqueue it for async grading) and return scores."""
    
    
    class CompositeEvaluator(EvaluatorInterface):
        """Runs any configured list of GradingStrategy implementations."""
    
        def __init__(self, strategies: List[GradingStrategy]) -> None:
            self._strategies = list(strategies)
    
        def evaluate(self, sample: EvaluationSample) -> Dict[str, float]:
            scores: Dict[str, float] = {}
            for strategy in self._strategies:
                scores[strategy.name] = strategy.score(sample)
            return scores
    

    Worked numeric check: suppose required_keywords = ["refund", "30 days", "receipt"] and the LLM replies "Refunds are issued within 30 days.". Lowercasing matches "refund" and "30 days" (2 of 3), so KeywordGradingStrategy returns 2 / 3 = 0.667. If the LLM instead paraphrases "You can get your money back within a month", keyword grading scores 0.0, while SemanticGradingStrategy scores near 0.90—illustrating why running multiple swappable strategies without editing the retrieval service is so valuable.

  6. Part 3: Maintain top-k chunks—sorted linked list vs. min-heap

    1. Complexity of sorted linked list insertion A linked list stores elements in scattered nodes connected by next pointers, which means there is no O(1) random access by index—binary search is impossible because finding the middle element already requires walking m / 2 pointers from head. - In general, inserting a new chunk into a sorted linked list of n elements takes O(n) time in the worst case (walking up to n nodes to find the sorted position, followed by an O(1) pointer splice). - If you cap the linked list at the top k chunks (n = k), inserting a qualifying chunk still walks up to k nodes = O(k) per insert. Scanning N candidate chunks therefore costs O(N * k) worst-case time (or O(N^2) if you insert all N chunks before taking the first k). For N = 1,000,000 chunks and k = 100, O(N * k) can traverse up to 100,000,000 list nodes.

    2. Optimizing with a Min-Heap of size k A min-heap is a complete binary tree stored flat inside a contiguous array where every parent's score is less than or equal to its children's scores. Because we keep only the k highest-scoring chunks seen so far in the min-heap, the root heap[0] is always the weakest (k-th best) chunk in our top-k set, readable in O(1) time: - If a new chunk's score is <= heap[0], it cannot be in the top k—reject it immediately in O(1) with a single comparison! - If a new chunk's score is > heap[0], evict heap[0] and sift the new chunk into place (heapreplace) in O(log k) time.

    Trace for k = 3 across 5 candidate scores [0.72, 0.40, 0.85, 0.50, 0.91]:

    Candidate   Action                                      Min-heap (heap[0] = weakest of top 3)
    ---------   -----------------------------------------   -------------------------------------
    0.72        size < 3 -> push                            [0.72]
    0.40        size < 3 -> push                            [0.40, 0.72]
    0.85        size < 3 -> push                            [0.40, 0.72, 0.85]   (cutoff = 0.40)
    0.50        0.50 > 0.40 -> replace root, sift           [0.50, 0.72, 0.85]   (cutoff = 0.50)
    0.91        0.91 > 0.50 -> replace root, sift           [0.72, 0.91, 0.85]   (cutoff = 0.72)
    Final sort descending (O(k log k)):                     [0.91, 0.85, 0.72]
    
    import heapq
    from typing import Iterable, List, Tuple
    
    
    def top_k_chunks(scored_chunks: Iterable[Tuple[str, float]], k: int) -> List[Tuple[float, str]]:
        """Return the k highest-scoring (score, chunk_id) pairs in descending order."""
        if k <= 0:
            return []
    
        # Min-heap of up to k pairs (score, chunk_id); heap[0] is the weakest kept chunk.
        heap: List[Tuple[float, str]] = []
        for chunk_id, score in scored_chunks:
            if len(heap) < k:
                heapq.heappush(heap, (score, chunk_id))
            elif score > heap[0][0]:
                # Pop the weakest chunk and push the stronger newcomer in one O(log k) step.
                heapq.heapreplace(heap, (score, chunk_id))
    
        # Sort the k winners from highest score to lowest in O(k log k) time.
        return sorted(heap, reverse=True)
    

    Why a size-k min-heap wins: - Time complexity: O(N log k) worst-case across N candidates (plus O(k log k) for the final sort) and O(k) memory. At N = 1,000,000 and k = 100, log2(100) ≈ 6.64, capping heap sifts at ~6.64 million steps—and if scores arrive in random order, only k * (1 + ln(N / k)) ≈ 100 * (1 + 9.21) ≈ 1,021 chunks ever beat heap[0] and pay the O(log k) update! - Cache locality: an array-backed heap keeps k tuples side by side in CPU cache, whereas linked-list nodes chase scattered heap pointers. - When to pick a balanced Binary Search Tree (BST) instead: a self-balancing BST (such as a Red-Black or AVL tree) also gives O(log k) insertion and O(log k) minimum eviction, while keeping all k elements continuously sorted and supporting O(log k) deletion of an arbitrary chunk ID—useful if the top-k list is long-lived and mutates as documents are deleted, though heavier in memory and constant factors than a binary heap for one-pass query merging.

Intuition & how it works

Think of a Retrieval-Augmented Generation (RAG) platform like an open-book exam assistant built from three specialized roles: 1. An offline librarian (the ETL pipeline) who reads incoming PDFs, cuts them into overlapping index cards so no sentence is sliced in half, and files each card on a map where similar topics sit close together (the vector database). 2. A fast desk clerk (query retrieval + min-heap) who takes a user's question, pulls candidate cards, and keeps only the k highest-scoring cards by tracking the weakest card currently in their hand so weaker candidates can be tossed instantly. 3. An independent grader (the Evaluator with Dependency Inversion) who grades finished answers using pluggable rubrics—without the desk clerk ever needing to know which grading rubrics exist.

Naive designs fail in all three places at once. Slicing PDFs every fixed 500 characters cuts sentences and tables mid-thought so crucial context vanishes; hardcoding KeywordGrader directly inside RetrievalService forces risky code edits and redeployments every time you add a new metric; and maintaining the top-k chunks in a sorted linked list requires walking pointers one node at a time (O(n) for a list of length n, or O(k) per insert when capped at k) because linked lists lack random access for binary search.

Walk through a tiny concrete trace with k = 2: - Ingest & chunk: A policy PDF has 12 tokens. With chunk size S = 6 and overlap O = 2 (step = 4), we store chunks covering tokens 0..5, 4..9, and 8..11. A 3-token rule "within 30 days" at tokens 4..6 is split in Chunk 0 (4..5) but sits completely intact in Chunk 1 (4..9) because 3 <= O + 1. - Embed & top-k: Three candidate chunks score [0.65, 0.92, 0.40] against the user's embedded query. Our k = 2 min-heap pushes 0.65 and 0.92 (heap[0] = 0.65), then rejects 0.40 in a single comparison (0.40 <= 0.65) and returns [0.92, 0.65]. - Evaluate: RetrievalService hands the finished answer "Refunds arrive within 30 days" to an injected EvaluatorInterface, where CompositeEvaluator runs both KeywordGradingStrategy (2 / 3 = 0.667) and SemanticGradingStrategy (0.94) with zero coupling back to retrieval.

Key points

  • ETL for RAG must preserve layout and be idempotent: parse columns/tables/scans (via OCR, Optical Character Recognition) cleanly, prepend document/section titles to chunks, batch embedding API calls, upsert deterministic (doc_id, version, chunk_index) IDs, switch active_version atomically, and isolate bad PDFs in a dead-letter queue (DLQ).
  • Overlap math guarantees intact phrases: with chunk size S and overlap O, chunks advance by S - O tokens, guaranteeing every span of up to O + 1 tokens appears unbroken in at least one chunk (10,000 tokens at S = 512, O = 64 produces 23 chunks and only 14.1% token overhead).
  • Embeddings + vector database roles: one shared embedding model maps chunks and queries into the same vector space so cosine similarity measures semantic closeness; the vector database uses Approximate Nearest Neighbor (ANN) indexes (such as HNSW graphs or IVF clusters) to avoid O(N * d) brute-force scans over gigabytes of vectors (1M * 768 * 4 B ≈ 3.07 GB raw float32).
  • Dependency Inversion flips the dependency arrow: RetrievalService depends only on EvaluatorInterface, and CompositeEvaluator depends only on GradingStrategy. Concrete graders (KeywordGradingStrategy, SemanticGradingStrategy, LLM-as-judge) plug in at startup via constructor injection without touching retrieval code.
  • Top-k data structure choice: inserting into a sorted linked list of length n is O(n) (O(k) when capped at k, giving O(N * k) total over N candidates) because linked lists lack random access; a size-k min-heap rejects non-qualifying chunks in O(1) and updates in O(log k), cutting total time to O(N log k) in O(k) space (or use a balanced BST if arbitrary O(log k) deletions and continuous sorted order are required).

Common mistakes

  • Fixed-character splitting without structure or overlap: slicing mid-sentence or exceeding the embedding model's context limit so trailing tokens are silently dropped and never indexed.
  • Mixing embedding models or skipping query normalization: encoding queries with v2 of an embedding model against chunks encoded with v1 produces meaningless cosine scores; changing models requires re-embedding into a fresh index and cutting over atomically.
  • Confusing "add an interface" with Dependency Inversion: if RetrievalService imports EvaluatorInterface and still calls KeywordGradingStrategy() inside RetrievalService.__init__, the hard dependency remains; concrete wiring belongs in startup configuration (the composition root).
  • Claiming binary search works on a sorted linked list: even when sorted, finding the midpoint of a linked list requires walking half its pointers (O(k)), so sorted insertion is never O(log k) on a plain linked list.
  • Thinking a min-heap stores all k elements in sorted order: a min-heap only guarantees heap[0] is the minimum; returning the top k from best to worst requires a final O(k log k) sort (sorted(heap, reverse=True)).

Follow-up questions

  • How can you prevent deleted documents from appearing in answers immediately while live traffic is hitting the vector index? Make the transactional SQL metadata database the authoritative source of truth for document lifecycle. When a user deletes a document, immediately mark is_deleted = true (or clear active_version) in SQL within one ACID transaction, and have the retrieval path over-fetch candidates (say 2k chunks) from the vector index and filter their IDs against active SQL metadata right before building the LLM prompt—plus invalidate any cached answers citing that doc_id. Because ANN graph indexes like HNSW are expensive to rewire synchronously, physical vector deletion can then run asynchronously via a background compaction worker without ever leaking deleted text to live queries.
  • How do relational databases for document metadata and dedicated vector stores for embeddings compare, and when would you combine or unify them? A standard SQL database provides ACID transactions (atomic, consistent, isolated, durable writes), relational joins for multi-tenant permissions, and instant status flips for versioning and deletion, whereas a specialized vector database provides purpose-built ANN indexes (HNSW/IVF), vector quantization, and horizontal sharding across hundreds of millions of embeddings. Running both introduces dual-write consistency risk, which you solve with the transactional outbox pattern—writing metadata + an indexing event in one SQL transaction and streaming that event to index workers. At moderate scale (under ~5–10 million chunks, where 10M * 768 * 4 B ≈ 30.7 GB still fits comfortably on one beefy node), Postgres with pgvector keeps metadata and embeddings in a single transactional store before you need a dedicated distributed vector cluster.
  • How would you scale response grading across multiple workers without slowing down user queries or double-counting scores? Decouple evaluation from query serving by having RetrievalService's EvaluatorInterface publish immutable (response_id, question, context, answer, rubric_version) events onto a durable message queue (such as Kafka or SQS), consumed by a stateless pool of Evaluator workers that autoscale on queue lag. Because message queues usually guarantee at-least-once delivery (a message may be processed twice after a worker retry), keep scores consistent by making database writes idempotent: upsert evaluation rows keyed by (response_id, strategy_name, rubric_version) so duplicate runs overwrite with the same result rather than double-counting metrics. Pin rubric_version inside each event payload during rollouts so metrics never silently mix old and new grading formulas, and if LLM-judge cost spikes, sample deterministically using a stable hash like crc32(response_id) % 10 == 0.

Follow-up questions

Similar questions

More Equinix interview questions

All 2 Equinix questions →