Batch Document Embedding and Filtered Vector Retrieval

Medium · Machine Learning · Software Engineer · Technical Screen

Problem Statement

Build the two core entry points of a semantic document-retrieval service: a fault-tolerant batch indexer that chunks, embeds, normalizes, and upserts documents, and a query function that retrieves the highest-scoring distinct documents matching an optional category filter.

External dependencies are injected so the pipeline can run against mocks or production services: - embed_model.encode(texts: List[str]) -> List[List[float]]: encodes a batch of B texts into B raw float vectors. - split_text(text: str, max_tokens: int) -> List[str]: splits text into chunks of at most max_tokens tokens (returning [text] if it already fits). - vector_db.upsert(records: List[dict]) -> None: writes records keyed by record['id'], overwriting any existing entry with the same 'id'. - vector_db.query(vector: List[float], filter: dict, k: int) -> List[dict]: returns up to k stored records matching all key-value pairs in filter, each carrying an added 'score' equal to the dot product between vector and record['vector'], sorted highest score first.

Implement:

  1. process_and_index_documents(documents, *, embed_model, vector_db, split_text, batch_size=32, max_retries=2, retry_delay=0.5) -> Dict[str, list]

    • Each input dictionary has shape {'id': str, 'text': str, 'category': str}.
    • Validation & deduplication: Reject any entry missing a non-empty 'id' immediately. If the same 'id' appears more than once in documents, keep only its last occurrence and validate that surviving entry. Mark a document failed if 'text' is missing, not a string, or whitespace-only, or if split_text(text, 512) yields no chunks.
    • Batched encoding with retries: Encode chunks in batches of batch_size. When embed_model.encode raises an exception, retry up to max_retries additional times with exponential backoff (retry_delay, 2 * retry_delay, 4 * retry_delay, ...). If all retries fail (or encode returns the wrong number of vectors), record every document touched by that batch as failed and continue processing remaining batches.
    • Unit-length normalization & atomic documents: Scale each vector to Euclidean length 1.0 (L2 norm) so dot-product scoring equals cosine similarity; reject zero-norm or non-finite (NaN/inf) vectors. Index a document only if all of its chunks succeed. Store chunk c (0, 1, ...) of doc_id deterministically as: {'id': f'{doc_id}#{c}', 'doc_id': doc_id, 'chunk': c, 'vector': unit_vector, 'category': doc.get('category'), 'text': chunk_text}.
    • Return {'indexed': [doc_id, ...], 'failed': [(doc_id, reason), ...]}.
  2. search_vector_store(query, category_filter, top_k=5, *, embed_model, vector_db, max_retries=2, retry_delay=0.5) -> List[dict]

    • Return [] immediately (without calling embed_model) when top_k <= 0 or query is empty/whitespace-only.
    • Encode [query] using the same retry policy and L2-normalize the resulting vector; raise EmbeddingError if the query cannot be embedded or normalized.
    • Pass {'category': category_filter} into vector_db.query (or {} when category_filter is None), over-fetching candidate chunks so multi-chunk documents do not crowd out distinct documents.
    • Collapse hits by 'doc_id' (retaining each document's highest-scoring chunk), rank by descending 'score' with ties broken by ascending 'doc_id', and return up to top_k dictionaries of shape {'id': doc_id, 'score': score, 'category': category, 'text': best_chunk_text}.

Examples

Example 1

Toy model outputs:
  encode(["reset api token"])     -> [[3.0, 4.0, 0.0]]
  encode(["invoice tax receipt"]) -> [[0.0, 0.0, 2.0]]
  encode(["rotate secret key"])   -> [[4.0, 0.0, 3.0]]

Input:
  docs = [
      {"id": "kb1", "text": "reset api token", "category": "security"},
      {"id": "kb2", "text": "invoice tax receipt", "category": "billing"},
  ]
  report = process_and_index_documents(docs, embed_model=..., vector_db=..., split_text=...)
  hits = search_vector_store("rotate secret key", "security", top_k=1, embed_model=..., vector_db=...)

Output:
  report -> {"indexed": ["kb1", "kb2"], "failed": []}
  hits   -> [{"id": "kb1", "score": 0.48, "category": "security", "text": "reset api token"}]

Walk-through: "kb1#0" normalizes [3, 4, 0] (length 5) to [0.6, 0.8, 0.0], and "kb2#0" normalizes [0, 0, 2] (length 2) to [0.0, 0.0, 1.0]. The query "rotate secret key" normalizes [4, 0, 3] (length 5) to [0.8, 0.0, 0.6]. Filtering inside vector_db.query restricts candidates to "security" (excluding "kb2" even though its unfiltered dot product 0.60 would be higher) and scores "kb1" at 0.6 * 0.8 + 0.8 * 0.0 + 0.0 * 0.6 = 0.48.

Example 2

Input:
  docs = [
      {"id": "kb3", "text": "obsolete draft", "category": "security"},
      {"id": "kb3", "text": "<700-token SSO guide split into chunk 0 and chunk 1>", "category": "security"},
      {"id": "kb4", "text": "   ", "category": "billing"},
  ]

Output:
  report -> {"indexed": ["kb3"], "failed": [("kb4", "empty text")]}
  search_vector_store("sso", None, top_k=2, ...) -> [{"id": "kb3", "score": 1.0, "category": "security", "text": "<chunk 1 text>"}]

Walk-through: Duplicate ID "kb3" keeps only its final 700-token version, which splits into "kb3#0" and "kb3#1". "kb4" fails validation because its text is blank. When searching "sso" across all categories (category_filter=None), both "kb3#0" and "kb3#1" match, and collapsing by doc_id returns "kb3" once using its higher-scoring chunk.

Constraints

  • MAX_CHUNK_TOKENS = 512 and default EMBED_BATCH_SIZE = 32.
  • Re-running process_and_index_documents on unchanged documents must overwrite existing f"{doc_id}#{chunk}" records in place rather than creating duplicates.
  • A multi-chunk document must never be partially indexed if one of its chunks fails encoding or L2 normalization.
  • Transient model failures retry up to max_retries times; exhausted query retries raise EmbeddingError, whereas exhausted ingestion batch retries isolate the failed batch and report affected documents in 'failed'.

Step-by-step walkthrough

  1. Restate the problem and external interfaces

    We are building the two halves of a semantic document-retrieval service:

    1. Batch ingestion (process_and_index_documents): Take raw articles {'id': str, 'text': str, 'category': str}, split long bodies into chunks of at most 512 tokens, turn every chunk into a unit-length embedding vector, and write those chunks into a vector store idempotently.
    2. Filtered search (search_vector_store): Take a user query string and an optional category_filter, embed the query with the exact same model, and return the top_k best-matching distinct documents in that category.

    To make the code testable without live network services, the external collaborators are injected as keyword arguments:

    • embed_model.encode(texts) takes a list of B strings and returns B float vectors (one list of floats per input string).
    • split_text(text, max_tokens) splits text into a list of chunk strings ([text] if it already fits in 512 tokens).
    • vector_db.upsert(records) inserts each record or overwrites any existing record with the same record['id'].
    • vector_db.query(vector, filter, k) returns up to k stored records matching every key-value pair in filter, ranked highest dot-product score first.

    Here is how data flows through both pipelines:

    INGESTION:
      docs ---> [1. Dedupe IDs] ---> [2. Validate & Chunk <=512] ---> [3. Batch Encode + Retry]
                                                                                |
           vector_db.upsert <--- [4. All-or-Nothing Records id="kb1#0"] <--- [L2 Normalize]
    
    RETRIEVAL:
      query ---> [Encode + Retry] ---> [L2 Normalize] ---> vector_db.query(vec, {"category": ...}, 3*k)
                                                                   |
                                         top_k docs <--- [Keep best chunk per doc_id]
    
  2. Why a naive `for` loop breaks in production

    A beginner's first draft often loops for doc in documents: vec = embed_model.encode([doc['text']])[0]; db.insert(vec). That breaks in five ways:

    • One network call per document is too slow: At 50 ms per API round-trip, 100,000 products take 5,000 seconds (~83 minutes) sequentially. Grouping 32 chunks per batch cuts 100,000 calls down to 3,125.
    • One giant call for everything crashes: Passing all 100,000 texts in a single encode call blows past GPU memory or HTTP payload limits. Fixed-size batching (EMBED_BATCH_SIZE = 32) hits the sweet spot.
    • Unnormalized dot products bias toward long vectors: Vector stores often score candidates with a fast dot product a . b. Without scaling every vector to length 1, a vector with larger magnitude wins even when it points in a worse direction.
    • Random IDs create duplicates on retries: Generating a fresh UUID on every run appends duplicate copies whenever an ingestion job restarts.
    • Partial failures corrupt search: If chunk 0 of a 2-chunk product succeeds and chunk 1 times out, storing chunk 0 alone leaves half a product description in the index.
  3. Key math & invariants: unit vectors, deterministic IDs, all-or-nothing docs

    1. Why L2 normalization turns dot products into cosine similarity: Cosine similarity measures the angle between two vectors a and b, ignoring their lengths:

    cosine_similarity(a, b) = (a . b) / (||a|| * ||b||)
    where a . b = a_0*b_0 + a_1*b_1 + ...  and  ||a|| = sqrt(a_0^2 + a_1^2 + ...)
    

    If we divide every document vector d by ||d|| during ingestion and divide the query vector q by ||q|| during search, both vectors now have length 1.0 (||d|| = 1, ||q|| = 1). The denominator becomes 1 * 1 = 1, so cosine_similarity(q, d) simplifies to plain q . d!

    Check with a tiny 3D example: - Document vector a = [3, 4, 0] has length sqrt(9 + 16 + 0) = 5 -> normalized u_a = [0.6, 0.8, 0.0]. - Query vector b = [4, 0, 3] has length sqrt(16 + 0 + 9) = 5 -> normalized u_b = [0.8, 0.0, 0.6]. - Their dot product is 0.6*0.8 + 0.8*0.0 + 0.0*0.6 = 0.48, matching (3*4 + 0 + 0) / (5 * 5) = 12 / 25 = 0.48. - A zero vector [0, 0, 0] has length 0 and no direction, so we reject it with EmbeddingError instead of dividing by zero.

    2. Deterministic chunk IDs give idempotency: Idempotency means running the exact same job once or five times leaves the database in the exact same state. By naming chunk c of document doc_id as f"{doc_id}#{c}" (e.g., "kb1#0", "kb1#1") and keeping doc_id in a separate metadata field, re-running upsert cleanly overwrites "kb1#0" in place.

    3. All-or-nothing documents & isolated batch errors: If any chunk of doc_id fails to embed or produces a zero/NaN vector, we record doc_id in bad_docs and skip all chunks of doc_id when writing to vector_db, while letting healthy batches finish normally.

  4. Helper functions: `l2_normalize` and `encode_with_retry`

    Let's write two small, focused helpers first:

    • l2_normalize(vector) computes the Euclidean length norm, rejects 0.0, NaN, or inf (not math.isfinite(norm)), and divides every coordinate by norm.
    • encode_with_retry(...) retries transient embed_model.encode exceptions up to max_retries times using exponential backoff — waiting retry_delay, then 2 * retry_delay, 4 * retry_delay, and so on so a struggling model service has breathing room to recover. If encode returns the wrong number of vectors, that is a code bug rather than a transient blip, so we raise EmbeddingError immediately.
    from typing import Dict, List, Optional, Tuple
    import math
    import time
    
    MAX_CHUNK_TOKENS = 512
    EMBED_BATCH_SIZE = 32
    UPSERT_BATCH_SIZE = 100
    CHUNK_OVERFETCH = 3
    
    
    class EmbeddingError(Exception):
        """The embedding model kept failing (after retries) or returned an unusable vector."""
    
    
    def l2_normalize(vector: List[float]) -> List[float]:
        # Compute Euclidean length sqrt(v_0^2 + v_1^2 + ...) so every stored vector has length 1.0
        squared_sum = 0.0
        for value in vector:
            squared_sum += value * value
        norm = math.sqrt(squared_sum)
    
        # A zero-length, NaN, or infinite vector has no valid direction for cosine similarity
        if norm == 0.0 or not math.isfinite(norm):
            raise EmbeddingError("vector has zero or non-finite length")
    
        unit_vector = []
        for value in vector:
            unit_vector.append(value / norm)
        return unit_vector
    
    
    def encode_with_retry(embed_model, texts: List[str], max_retries: int,
                          retry_delay: float) -> List[List[float]]:
        attempt = 0
        while True:
            try:
                vectors = embed_model.encode(texts)
            except Exception as exc:
                # Catch client-specific timeout or network errors and retry with exponential backoff
                attempt += 1
                if attempt > max_retries:
                    raise EmbeddingError(f"encode failed after {attempt} attempts: {exc!r}") from exc
                sleep_seconds = retry_delay * (2 ** (attempt - 1))
                time.sleep(sleep_seconds)
                continue
    
            # A shape mismatch is a contract bug rather than a transient outage, so fail immediately
            if len(vectors) != len(texts):
                raise EmbeddingError(f"model returned {len(vectors)} vectors for {len(texts)} texts")
            return vectors
    
  5. Build the batch ingestion pipeline

    process_and_index_documents runs in four clean phases:

    1. Deduplicate input IDs: Missing IDs go straight to failed. If the same id appears twice in one call, latest_docs[doc_id] = doc keeps only the latest version. Notice we validate text after deduplicating: if "kb1" appears first with blank text and later with valid text, the valid update wins cleanly; if the later update is blank, it fails instead of indexing stale text.
    2. Validate and chunk: Non-empty strings are passed to split_text(text, 512) to produce (doc_id, chunk_index, chunk_text) tuples.
    3. Batch encode and normalize: Slice chunks in steps of batch_size. If a batch fails after retries, record each doc_id in that batch inside bad_docs and keep going with the remaining batches.
    4. Upsert healthy documents: Skip any chunk whose doc_id is in bad_docs, upsert the rest in batches of 100, and return {"indexed": ..., "failed": ...}.
    def process_and_index_documents(documents: List[dict], *, embed_model, vector_db, split_text,
                                    batch_size: int = EMBED_BATCH_SIZE, max_retries: int = 2,
                                    retry_delay: float = 0.5) -> Dict[str, list]:
        # failed: list of (doc_id, reason), e.g. [(None, "missing id"), ("kb9", "empty text")]
        failed: List[Tuple[str, str]] = []
    
        # Phase 1: deduplicate by doc_id so repeated IDs in one batch keep only their latest version
        latest_docs: Dict[str, dict] = {}
        for doc in documents:
            doc_id = doc.get("id")
            if not doc_id:
                failed.append((doc_id, "missing id"))
                continue
            latest_docs[doc_id] = doc
    
        # Phase 2: validate surviving text and split long documents into <= 512-token chunks
        chunks: List[Tuple[str, int, str]] = []
        bad_docs: Dict[str, str] = {}
        for doc_id, doc in latest_docs.items():
            text = doc.get("text")
            if not isinstance(text, str) or not text.strip():
                bad_docs[doc_id] = "empty text"
                continue
            pieces = split_text(text, MAX_CHUNK_TOKENS)
            if not pieces:
                bad_docs[doc_id] = "no chunks produced"
                continue
            for chunk_index, chunk_text in enumerate(pieces):
                chunks.append((doc_id, chunk_index, chunk_text))
    
        # Phase 3: embed chunks in fixed-size batches and L2-normalize each resulting vector
        chunk_vectors: Dict[Tuple[str, int], List[float]] = {}
        for start in range(0, len(chunks), batch_size):
            batch = chunks[start:start + batch_size]
            batch_texts = [chunk_text for _, _, chunk_text in batch]
            try:
                raw_vectors = encode_with_retry(embed_model, batch_texts, max_retries, retry_delay)
            except EmbeddingError as exc:
                for doc_id, _, _ in batch:
                    bad_docs.setdefault(doc_id, str(exc))
                continue
    
            for (doc_id, chunk_index, _), raw_vector in zip(batch, raw_vectors):
                try:
                    chunk_vectors[(doc_id, chunk_index)] = l2_normalize(raw_vector)
                except EmbeddingError as exc:
                    bad_docs.setdefault(doc_id, str(exc))
    
        # Phase 4: build deterministic chunk records (all-or-nothing per doc) and upsert in batches
        records = []
        for doc_id, chunk_index, chunk_text in chunks:
            if doc_id in bad_docs:
                continue
            records.append({
                "id": f"{doc_id}#{chunk_index}",
                "doc_id": doc_id,
                "chunk": chunk_index,
                "vector": chunk_vectors[(doc_id, chunk_index)],
                "category": latest_docs[doc_id].get("category"),
                "text": chunk_text,
            })
    
        for start in range(0, len(records), UPSERT_BATCH_SIZE):
            vector_db.upsert(records[start:start + UPSERT_BATCH_SIZE])
    
        indexed = [doc_id for doc_id in latest_docs if doc_id not in bad_docs]
        for doc_id, reason in bad_docs.items():
            failed.append((doc_id, reason))
        return {"indexed": indexed, "failed": failed}
    
  6. Build the filtered search service

    Two subtle bugs trip up vector search implementations:

    1. Post-filtering instead of pre-filtering: Suppose the knowledge base has 20 "billing" articles that match "reset" with score 0.95 and 1 "security" article with score 0.70. If you ask vector_db for the global top 5 without a filter and filter "security" afterward in Python, all 5 slots are taken by "billing" and you falsely return []! Always pass {"category": category_filter} inside vector_db.query.
    2. Returning chunks instead of documents: A long article split into 4 chunks could occupy 4 of the top_k = 5 results. We ask vector_db.query for top_k * CHUNK_OVERFETCH (3 * top_k) chunk hits, keep only the highest-scoring chunk per doc_id, sort by (-score, doc_id), and slice [:top_k].

    Also guard edge inputs cleanly: top_k <= 0 or a blank query returns [] immediately without calling embed_model, whereas a failed query embedding raises EmbeddingError so callers never confuse an outage with "zero matching articles."

    def _rank_key(hit: dict) -> Tuple[float, str]:
        # Sort higher cosine similarity first; break score ties deterministically by doc_id
        return (-hit["score"], hit["doc_id"])
    
    
    def search_vector_store(query: str, category_filter: Optional[str], top_k: int = 5, *,
                            embed_model, vector_db, max_retries: int = 2,
                            retry_delay: float = 0.5) -> List[dict]:
        # Guard invalid top_k or blank queries before spending a network call on embed_model
        if top_k <= 0 or not query or not query.strip():
            return []
    
        # Embed and L2-normalize the query with the exact same pipeline so dot product == cosine
        raw_query_vectors = encode_with_retry(embed_model, [query], max_retries, retry_delay)
        query_vector = l2_normalize(raw_query_vectors[0])
    
        # Push category filtering into vector_db.query so non-matching categories cannot crowd out hits
        metadata_filter = {}
        if category_filter is not None:
            metadata_filter["category"] = category_filter
        chunk_hits = vector_db.query(query_vector, metadata_filter, top_k * CHUNK_OVERFETCH)
    
        # Collapse multiple matching chunks of the same document by keeping its highest-scoring chunk
        best_hit_by_doc: Dict[str, dict] = {}
        for hit in chunk_hits:
            doc_id = hit["doc_id"]
            if doc_id not in best_hit_by_doc or hit["score"] > best_hit_by_doc[doc_id]["score"]:
                best_hit_by_doc[doc_id] = hit
    
        ranked_hits = sorted(best_hit_by_doc.values(), key=_rank_key)
        results = []
        for hit in ranked_hits[:top_k]:
            results.append({
                "id": hit["doc_id"],
                "score": hit["score"],
                "category": hit["category"],
                "text": hit["text"],
            })
        return results
    
  7. Walk through Example 1 and complete solution

    Trace Example 1 with our 3D toy model where encode(["reset api token"]) -> [[3.0, 4.0, 0.0]], encode(["invoice tax receipt"]) -> [[0.0, 0.0, 2.0]], and encode(["rotate secret key"]) -> [[4.0, 0.0, 3.0]]:

    1. Ingest [{'id': 'kb1', 'text': 'reset api token', 'category': 'security'}, {'id': 'kb2', 'text': 'invoice tax receipt', 'category': 'billing'}]:
      • latest_docs = {'kb1': ..., 'kb2': ...}, chunks = [('kb1', 0, 'reset api token'), ('kb2', 0, 'invoice tax receipt')].
      • l2_normalize([3.0, 4.0, 0.0]) divides by 5.0 -> [0.6, 0.8, 0.0]; l2_normalize([0.0, 0.0, 2.0]) divides by 2.0 -> [0.0, 0.0, 1.0].
      • vector_db.upsert stores 'kb1#0' and 'kb2#0' with unit vectors and metadata.
      • Returns {'indexed': ['kb1', 'kb2'], 'failed': []}.
    2. Search search_vector_store('rotate secret key', 'security', top_k=1):
      • Query vector [4.0, 0.0, 3.0] normalizes to [0.8, 0.0, 0.6].
      • vector_db.query([0.8, 0.0, 0.6], {'category': 'security'}, 3) excludes 'kb2#0' ('billing') inside the store and computes dot product 0.6*0.8 + 0.8*0.0 + 0.0*0.6 = 0.48 on 'kb1#0'.
      • Returns [{'id': 'kb1', 'score': 0.48, 'category': 'security', 'text': 'reset api token'}].

    Here is the complete solution.py:

    from typing import Dict, List, Optional, Tuple
    import math
    import time
    
    MAX_CHUNK_TOKENS = 512
    EMBED_BATCH_SIZE = 32
    UPSERT_BATCH_SIZE = 100
    # Multiple chunks of one long document can fill the top hits, so fetch extra chunk hits
    # before collapsing chunks back into distinct documents.
    CHUNK_OVERFETCH = 3
    
    
    class EmbeddingError(Exception):
        """The embedding model kept failing (after retries) or returned an unusable vector."""
    
    
    def l2_normalize(vector: List[float]) -> List[float]:
        # Compute Euclidean length sqrt(v_0^2 + v_1^2 + ...) so every stored vector has length 1.0
        squared_sum = 0.0
        for value in vector:
            squared_sum += value * value
        norm = math.sqrt(squared_sum)
    
        # A zero-length, NaN, or infinite vector has no valid direction for cosine similarity
        if norm == 0.0 or not math.isfinite(norm):
            raise EmbeddingError("vector has zero or non-finite length")
    
        unit_vector = []
        for value in vector:
            unit_vector.append(value / norm)
        return unit_vector
    
    
    def encode_with_retry(embed_model, texts: List[str], max_retries: int,
                          retry_delay: float) -> List[List[float]]:
        attempt = 0
        while True:
            try:
                vectors = embed_model.encode(texts)
            except Exception as exc:
                # Catch client-specific timeout or network errors and retry with exponential backoff
                attempt += 1
                if attempt > max_retries:
                    raise EmbeddingError(f"encode failed after {attempt} attempts: {exc!r}") from exc
                sleep_seconds = retry_delay * (2 ** (attempt - 1))
                time.sleep(sleep_seconds)
                continue
    
            # A shape mismatch is a contract bug rather than a transient outage, so fail immediately
            if len(vectors) != len(texts):
                raise EmbeddingError(f"model returned {len(vectors)} vectors for {len(texts)} texts")
            return vectors
    
    
    def process_and_index_documents(documents: List[dict], *, embed_model, vector_db, split_text,
                                    batch_size: int = EMBED_BATCH_SIZE, max_retries: int = 2,
                                    retry_delay: float = 0.5) -> Dict[str, list]:
        # failed: list of (doc_id, reason), e.g. [(None, "missing id"), ("kb9", "empty text")]
        failed: List[Tuple[str, str]] = []
    
        # Phase 1: deduplicate by doc_id so repeated IDs in one batch keep only their latest version
        # latest_docs: {"kb1": {"id": "kb1", "text": "reset api token", "category": "security"}, ...}
        latest_docs: Dict[str, dict] = {}
        for doc in documents:
            doc_id = doc.get("id")
            if not doc_id:
                failed.append((doc_id, "missing id"))
                continue
            latest_docs[doc_id] = doc
    
        # Phase 2: validate surviving text and split long documents into <= 512-token chunks
        # chunks: [("kb1", 0, "reset api token"), ("kb3", 0, "..."), ("kb3", 1, "...")]
        chunks: List[Tuple[str, int, str]] = []
        # bad_docs: maps doc_id -> first error message so partial documents are never indexed
        bad_docs: Dict[str, str] = {}
        for doc_id, doc in latest_docs.items():
            text = doc.get("text")
            if not isinstance(text, str) or not text.strip():
                bad_docs[doc_id] = "empty text"
                continue
            pieces = split_text(text, MAX_CHUNK_TOKENS)
            if not pieces:
                bad_docs[doc_id] = "no chunks produced"
                continue
            for chunk_index, chunk_text in enumerate(pieces):
                chunks.append((doc_id, chunk_index, chunk_text))
    
        # Phase 3: embed chunks in fixed-size batches and L2-normalize each resulting vector
        # chunk_vectors: {("kb1", 0): [0.6, 0.8, ...], ...}
        chunk_vectors: Dict[Tuple[str, int], List[float]] = {}
        for start in range(0, len(chunks), batch_size):
            batch = chunks[start:start + batch_size]
            batch_texts = [chunk_text for _, _, chunk_text in batch]
            try:
                raw_vectors = encode_with_retry(embed_model, batch_texts, max_retries, retry_delay)
            except EmbeddingError as exc:
                # Isolate batch failures: mark affected documents failed, keep processing later batches
                for doc_id, _, _ in batch:
                    bad_docs.setdefault(doc_id, str(exc))
                continue
    
            for (doc_id, chunk_index, _), raw_vector in zip(batch, raw_vectors):
                try:
                    chunk_vectors[(doc_id, chunk_index)] = l2_normalize(raw_vector)
                except EmbeddingError as exc:
                    bad_docs.setdefault(doc_id, str(exc))
    
        # Phase 4: build deterministic chunk records (all-or-nothing per doc) and upsert in batches
        records = []
        for doc_id, chunk_index, chunk_text in chunks:
            if doc_id in bad_docs:
                continue
            records.append({
                "id": f"{doc_id}#{chunk_index}",
                "doc_id": doc_id,
                "chunk": chunk_index,
                "vector": chunk_vectors[(doc_id, chunk_index)],
                "category": latest_docs[doc_id].get("category"),
                "text": chunk_text,
            })
    
        for start in range(0, len(records), UPSERT_BATCH_SIZE):
            vector_db.upsert(records[start:start + UPSERT_BATCH_SIZE])
    
        indexed = [doc_id for doc_id in latest_docs if doc_id not in bad_docs]
        for doc_id, reason in bad_docs.items():
            failed.append((doc_id, reason))
        return {"indexed": indexed, "failed": failed}
    
    
    def _rank_key(hit: dict) -> Tuple[float, str]:
        # Sort higher cosine similarity first; break score ties deterministically by doc_id
        return (-hit["score"], hit["doc_id"])
    
    
    def search_vector_store(query: str, category_filter: Optional[str], top_k: int = 5, *,
                            embed_model, vector_db, max_retries: int = 2,
                            retry_delay: float = 0.5) -> List[dict]:
        # Guard invalid top_k or blank queries before spending a network call on embed_model
        if top_k <= 0 or not query or not query.strip():
            return []
    
        # Embed and L2-normalize the query with the exact same pipeline so dot product == cosine
        raw_query_vectors = encode_with_retry(embed_model, [query], max_retries, retry_delay)
        query_vector = l2_normalize(raw_query_vectors[0])
    
        # Push category filtering into vector_db.query so non-matching categories cannot crowd out hits
        metadata_filter = {}
        if category_filter is not None:
            metadata_filter["category"] = category_filter
        chunk_hits = vector_db.query(query_vector, metadata_filter, top_k * CHUNK_OVERFETCH)
    
        # Collapse multiple matching chunks of the same document by keeping its highest-scoring chunk
        # best_hit_by_doc: {"kb1": {"doc_id": "kb1", "score": 0.87, ...}, ...}
        best_hit_by_doc: Dict[str, dict] = {}
        for hit in chunk_hits:
            doc_id = hit["doc_id"]
            if doc_id not in best_hit_by_doc or hit["score"] > best_hit_by_doc[doc_id]["score"]:
                best_hit_by_doc[doc_id] = hit
    
        ranked_hits = sorted(best_hit_by_doc.values(), key=_rank_key)
        results = []
        for hit in ranked_hits[:top_k]:
            results.append({
                "id": hit["doc_id"],
                "score": hit["score"],
                "category": hit["category"],
                "text": hit["text"],
            })
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of an embedding (a fixed-length list of numbers produced by a neural network to represent a text's meaning) as GPS coordinates on a semantic map: "reset api token" and "rotate secret key" land right next to each other even though they share zero words. To build a reliable search engine on top of that map, we standardize every arrow to have length 1.0 (L2 normalization, dividing each number in a vector by the square root of the sum of its squared numbers) so that comparing any two arrows only requires multiplying matching coordinates and adding them up (a dot product), which then equals cosine similarity (how closely two vectors point in the same direction, from -1 to +1).

A naive loop that embeds one document per API call, appends random record IDs, and filters categories after fetching the top 5 results breaks immediately at production scale. Calling the model one text at a time wastes hours on network round-trips (while sending all texts at once overflows GPU memory), random IDs create duplicate search hits whenever a failed job is retried, and filtering after retrieval returns empty results whenever another category crowds out the global top 5. Instead, we chunk long documents to <= 512 tokens, embed in fixed batches of 32 with retries, upsert (insert if new, overwrite if the ID already exists) using deterministic "doc_id#chunk" keys for idempotency (running the same job twice produces the exact same stored state), and push category filters directly into the vector database query.

Walk through a concrete 2-document trace in 3D: 1. Suppose "kb1" ("reset api token", "security") encodes to [3, 4, 0] (length 5 -> normalized [0.6, 0.8, 0.0]) and "kb2" ("invoice tax receipt", "billing") encodes to [0, 0, 2] (length 2 -> normalized [0.0, 0.0, 1.0]). We upsert "kb1#0" and "kb2#0". 2. An engineer searches "rotate secret key" inside "security" with top_k = 1, and the query encodes to [4, 0, 3] (length 5 -> normalized [0.8, 0.0, 0.6]). 3. vector_db.query([0.8, 0.0, 0.6], {"category": "security"}, 3) restricts candidates to "security" ("kb1#0", preventing "kb2#0" from winning with 0.60), computes dot product 0.6*0.8 + 0.8*0.0 + 0.0*0.6 = 0.48, deduplicates by doc_id, and returns [{"id": "kb1", "score": 0.48, ...}].

Complexity

Let D be the number of input documents, C be the total number of <= 512-token chunks produced across them, B be batch_size (32), d be the embedding dimension (e.g., 768), and M be the total chunks stored in vector_db.

  • Ingestion time — O(C * d) CPU work plus ceil(C / B) model API calls and ceil(C / 100) DB upsert calls: We scan D documents once to deduplicate IDs, split valid texts into C chunks, send ceil(C / B) batches to embed_model.encode (which dominates wall-clock latency), and spend O(d) arithmetic per chunk inside l2_normalize.
  • Ingestion space — O(C * d): One invocation holds the C chunks and their d-dimensional normalized float lists in memory before upserting; for millions of catalog items, stream pages of ~1,000 documents per call so memory stays bounded.
  • Search time — 1 model call + O(d) normalization + vector_db.query + O(h log h) deduplication/sort where h <= 3 * top_k: A brute-force flat vector store scans O(M * d) floats, whereas production approximate nearest-neighbor indexes like HNSW (Hierarchical Navigable Small World, a multi-layer proximity graph over vectors) search in roughly O(d * log M) time.
  • Search space — O(d + h): We hold only the single d-float query vector and at most h = 3 * top_k candidate chunk records in memory.

Edge cases

  • Empty documents list ([]): Makes zero calls to embed_model or vector_db and returns {"indexed": [], "failed": []}.
  • Missing id or blank/whitespace text: Caught before calling embed_model and reported in "failed".
  • Duplicate id within the same documents call: Deduplicated up front so the last occurrence wins; if "kb1" arrives blank first and valid second it succeeds cleanly, whereas valid first and blank second marks "kb1" failed without indexing stale text.
  • Splitter produces zero chunks (e.g., punctuation-only text stripped by tokenizer): Caught by if not pieces: and marked failed rather than falsely reported as indexed with zero stored vectors.
  • Zero-length, NaN, or inf vector from the model: Rejected by l2_normalize (norm == 0.0 or not math.isfinite(norm)), failing the owning document cleanly instead of storing NaN scores that poison rankings.
  • Multi-chunk document partially fails across batch boundaries: Because records skips every chunk whose doc_id appears in bad_docs, a document is indexed all-or-nothing.
  • Blank query, top_k <= 0, or category with zero matches: Returns [] cleanly (and blank/top_k <= 0 skips the embed_model call completely), whereas a broken query model raises EmbeddingError so the caller can return HTTP 503 instead of fake empty search results.

Common mistakes

  • Normalizing stored vectors without normalizing the query (or vice versa): If stored document vectors are unnormalized, longer vectors artificially inflate dot products and corrupt the ranking order; if the query vector is unnormalized, relative order holds for one query but similarity scores are scaled by ||query|| and lose their [-1, 1] cosine meaning.
  • Using random UUIDs instead of deterministic IDs: Assigning uuid4() per chunk turns every pipeline retry into duplicate vectors that fill top_k results with copies of the same article.
  • Filtering categories after vector_db.query: Fetching the global top_k first and filtering in Python returns [] whenever popular items from other categories take all top_k slots.
  • Returning raw chunks instead of distinct documents: Without over-fetching (top_k * CHUNK_OVERFETCH) and grouping by doc_id, one 2,000-word article can monopolize all 5 search slots.
  • Swallowing query embedding exceptions into return []: Returning an empty list when the embedding service times out hides outages behind "No results found" pages instead of triggering alerts or fallback keyword search.
  • Upgrading the embedding model without re-indexing: Vectors from Model v2 live in a rotated coordinate space incompatible with Model v1 vectors; query and index models must always match.

Alternative approaches

  • Vectorized NumPy normalization: When embed_model.encode returns a 2D numpy.ndarray of shape (B, d), normalize an entire batch in C without Python loops (checking zero norms per row so one bad row can still be isolated):
import numpy as np


def l2_normalize_batch(matrix: np.ndarray) -> np.ndarray:
    norms = np.linalg.norm(matrix, axis=1, keepdims=True)
    if np.any((norms == 0.0) | ~np.isfinite(norms)):
        raise ValueError("batch contains a zero or non-finite vector")
    return matrix / norms
  • Binary-splitting poison batches: If a batch of 32 chunks fails permanently because a single malformed text crashes the model, recursively split the failed batch into two halves of 16, 8, ..., 1 to isolate the single bad chunk in log2(32) = 5 extra calls while rescuing the other 31 chunks.
  • Hybrid lexical + vector search: Combine dense cosine similarity with BM25 (a classic keyword-matching score based on term frequency and word rarity) via Reciprocal Rank Fusion so exact error codes like "ERR_OAUTH_401" match precisely alongside semantic queries like "rotate expired credentials".

Follow-up questions

  • When source articles are edited or shortened over time, how do you keep the vector store synchronized without leaving orphaned chunks behind? Store a content_hash = sha256(model_version + "\n" + text) and chunk_count alongside each document so unchanged items skip re-embedding completely. When an article's text changes, upsert the new chunks first and then delete stale tail chunks: for example, if "kb1" shrinks from 4 chunks (kb1#0..kb1#3) to 2 chunks (kb1#0..kb1#1), explicitly delete kb1#2 and kb1#3 so old paragraphs stop matching searches. Stream updates from a transactional outbox with a monotonic version number per doc_id (ignoring out-of-order older versions), run a nightly reconciliation sweep comparing source hashes against indexed hashes, and handle embedding-model upgrades via blue-green indexing (build a complete second index with the new model, then atomically swap the read alias).

  • Once the vector collection outgrows a single machine's RAM, how would you compress, tier, and shard the index across nodes? First size the footprint: 50 million chunks at 768 float32 dimensions (4 bytes each) takes 50M * 768 * 4 ≈ 153.6 GB of raw vectors before graph overhead. You can first shrink RAM per node by 2x with float16 or by 32x (~4.8 GB) using product quantization (splitting each 768D vector into 96 sub-vectors and replacing each sub-vector with a 1-byte nearest-centroid ID), keeping full float32 vectors on NVMe SSDs (or disk-backed indexes like DiskANN / IVF, Inverted File indexes that cluster vectors into Voronoi cells on disk) to re-score the top 100 candidates accurately. Beyond one machine, shard by hash(doc_id) for uniform storage and query load: a coordinator fans each query out to all S shards in parallel, fetches each shard's filtered top_k, and merges the S * top_k candidates in O(S * top_k). (Sharding by category avoids fan-out on category-filtered queries, but creates hot shards for popular categories like "security" and still requires full fan-out when category_filter is None.)

  • What offline benchmarks, live user signals, and score-distribution checks would you track to detect retrieval quality degradation as content and queries evolve? Monitor four complementary signals across offline quality, online user behavior, vector geometry, and pipeline health. First, run an automated golden evaluation set (hundreds of real queries paired with human-judged relevant articles) every day and alert if recall@5 (the fraction of relevant items appearing in the top 5) or nDCG@10 (Normalized Discounted Cumulative Gain, a ranking score that rewards placing stronger matches closer to rank 1) drops. Second, track online behavioral metrics: top-3 click-through rate, resolution/conversion rate from search, query reformulation rate, and zero-result rate. Third, monitor score and embedding drift by tracking the daily distribution of top-1 cosine similarity scores (using a Kolmogorov-Smirnov test or Population Stability Index against a baseline week — a sudden drop flags new terminology or thin descriptions the model does not understand) alongside ingestion lag and failed-document rates.

Follow-up questions

Similar questions

More Nike interview questions

All 3 Nike questions →