The interview problem
Design enterprise code search over 20 million code units at 200 queries per second. A developer asks, “Where do we retry failed uploads without creating duplicate objects?” Return authorized, navigable source locations from the requested repository version. Explain retrieval, training data, evaluation, freshness and failures.
Original ML-design practice, not a reported company interview. All workloads and numerical examples are hypothetical. Interview date not applicable; sources retrieved September 27, 2026.
1. Define what a correct result means
Similarity is insufficient. A retry loop that creates a new idempotency token on every attempt looks relevant but can violate the requested behavior. A helper that reuses the token may be useful, but its caller must also supply a stable operation identity. A comment promising idempotency is weaker evidence than the actual request construction and server contract.
Ask which repositories, branch or commit, languages and generated files are in scope. Distinguish finding an implementation, finding usage examples and explaining behavior. This service retrieves source evidence; it does not certify that arbitrary code is correct or execute repository code during indexing.
A result includes repository, immutable commit, path, symbol, source lines and an explanation tied to those lines. Queries requiring a caller/helper chain should return both pieces when available. If evidence is incomplete, say what remains unresolved rather than presenting a single similar function as a complete solution.
2. Build versioned retrieval units
authorized repository snapshot
↓
parse units + symbols + bounded dependency context
↓
lexical index + embedding index + versioned relationships
↓
validate and publish commit manifest atomically
query + repository/ref constraints + access policy
↓
lexical and dense retrieval → authorized candidate union
↓
query/code reranking with bounded context
↓
version checks → evidence snippets → immutable source linksUse a key containing repository ID, commit, path and a unit identity. Keep source blob hash, byte offsets, parser version and embedding model version. Function names are neither unique nor stable. A logical identity can help track renames, but the served result must refer to exact source bytes.
Parse functions and classes without splitting the controlling condition away from its body. Oversized units need subunits with their enclosing signature and source mapping. Index symbols and error strings lexically; use embeddings for natural-language intent. Retrieve bounded caller, callee or type context when it changes interpretation. Cap graph depth and token count: an unrestricted dependency expansion can consume an entire monorepo.
Resolve a requested branch to a commit. If that commit is not indexed, expose the lag and offer an explicitly labeled older snapshot rather than silently answering for another version. Publish a manifest only after the lexical, vector and relationship components for that snapshot pass validation. An interrupted build leaves the previous complete snapshot available.
3. Establish a strong baseline before structural models
Start with lexical retrieval over identifiers, signatures and comments, with repository and language filters. Add a dual encoder that embeds developer intent and code into a shared retrieval space. Merge and deduplicate candidates, then apply a more expensive query/code reranker to a bounded pool.
Train on reviewed query/code pairs and hard negatives: wrong overload, stale implementation, almost identical fork, missing error branch and retry code with an unstable token. Distinguish direct implementation, necessary dependency, merely related code and misleading matches. Several implementations can legitimately satisfy a query; treating every unclicked result as negative introduces false labels. Use a contrastive retrieval objective with reviewed positives and negatives, and a graded ranking objective for the reranker. Mask known alternative positives from in-batch negatives. Keep the selected commit and context visible to annotators so a label does not silently refer to another revision.
Documentation-derived pairs are a useful starting point, but documentation can be stale and its vocabulary may make benchmark retrieval easier than real developer tasks. Add independently written task queries and review relevance against the selected commit. Structural or data-flow features are optional improvements to compare against the baseline, not a prerequisite for calling the system semantic search.
Static relationships can be incomplete for reflection and dynamic dispatch. Expose parser coverage and use a labeled text fallback for unsupported languages. Do not silently treat missing edges as proof that no dependency exists. Tests can support a claim for the cases they exercise; neither a passing test nor a high retrieval score proves general behavioral equivalence.
4. Separate candidate recall from final usefulness
Construct 1,000 held-out developer queries with reviewed answers for a specified commit and permission scope. Suppose 800 have a valid implementation in the accessible corpus and 200 have no valid result. Split training and evaluation by repository/fork/clone family and time so near-identical revisions do not leak across the boundary.
| Measurement on the 800 answerable queries | Count | Rate |
|---|---|---|
| Candidate pool contains a direct implementation | 720 | 90% |
| Top result is a direct implementation | 600 | 75% |
| Top five contain a direct implementation | 680 | 85% |
Conditional top-one success among queries with a retrievable candidate is 600/720 = 83.33%. Reporting only that conditional number hides the 80 candidate-generation misses. A reranker operating on the same pool cannot recover them. A wrong-commit match does not count as success even when its text looks correct.
For multi-unit questions, measure whether the returned set covers the required evidence chain separately. Finding one implementation is not equivalent to proving that its callers preserve the required behavior. Use graded relevance or task-specific evidence labels alongside top-k hit metrics.
Evaluate abstention on both groups. A system that confidently returns a misleading snippet for every one of the 200 unanswerable queries has a serious defect even if its answerable-query ranking is strong. Report answer coverage, wrong confident answers, and correctness at the chosen threshold; do not remove abstained answerable queries from the denominator without labeling the conditional metric.
Compare lexical, dense and hybrid retrieval at equal candidate and latency budgets. Online signals can include successful navigation to the reviewed symbol and explicit corrections, but clicks alone reflect rank and familiarity. Use a controlled rollout with task completion, latency, permission violations and stale-result rates as separate outcomes.
5. Calculate storage and reranking cost
raw vectors = 20,000,000 × 768 dimensions × 2 bytes
= 30.72 GB
three copies = 92.16 GBThese decimal figures exclude ANN structures, metadata, source text and dependency graphs. They also assume one embedding per unit; multiple context representations increase the count. Avoid presenting raw vector size as the complete search-cluster memory requirement.
reranking demand = 200 queries/s × 100 pairs/query
= 20,000 query/code pairs/s
hypothetical benchmark capacity = 250 pairs/s
full-utilization equivalent = 20,000 / 250 = 80 workers
at 70% target utilization = ceil(80 / 0.70) = 115 workersThe worker throughput is an assumption to benchmark with the actual code lengths, batching and latency target. Queueing, peak traffic and failure tolerance may require more capacity. A long dependency context can lower throughput dramatically. Limit context and adapt the reranking pool, then measure the quality cost instead of silently truncating critical code.
If 1% of units require refreshed embeddings per day, that is 200,000 units. At an assumed 100 units per second, one worker needs 2,000 seconds, or 33 minutes 20 seconds, for embedding computation alone. Parsing, relationship updates, indexing and publication add time. The changed-unit estimate must include context invalidation: a modified shared helper can invalidate representations of unchanged callers.
6. Make authorization part of retrieval
Apply repository access constraints during candidate generation where supported, and recheck before returning text, names or links. A post-filter can underfill results, so measure authorized recall and overfetch within a bound. Never expose a forbidden repository's name through an explanation or suggestion.
Scope caches to effective permissions and source version. Revalidate on opening a result and invalidate cached snippets after revocation. The index can contain historical code a user no longer has permission to read; historical availability does not imply current authorization. Define deletion propagation for source copies, embeddings, logs and backups under the organization's retention policy.
Limit captured query and snippet telemetry because developer queries may themselves contain secrets. Secret scanning complements access controls but cannot guarantee that all sensitive values are detected. Do not execute build scripts or tests merely because they are present in an indexed repository.
7. Diagnose failure by stage
| Failure | What goes wrong | Response |
|---|---|---|
| Stale comment | Natural-language match contradicts implementation | Rerank with source and annotate unresolved behavioral evidence |
| Mixed commits | Helper context belongs to another revision | Use one validated snapshot manifest throughout retrieval |
| Fork duplicates | Top results repeat the same implementation | Group authorized equivalents while preserving provenance and access |
| Parser failure | Units or relationships disappear | Record coverage, use a labeled fallback and alert on regressions |
| Revoked repository | Cached snippets retain unauthorized source | Recheck access and invalidate all result-cache layers |
| Partial index build | One retrieval channel searches a newer commit | Publish atomically and retain the last complete manifest |
| Lost negation | “Without duplicate objects” becomes generic retry intent | Preserve constraints and include contradiction hard negatives |
Track candidate recall, reranker errors, unsupported language coverage, index lag, permission filtering and dependency-context truncation independently. A single aggregate relevance score cannot tell whether to improve parsing, retrieval, ranking or corpus freshness.
8. Trade-offs and follow-ups
Small units provide precise navigation but may hide behavior spread across functions. Larger contexts improve interpretation at higher embedding and reranking cost. Central indexing simplifies ranking across repositories; federated retrieval can fit data boundaries but complicates latency and score calibration. Frequent refresh reduces staleness but needs dependency-aware invalidation.
- The requested behavior is absent. Return an honest no-result or related evidence with explicit limitations, not invented source locations.
- The first result passes one retry test. Check failure modes and the idempotency contract; one test does not establish general correctness.
- A function was renamed. Resolve by the selected commit and source identity; use history only as additional evidence.
- A result is a wrapper. Include the delegated implementation when authorized and budget permits, and identify which unit supports each claim.
- The branch was deleted. Follow the repository's retention and access policy; an immutable commit link is useful only while that authorized snapshot remains available.
Self-review rubric
A strong answer defines correctness at a commit and permission scope, establishes a lexical baseline, uses code-specific hard negatives and distinguishes candidate recall from final evidence coverage. It checks clone leakage, sizes context-sensitive reranking, handles atomic publication and revocation, and avoids equating relevance with behavioral proof. An excellent answer explains how to debug a missed query and how dependency changes invalidate previously indexed context.
Sources and attribution
- CodeSearchNet Challenge — primary paper metadata and abstract on code-search benchmarking; submitted September 20, 2019, revised June 8, 2020.
- GraphCodeBERT — primary paper metadata and abstract describing data-flow-aware code representations; submitted September 17, 2020, revised September 13, 2021.
Retrieved September 27, 2026. These references motivate retrieval and structural representation choices; they do not establish current production performance. The workload, architecture, failure examples and calculations are original practice material. No recent company interview attribution is claimed.
Continue your preparation
Choose a connected learning path or browse more ML system design questions. Read our editorial method and attribution policy.