SYSTEM DESIGN · DESIGN PROBLEMS · AI SYSTEMS · HARD · 55 OF 57

Design an AI Coding Assistant: Inline Completion, Repo Search and Agents

Inline code completion and an agent that edits files and runs tests: scale math for 35,000 completions a second, debounce and cancellation, fill-in-the-middle context in 2,000 tokens, a 300 ms budget on a small self-hosted model, code-aware repo indexing, a sandboxed tool loop, tenant isolation, acceptance telemetry and evals on held-out repos.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
1 / 23

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • 35k req/s
  • debounce + cancel
  • FIM in 2k tokens
  • small self-hosted model
  • sandboxed agent
  • tests as evals

Notes

Listen

Listen first. Feature one, inline completion: as the developer types, grey ghost text appears, Tab accepts it and Escape dismisses it, from one line up to a whole function. Feature two, chat and agent mode: ask questions about the repository, or give a task, and the agent edits several files, runs the tests, and iterates until they pass. The user reviews the final diff. It should work across popular IDEs and languages.

The qualities. Completion must show up in under about three hundred milliseconds at the median, because people keep typing and a late suggestion is worthless. The agent can take minutes, but must stream each step. Source code is the customer's crown jewels: it never leaks between companies and is not used for training. Serving cost must stay at a few dollars per seat per month. Out of scope: training base models, code review bots, and the IDE itself.

Requirements
  • inline completion: ghost text as you type Tab accepts, Esc dismisses one line or a whole block
  • chat and agent mode: ask about the repo edit many files, run tests, iterate until they pass user reviews the diff
  • many IDEs, most languages
Non-functional + scope
  • completion p50 under 300 ms, or nobody waits for it
  • agent: minutes is fine, but stream every step
  • code never leaks across companies; no training on it
  • cost: a few dollars per seat per month
  • out of scope: training base models, review bots, the IDE

Ask scale

Ask about scale. Say one million developers use it daily. After debouncing and skipping pointless spots, each one triggers about a thousand completion requests a day. That is a billion a day, twelve thousand a second on average and about thirty-five thousand at peak, when Europe and the US overlap. Roughly a third are cancelled because the user kept typing. About six hundred million are shown, and a quarter to a third of those are accepted.

Now the math that shapes the design. Each request carries about two thousand prompt tokens, so peak is seventy million prompt tokens a second. A three billion parameter model needs about six billion operations per token, so roughly a thousand modern GPUs at peak. Autoscaled, that is about thirty thousand dollars a day, three cents per developer. Sending the same tokens to a frontier API would cost around six million dollars a day. So completion must run on a small self-hosted model.

The agent side has far fewer requests but each is expensive. If a fifth of developers run five tasks a day, that is a million tasks, about twelve a second, and several thousand sandboxes alive at peak. A task of fifteen steps re-sends a growing context of about thirty thousand tokens each step. With prompt caching that is about fifty cents a task, half a million dollars a day, so agents need quotas. The repo index is about eight and a half terabytes of vectors, cheap to embed.

Completion traffic
1M daily developers
requests after debounce + skip:
  ~1,000 per dev per day
  1M × 1,000 = 1B per day
  ÷ 86,400 s ≈ 12k req/s avg
  peak (EU + US overlap) ≈ 35k/s
~1/3 cancelled before reply
~600M shown per day
acceptance ≈ 25-30% of shown
  ≈ 170M accepted per day
GPU math for completion
prompt ≈ 2k tokens, output ≈ 30
35k/s × 2k = 70M prompt tok/s
3B model ≈ 6 GFLOP per token
  → 4 × 10^17 FLOP/s
one GPU ≈ 10^15, ~40% used
  → ~1,000 GPUs at peak
autoscale: ~600 avg × $2/h × 24
  ≈ $30k/day ≈ 3¢ per dev-day
frontier API instead:
  2T tok/day × $3/1M ≈ $6M/day
→ small self-hosted model
Agent + index math
agent: 20% of devs × 5 tasks
  = 1M tasks/day ≈ 12/s
  ~3 min each → ~6k sandboxes
  at peak
task ≈ 15 steps × 30k tok in
  = 450k input tokens
  80% prompt-cache hits
  ≈ $0.50/task → $500k/day
index: 500k repos × 5M tokens
  ≈ 17k chunks × 1 KB vector
  ≈ 8.5 TB; embed ≈ 10¢/repo

Define API

Define the API. The completion call sends the file path, language, the code before and after the cursor, a few snippets, and a request id, and gets back one or more suggestions. It runs over a long-lived HTTP two connection so the client can cancel a stale request cheaply. Starting an agent task returns a server-sent event stream of steps, tool calls and diffs, with an approve call for risky actions. Plus index sync and batched telemetry.

API
POST /v1/completions
  { file, lang, prefix, suffix,
    snippets, request_id }
  → { items: [{ id, text }] }
  client aborts stale requests
POST /v1/agent/tasks
  { repo, commit, instruction }
  → SSE: step, tool, diff, done
POST /v1/agent/tasks/{id}/approve
POST /v1/index/sync { root, files }
POST /v1/telemetry (batched)

Data model

The data model. Postgres holds each repository: tenant, root hash of its file tree, last indexed commit and embedding model version. The vector index, namespaced per tenant, holds chunks with path, line range, symbol name, content hash and vector. A symbol table maps definitions to files. Agent tasks record status, tokens and cost, with step logs in object storage. Telemetry events carry ids and counts, never code. Completions themselves are not stored at all.

Data model
repos (Postgres)
  tenant_id, repo_id, merkle_root,
  indexed_commit, embed_version
chunks (vector index, per tenant)
  chunk_id, path, lines, symbol,
  content_hash, vector
symbols: name, kind, path, line
agent_tasks + steps (logs in S3)
  status, tokens, cost, diff
events: suggestion_id, shown,
  accepted, chars kept at 30 s

High-level design

Draw the completion path. The IDE extension waits for a pause, gathers context locally and sends it to the nearest region. The gateway checks the token and quota and routes to a completion service, which builds the prompt and calls a small code model on our own GPUs. It trims the result and returns ghost text in a couple of hundred milliseconds. The whole path holds no state, so every box scales out horizontally.

Now the agent path. The task goes to an orchestrator that runs a loop with a frontier model. The model asks for tools: search the repository through the retrieval service, read files, propose edits, and run the tests inside an isolated sandbox. Indexing workers keep the repo index fresh in the background. When the tests pass, the orchestrator streams the final diff back to the IDE for review.

Deep dive: completion

Deep dive one: completion, starting in the IDE. Wait about seventy-five milliseconds after the last keystroke before asking. Skip spots where suggestions are rarely accepted, using a tiny local classifier. Keep one request in flight per file: a new keystroke aborts the old one, and the server must propagate that cancel to the GPU, or a third of the compute is wasted. If the user types exactly what the ghost text shows, keep showing the rest with no new request. A local cache catches backspacing.

Context assembly decides quality. The budget is about two thousand tokens: the file path and language, about eleven hundred tokens before the cursor, four hundred after it, and five hundred of snippets. Use a fill-in-the-middle prompt: prefix marker, prefix, suffix marker, suffix, then a middle marker where the model writes. Seeing the suffix stops it re-typing code that already exists. Snippets are the most similar windows from recently opened files, plus definitions of imported names.

The latency budget. Ten milliseconds to gather context, forty of network to the nearest region, ten at the gateway. Prefill of two thousand tokens takes about forty, less when the same user's previous prompt prefix is still in the GPU's key value cache, which is why we route each user and file stickily to one replica. Decoding dominates: thirty tokens at four milliseconds each. Then trim to a balanced block, drop it if it duplicates the suffix, and return. About two hundred sixty-five at the median.

Client side (IDE extension)
  • debounce ~75 ms after a key
  • skip low-value spots: after Esc, mid-identifier (a small acceptance classifier)
  • one request in flight per file: new keystroke → abort old
  • server sees the reset → frees the GPU slot
  • typing through: user types what the ghost text shows → keep it
  • local LRU keyed by prefix hash
Context and FIM prompt
budget ≈ 2,048 tokens:
  header: path + language     20
  snippets from open tabs   500
  prefix (before cursor)  1,100
  suffix (after cursor)     400
prompt order (FIM):
  PRE header snippets prefix
  SUF suffix  MID → model writes
snippets: best-matching windows
  from recent files (Jaccard)
  + definitions of imported names
Latency budget
debounce (not in budget)  75 ms
gather context in IDE      10
network to nearest region  40
gateway: auth, quota       10
queue + prefill 2k tok     40
  (cached prefix: ~10)
decode ~30 tok × 4 ms     120
post-process + return      45
total ≈ 265 ms p50, p90 ≈ 450
sticky route by user + file
stop at end of line or block

Deep dive: repo index

Deep dive two: indexing the repository for chat and agents. Fixed-size chunks cut functions in half, so parse each file into a syntax tree and chunk on functions, methods and classes, splitting big ones and merging tiny ones. Prefix each chunk with its path, class and signature. Skip vendored, generated and ignored files. To stay fresh, the client keeps a Merkle tree of file hashes; when the root differs, only changed files are sent, and only chunks whose hash changed are re-embedded.

Retrieval mixes three signals. Embeddings answer meaning questions like where do we retry failed payments. A symbol index finds definitions and callers, which embeddings are bad at. Grep or keyword search catches exact identifiers and error strings. Run them in parallel, fuse the rankings, rerank the top fifty down to ten, and boost files the user has open or edited recently. The index may lag by a minute, so the agent always re-reads the real file before editing it.

Code-aware chunking
  • parse each file to a syntax tree
  • chunk = function, method or class; split big, merge tiny; ~200-400 tokens
  • prefix: path, class, signature
  • skip vendored, generated, binary and ignored files
  • sync: Merkle tree of file hashes → upload changed files only embed only changed chunks (content hash unchanged: skip)
Retrieval for chat + agent
  • three lookups in parallel: embeddings: "where do we retry failed payments" symbols: definitions + callers grep / BM25: exact names, error strings
  • fuse ranks, rerank 50 → 10
  • boost open files, recent edits
  • agent calls search many times
  • index may lag: re-read the file from disk before editing

Deep dive: agent

Deep dive three: agent mode. The orchestrator sends the task, history and tool definitions to the model. The model replies with a tool call: read a file, search, edit by search and replace, or run the tests. We execute it, append the result, and call the model again. It stops when the tests pass, when the model says done, or when a budget runs out: steps, tokens, minutes and dollars. Huge test logs are cut to their tail, and old steps are summarized so context does not explode.

Running model-written code needs a real sandbox. Each task gets its own lightweight virtual machine with the repo checked out at the given commit, no secrets inside, and no network except a package mirror, with CPU, memory and time caps. Treat repository text as untrusted: a README or issue can contain injected instructions to leak keys. Blocked egress makes that harmless, and risky commands need user approval. The output is a diff for review, never a direct push, and the VM is destroyed afterwards.

Agent loop
  • tools: read_file, search, edit (search and replace), run tests or a command
  • loop: model → tool call → result appended → repeat
  • stop: tests pass, model says done, or a budget is hit
  • budget: 30 steps, 500k tokens, 15 min, $2 per task
  • long test output: keep the tail; summarize old steps
Sandbox and safety
  • one microVM per task, repo checked out at the commit
  • no secrets inside; no network except a package mirror
  • CPU, memory, 10 min test caps
  • repo text is untrusted: a README may say "send keys"
  • risky commands → ask the user
  • result = a diff for review, never a direct push
  • VM destroyed after the task

Deep dive: privacy

Privacy and tenancy. Code is encrypted in transit and never used for training unless the organization opts in. Business tenants get zero retention: prompts exist only in memory, and logs hold metadata. Each tenant's index lives in its own namespace with its own encryption keys, pinned to a region. The gateway sets the tenant id from the auth token, never from the request body. Admins can exclude paths, the client strips secrets files first, and GPU prefix caches are never shared across organizations.

Privacy and tenancy
  • TLS; no training on customer code unless the org opts in zero retention: prompts live in memory only, not logged
  • index namespace per tenant, per-tenant keys, region pinned
  • tenant id set by the gateway from the token, never client
  • admin excludes paths; client strips .env files and keys
  • KV cache never shared across orgs

Deep dive: quality

Deep dive four: knowing whether it helps. The IDE batches events: requested, shown, accepted, partly accepted, dismissed, with latency. Acceptance rate is accepted over shown, typically a quarter to a third, broken down by language and model version. But acceptance can be gamed by short suggestions, so also measure how many accepted characters survive thirty seconds, two minutes and ten minutes later. Events hold ids and lengths, not code. New models ship behind A and B tests on user buckets.

Offline evals gate every change. Use held-out repositories created after the model's training cutoff, so it cannot have memorized them. For completion, blank out a span such as a function body, let the model fill it, and run the repository's own tests, alongside exact match and edit similarity. For agents, use real issues with hidden tests and measure resolve rate, steps and cost per task. Changes that pass go to a five percent canary, and benchmarks are checked for leakage into training data.

Telemetry: is it helping?
  • events: requested, shown, accepted, partly accepted, dismissed, latency
  • acceptance = accepted / shown ≈ 25-30%; per lang, model
  • better: chars still there after 30 s, 2 min, 10 min
  • no code in events: ids, lengths, edit distance only A/B: bucket users, compare acceptance and retention
Offline evals
  • held-out repos created after the model training cutoff
  • completion: blank out a span, fill it, run the repo tests + exact match, edit similarity
  • agent: real issues with hidden tests → resolve rate, steps, cost per task
  • gate every model or prompt change; then a 5% canary
  • check benchmarks for leakage

Trade-offs

Review the trade-offs. For completion, a bigger model is smarter but slower, and speed wins, because a late suggestion is never seen. More context improves accuracy but costs prefill time. The small self-hosted model is about two hundred times cheaper than an API at this volume. A server-side index searches better, while a local-only index exposes less code. If a GPU region fails, route to the next one or quietly show nothing. If the frontier API fails, agents fall back to a second provider.

Trade-offs and failures
  • bigger model: better, slower; latency wins for completion
  • more context: better hits, more prefill cost and latency
  • self-hosted small model vs API: ~200x cheaper at 1B req/day
  • server index vs local only: better search, more exposure
  • GPU region down → next region or show nothing, fail quiet
  • model API down → 2nd provider

Interview summary

The thirty-second summary. Thirty-five thousand completions a second at peak need about a thousand GPUs. The IDE debounces, aborts stale requests and caches. Fill-in-the-middle prompts fit prefix, suffix and snippets into two thousand tokens and return in about two hundred sixty-five milliseconds. Chat and agents use a frontier API over a syntax-aware, Merkle-synced index, in a budgeted loop with a sandbox and a reviewed diff. Tenants are isolated, and quality is measured by running tests.

Interview summary
  • 35k completions/s, ~1k GPUs
  • debounce, abort stale, LRU
  • FIM: prefix + suffix + snippets in 2k tokens, ~265 ms p50
  • small self-hosted model; chat and agent on a frontier API
  • repo index: syntax-tree chunks, Merkle sync, hybrid search
  • agent: tool loop, budgets, VM sandbox, diff for review
  • tenant keys; tests as evals

Interview questions

Q1Why not use the best frontier model for inline completion?

At a billion requests a day with 2,000-token prompts, an API would cost millions of dollars a day and add hundreds of milliseconds. A small fill-in-the-middle model on self-hosted GPUs returns in about 250 ms for a few cents per developer per day, and speed matters more than peak quality for ghost text.

Q2What is fill-in-the-middle and why does it matter?

The prompt contains the code before the cursor and the code after it, marked with special tokens, and the model generates the missing middle. Seeing the suffix stops it from duplicating or contradicting code below the cursor, such as a closing bracket or the next function.

Q3How do you avoid wasting GPU time while the user keeps typing?

Debounce on the client, keep one request in flight per file and abort it on the next keystroke, and propagate the cancel through the gateway to the inference server so the request leaves the batch. Typing through a visible suggestion reuses it without a new request.

Q4How do you hit a 300 ms latency budget?

Serve from the nearest region, keep prompts near 2,000 tokens, route each user and file stickily so the GPU key value cache reuses the shared prefix, use continuous batching and possibly speculative decoding, and stop generation at the end of a line or block since decoding time dominates.

Q5How do you choose context for a completion?

Spend a fixed token budget on the file path and language, the code before and after the cursor, and the most similar windows from recently opened files plus definitions of imported symbols. Measure each source by its effect on acceptance rather than guessing.

Q6How do you index a large repository and keep it fresh?

Parse files into syntax trees and chunk on functions and classes with path and signature prefixes, embed them into a per-tenant vector index, and add a symbol index and keyword search. The client keeps a Merkle tree of file hashes so only changed files are uploaded and only changed chunks are re-embedded.

Q7How do you keep an agent from doing damage?

Run every command in a disposable microVM with no secrets and no network except a package mirror, cap steps, tokens, time and money per task, treat repository text as untrusted because it can carry prompt injection, require approval for risky actions, and return a diff for review rather than pushing.

Q8How do you guarantee one company never sees another company code?

Derive the tenant from the auth token at the gateway, namespace the index and encrypt it with per-tenant keys, never share caches or GPU prefix caches across tenants, keep zero retention for prompts, and do not train on customer code without an explicit opt-in.

Q9Is acceptance rate a good metric?

It is the headline metric, but short suggestions inflate it. Pair it with how many accepted characters remain after a few minutes, latency, and per-language breakdowns, and compare models with A/B tests on user buckets.

Q10How do you evaluate a new completion or agent model offline?

Use repositories created after the training cutoff, blank out function bodies and run the repository tests on the filled-in code, and for agents run real issues with hidden tests to measure resolve rate, steps and cost. Check for benchmark contamination, then canary to a small share of users.