Design: AI coding assistant
Three products on one context engine: a small fill-in-the-middle model for sub-300 ms inline completion, a large model for chat over a repo index, and an agent that edits and runs tests in a sandbox.
Analogy: A pair programmer who whispers the next line as you type, answers questions about the codebase and, handed a ticket, works on a branch in another room and brings you a diff.
Fundamentals you'll use
How it works
- Scale: 100k seats make ~10k completion QPS; a suggestion must show ~300 ms after the typing pause.
- Gather context cheapest first: IDE state, then a tree-sitter symbol index, then embeddings fused with grep.
- Completion is prefill-heavy (~2.6k tokens in, ~20 out), so prefix caching matters more than decode speed.
- The worst failure is leaked code: per-tenant indexes, no training on customer code, and agent sandboxes without secrets.
- Measure acceptance rate plus retention after 30 s and 10 min, because accept-then-delete is a false positive.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your inline-completion fleet is GPU-saturated at peak, yet most suggestions it generates are never displayed. The IDE plugin debounces 75 ms and aborts the in-flight request on every keystroke. Most likely cause and fix?
Go deeper
Full explanation
Requirements
Functional: inline completion as you type (single and multi-line); chat about the repository with file citations; an agent that takes a task ("fix this failing test"), edits several files, runs the tests and proposes a diff. Admins get policies, content exclusions and usage reports.
Non-functional: a suggestion visible ~300 ms after the typing pause (later and the user has typed past it), chat TTFT < 2 s, agent tasks in minutes; cost per seat well under a ~$10–40/month price; customer code never used for training.
What I'd ask first:
- Which IDEs and languages, and how big are the repos (monorepos with 10M+ lines)?
- May code leave the customer's network, or is VPC/on-prem required?
- Where does the agent run code, with what network access and secrets?
- Is success acceptance rate, retained code, or merged PRs?
Highest-cost failure: customer code leaking — across tenants, into training data, or out of an agent sandbox. One incident ends enterprise sales.
High-level design
Three surfaces share one context engine but get different models, because their latency budgets differ by ~1,000× (300 ms vs ~5 min).
- Completion (hot path): the IDE plugin debounces keystrokes, cancels stale requests and builds a fill-in-the-middle (FIM) prompt locally from prefix, suffix and snippets of open tabs. A gateway checks a prefix cache, then a small FIM model in the nearest region streams a few lines.
- Chat: the question and selection go through retrieval over the repo index (symbols, embeddings and grep, as in Hybrid search & RRF), then a large model answers with citations.
- Agent: a tool loop on the large model (ReAct: the agent loop) calls
search,read_file,editandrun_testsagainst an isolated sandbox and returns a diff for human review (Human-in-the-loop & approvals). - Offline: an indexer parses each repo with tree-sitter into symbols and function-level chunks, embeds them, and updates incrementally on save and commit.
Code IDE side: debounce, cancel, cache
// IDE side of inline completion: most requests must die before they cost GPU time.
const DEBOUNCE_MS = 75; // lower = snappier, but more requests
const cache = new Map<string, string>(); // users backspace and retype constantly
let timer: ReturnType<typeof setTimeout> | undefined;
let inflight: AbortController | undefined;
export function onKeystroke(doc: TextDoc, cursor: number) {
clearTimeout(timer);
inflight?.abort(); // the old suggestion is already stale
timer = setTimeout(() => void complete(doc, cursor), DEBOUNCE_MS);
}
async function complete(doc: TextDoc, cursor: number) {
const prefix = doc.text.slice(Math.max(0, cursor - 6_000), cursor);
const suffix = doc.text.slice(cursor, cursor + 2_000); // so it won't re-close brackets
const key = hash(prefix.slice(-400) + "|" + suffix.slice(0, 200));
const hit = cache.get(key);
if (hit !== undefined) return showGhostText(hit);
inflight = new AbortController();
try {
const res = await fetch(COMPLETE_URL, {
method: "POST", signal: inflight.signal, // server sees the abort, stops decoding
body: JSON.stringify({
prefix, suffix,
snippets: similarSnippets(doc, 3), // open tabs and recent edits
max_tokens: 64, stop: ["\n\n"],
}),
});
const { text } = await res.json();
cache.set(key, text);
showGhostText(text);
} catch (e) {
if ((e as Error).name !== "AbortError") reportError(e);
}
}Real example
A developer pauses after typing def parse_invoice( in a 1,200-line file. After 75 ms of quiet the plugin cancels the previous in-flight request and builds a FIM prompt locally: ~1.5k tokens before the cursor, ~500 after, and 3 similar snippets from open tabs (~600), ~2.6k tokens in total. Network ~40 ms; prefill on a ~7B FIM model ~40 ms (less when the previous keystroke's prefix is still cached); then 15 tokens at ~8 ms each (~120 ms). The ghost text appears ~275 ms after the pause. The developer presses Tab; telemetry logs the accept and checks again after 30 s and 10 min how much of the inserted text survived.
Trade-offs +4 · −4
+ You gain
- Each surface gets the model its latency budget allows: small FIM for keystrokes, large for chat and agents.
- One context engine serves all three surfaces, so better indexing lifts everything at once.
- Tests as the verifier make agent output checkable instead of merely plausible.
- Retention metrics catch suggestions that get accepted and then deleted.
− You pay
- The completion fleet serves keystroke-rate traffic: ~10k QPS of short-lived, often cancelled requests.
- Per-customer repo indexes cost storage and compute, and must stay fresh on every save.
- Agent sandboxes burn real compute per task and are an attack surface.
- On-prem tiers fork the model, the release process and the support burden.
Use it when
Developer tools where latency tiers differ by orders of magnitude and code is customer-confidential: IDE assistants, internal developer platforms, code-review bots.
Avoid it when
A single surface (only chat, or only batch code review): skip the FIM fleet and the sandbox, and use one large model with repo retrieval.
Numbers to know 5
- Completion budget ~300 ms: debounce ~75 + network ~40 + prefill ~40 + 15 tokens × ~8 ms ≈ 275 ms (~7B FIM model, nearby region).
- Load: 100k seats × 40% typing at peak × 1 request per ~4 s after debounce ≈ 10k completion QPS.
- Prefill-bound: 10k QPS × ~2.6k input tokens ≈ 26M prefill tok/s vs ~200k output tok/s (~20 each), so prefix caching dominates.
- Agent task: 40 steps × ~30k context ≈ 1.2M input tokens ≈ $3.60 at an assumed $3/1M uncached, ~$0.70 with 90% cache hits at a 10% cache-read price, plus ~$0.30 output (~500/step at $15/1M).
- Index: 1M lines × ~10 tokens = 10M tokens ≈ 33k chunks of ~300 × 4 KB (1,024-dim float32) ≈ 135 MB; full re-embed ~$0.20 at $0.02/1M.
Common pitfalls 4
- Optimizing acceptance rate alone: longer, bolder suggestions get accepted, then deleted. Track retention and post-accept edit distance too.
- Aborting only on the client: the GPU keeps decoding stale requests, which at keystroke rates wastes a large share of the fleet. Propagate disconnects to the inference server.
- Running the agent with the developer's credentials and open egress: one injected instruction in a README can exfiltrate secrets (Prompt injection (direct & indirect)).
- A nightly index: suggestions call functions that were renamed this morning. Re-index changed files on save.
Interview questions 3
Answer out loud first, then reveal.
Why not use your best model for autocomplete?Show answer
Because the budget is ~300 ms end to end and the traffic is keystroke-rate. A frontier model's TTFT alone often exceeds that, and at ~10k QPS of mostly cancelled requests the cost per seat would exceed the seat price. Completions are short and tightly constrained by prefix and suffix, which is exactly where a small FIM-trained model is good enough. I spend the large model on chat and the agent, and distill it into the completion model on public and licensed code, measuring the swap by retention, not just acceptance.
How do you know the agent actually helps?Show answer
Three layers. Offline, an internal SWE-bench-style suite of real issues from repos we may use, with hidden tests; pass@1 and cost per solved task gate every model or prompt change. Online, the share of agent PRs merged, merged-then-reverted within a week, and how much humans edit before merging. Then weekly error analysis on failed traces: failures often come from localizing the wrong file, not from bad code. I don't trust public leaderboard scores here, because contamination and scaffolding differences make them weak predictors on our users' repos.
A bank wants it, but code can't leave their network. What changes?Show answer
Everything that phones home. I ship the stack as one deployable bundle, an inference server such as vLLM with an open-weights coder model, the indexer, the vector store and the agent sandboxes, into their VPC or on-prem GPUs, with telemetry reduced to aggregate counters they can audit. The trade-off is quality and velocity: open models trail frontier ones, and every release now goes through their change process. So I version the bundle quarterly, keep the plugin compatible across two versions, and run our eval suite inside their environment before each upgrade.
Deep dive 5
Completion: latency is the product
Past ~300–500 ms the user has typed beyond the suggestion, so the model is small (~1–15B), trained for fill-in-the-middle (it sees prefix and suffix, so it doesn't re-close a bracket that already exists) and served close to users at high priority. Most requests die young: debounce ~50–100 ms, abort on every keystroke and propagate the disconnect so the GPU stops decoding. Completion is prefill-heavy (~2.6k tokens in, ~20 out), so automatic prefix caching across consecutive keystrokes matters more than decode speed; speculative decoding (Speculative decoding) helps the multi-line case. Stop at end of line when the cursor is mid-line. Improve the small model by distillation (Knowledge distillation) from the large one on public and licensed code, never on customer code without opt-in.
Repo context retrieval
Three sources, cheapest first. (1) IDE state: open tabs, recent edits, imports, the cursor's neighborhood. It is free and usually the best signal. (2) A symbol index built with tree-sitter: definitions, references, call graph. It answers "what is the signature of InvoiceRepo.save?" exactly, which embeddings can't. (3) Embeddings of function-level chunks for fuzzy questions ("where do we retry webhooks?"), fused with grep/BM25. Index incrementally: hash files into a Merkle tree, sync only changed subtrees and re-embed only changed chunks. Completion uses (1) plus cheap symbol lookups, since vector search rarely fits its budget; chat and the agent use all three, then rerank (Reranking (cross-encoders)) to fit the window.
Agent loop & sandbox
A tool loop with a small, sharp tool set (Designing tools for agents (ACI)): search, read_file, edit (apply a diff), run (tests, linter, type checker). Each task gets an ephemeral container or microVM (gVisor, Firecracker) with the repo at a commit and dependencies pre-cached, no secrets, egress limited to package registries, and caps (e.g. 50 steps, 30 min). Tests are the verifier: the agent iterates until they pass, and the result is a branch or PR a human reviews; it never pushes to main. Repo text is untrusted input: a README or issue can carry a prompt injection, so the sandbox must hold nothing worth stealing (The lethal trifecta). Cost: 40 steps × ~30k context ≈ 1.2M input tokens, so cache the stable prefix and compact old tool output.
Evaluation
Completion: acceptance rate (shown → accepted), which GitHub's study found the best predictor of perceived productivity, plus retention, the share of accepted characters still present after 30 s and 10 min, because accept-then-delete is a false positive. Watch latency-to-display and the share of requests that show anything. Offline, public sets like HumanEval (Public benchmarks & contamination) are saturated, so build FIM tasks from repos you may use: mask a function body, check it compiles and its tests pass. Agent (Evaluating agents): an internal SWE-bench-style suite of real issues with hidden tests, tracking pass@1 and cost per solved task, run in CI (Evals in CI/CD & release gates) on every model or prompt change. Online, A/B by user, never by request, so nobody flips between models mid-session.
Privacy & deployment
Customer code is the crown jewel. Contractually: no training on it, zero or short retention of prompts (process in memory, keep metadata-only telemetry), encryption in transit and at rest. Technically: per-tenant indexes with tenant_id enforced in the storage layer (Multi-tenant isolation in AI apps); embeddings count as code, since they can be partially inverted back into text. Scan outgoing context for credentials before it leaves the IDE, and honor admin content exclusions (secrets/, licensed code) in the plugin and the indexer. Enterprise tiers add a bring-your-own model endpoint, VPC deployment, or fully on-prem with an open-weights coder model (API vs self-hosting), trading some quality and release speed for code that never leaves the network.