Home / AI Architecture & System Design / AI System Design

AI System DesignSeniorQuestion 16 of 20

Design an inline code-completion assistant like GitHub Copilot.

30-second answer

Latency first: suggestion within ~300 ms p50 and 500 ms p95 of a pause. The client debounces, cancels stale requests, reuses suggestions as the user types through them, and sends prefix, suffix and the most similar snippets from open files, ordered so consecutive prompts share a cacheable prefix. A small fill-in-the-middle code model (3–15B) in nearby regions with session affinity generates short completions, which are trimmed at block boundaries, parsed and filtered (secrets, public-code matches). ~50k requests/s at peak, prefill-dominated, so prefix caching cuts GPUs ~4×. Measure accepted and retained code, not just acceptance.

Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.

New to these terms? 10 terms on this page are explained in the glossary

0–5 min Functional requirements

This is a latency problem first. A suggestion that arrives after the developer has typed the next character is wasted, so every decision is judged by milliseconds.

You Are we designing inline "ghost text" completion as you type, or a chat assistant in the IDE?

Interviewer Inline completion. Single-line and multi-line suggestions at the cursor.

You Which IDEs and languages?

Interviewer VS Code and JetBrains plugins; the top 20 languages.

You How many developers, and is there an enterprise version with private code?

Interviewer About a million active developers, many in enterprises who need their code kept private.

# Functional requirement Why it matters
F1 Suggest a completion at the cursor as the user types, shown as ghost text The core feature
F2 Use surrounding context: code before and after the cursor, open files, imports Relevance is most of the quality
F3 Accept with Tab, partially accept, or dismiss by typing Interaction model
F4 Multi-line suggestions that complete a block (function body, loop) Big productivity wins
F5 Enterprise controls: no code retention, admin policies, filtering suggestions that match public code Required to sell to companies
F6 Telemetry: shown, accepted, still present after 30 s The quality signal for everything else

Out of scope: chat, agent edits across files, code review.

5–10 min Non-functional requirements and estimates

You What should a suggestion's latency be?

Interviewer It should feel instant.

You Then I'll target suggestion shown within 500 ms p95 of the user pausing, and ~300 ms p50. Beyond that, people have typed on.

Requirement Target What it forces
End-to-end latency ≤ 300 ms p50, ≤ 500 ms p95 from pause to ghost text Small model, short outputs, regional serving, cancellation
Quality Acceptance rate as the north star (often ~25–35% of shown suggestions) Context retrieval, evals on real edits
Throughput Bursty: every pause in typing triggers a request Debounce, client cache, cancel stale requests
Privacy Enterprise code not stored or used for training Zero-retention mode; regional processing
Availability 99.9%; failure is silent (no ghost text) Never block the editor
Cost Fraction of a cent per accepted suggestion Prefix caching, small model

Back-of-envelope estimates:

  • Requests: 1M active developers, ~300k typing at peak. After debouncing, an active developer triggers ~1 request every 6 s → ~50,000 requests/s at peak. About half are cancelled because the user keeps typing.
  • Prompt and output: ~2,000 prompt tokens (code before and after the cursor plus snippets from other files); ~25 output tokens on average. Prefill-heavy: 80 prompt tokens for every output token.
  • Prefill compute: completed requests ≈ 25,000/s × 2,000 = 50M tokens/s. A 7B model needs ~1.4e10 FLOPs per token → 7e17 FLOP/s. At ~5e14 useful FLOP/s per H100 that's ~1,400 GPUs with no caching. Consecutive requests from one developer share most of their prefix; with ~75% prefix-cache hits it's ~350 GPUs, plus decode and headroom. This is why session affinity matters so much here.
  • Latency budget (p50):
debounce after last keystroke          75 ms
network to nearest region (RTT)        40 ms
gateway, auth, routing                  5 ms
queue + prefill of ~500 new tokens     40 ms   (1,500 cached)
decode 25 tokens × 6 ms               150 ms
post-processing + render               10 ms
total                                ~320 ms

10–18 min High-level design

You Most of the cleverness is on the client: when to ask, what context to send, and when to reuse a suggestion. The server is a small, fast code model with fill-in-the-middle, served close to users with session affinity.

Scroll sideways to see the whole diagram.

Inline code completion (Copilot-style)Components: Context engine (prefix · suffix · tabs); Open files (+ local symbol index); IDE plugin (debounce · cancel); Regional gateway (session affinity); FIM code model (3–15B · prefix cache); Post-processor (trim · parse · filter); Public-code index (match filter); Telemetry (shown · accepted · kept); A/B + edit benchmark (every model change). Flow: Open files to Context engine; Context engine to IDE plugin; IDE plugin to Regional gateway; Regional gateway to FIM code model; FIM code model to Post-processor; Post-processor to Public-code index; Post-processor to IDE plugin (ghost text); IDE plugin to Telemetry (events); Telemetry to A/B + edit benchmark.Context engineprefix · suffix · tabsOpen files+ local symbol indexIDE plugindebounce · cancelRegional gatewaysession affinityFIM code model3–15B · prefix cachePost-processortrim · parse · filterPublic-code indexmatch filterTelemetryshown · accepted · keptA/B + edit benchmarkevery model changeghost textevents
Inline code completion (Copilot-style). The plugin debounces keystrokes, gathers prefix, suffix and similar snippets from open files, and cancels stale requests. A regional gateway routes by session so the prefix cache hits; a small fill-in-the-middle model generates a short completion that's trimmed, parsed and filtered before it appears as ghost text. Accept and retention events drive A/B tests.

Components:

  • IDE plugin: watches edits, decides when to request (debounce, not mid-word in some cases), gathers context, cancels stale requests, caches suggestions, renders ghost text and reports telemetry.
  • Context engine (in the plugin): builds the prompt: text before the cursor (prefix), after the cursor (suffix), the file path and language, and the most similar snippets from recently opened files. Optionally symbols from a local repo index.
  • Completion gateway (per region): auth, enterprise policy, rate limits, request cancellation, routing by session for cache affinity.
  • Model servers: a small code model (3–15B) trained with fill-in-the-middle, with continuous batching, prefix caching and possibly speculative decoding.
  • Post-processor: trims the suggestion (stop at the end of the block, remove text that duplicates the suffix), checks it parses, and filters secrets and matches against public code when the policy requires.
  • Telemetry pipeline: shown / accepted / retained events, aggregated by model version and language for A/B tests.

API sketch:

POST /v1/completions
{ session_id, request_id, language, path, prefix, suffix, snippets: [{path, text}], max_tokens: 64 }
→ stream: { choices: [{ text, finish_reason }] }
DELETE /v1/completions/{request_id}     (cancel)
POST /v1/telemetry  { request_id, event: shown | accepted | partially_accepted | dismissed | retained_30s }

How it works: a worked example

A study aid: one completion traced from keystroke to ghost text.

The situation. A developer is editing billing/invoice.py. The cursor sits inside a new function:

def total_with_tax(items: list[LineItem], region: str) -> Decimal:
    """Sum line items and apply the regional tax rate."""
    |

tax.py is open in another tab and defines TAX_RATES: dict[str, Decimal].

1. Trigger. The developer presses Enter after the docstring and pauses. The plugin waits 75 ms; no new keystroke arrives, so it requests a completion.

2. Context assembly (~5 ms, on the laptop).

  • Prefix: the 120 lines above the cursor (imports, LineItem dataclass, the signature), about 1,400 tokens.
  • Suffix: the 30 lines below (the next function), about 300 tokens.
  • Snippets: the plugin compares the code near the cursor with sliding windows of recently opened files and picks the most similar ones by token overlap. The TAX_RATES definition from tax.py scores highest, ~150 tokens.

The prompt in fill-in-the-middle format (special tokens vary by model):

<|file|>billing/tax.py
TAX_RATES: dict[str, Decimal] = {"EU": Decimal("0.20"), "US-CA": Decimal("0.0725"), ...}
<|file|>billing/invoice.py
<|prefix|>from decimal import Decimal ... def total_with_tax(items: list[LineItem], region: str) -> Decimal:
    """Sum line items and apply the regional tax rate."""
    <|suffix|>

def format_invoice(...): ...
<|middle|>

3. Server (~285 ms). The gateway routes by session_id to replica code-eu-14, which served this developer's previous request 4 s ago. The first ~1,500 tokens (snippet and the unchanged top of the file) are cached, so prefill covers ~350 tokens: ~30 ms. Decoding produces:

    subtotal = sum(item.price * item.quantity for item in items)
    rate = TAX_RATES.get(region, Decimal("0"))
    return subtotal * (1 + rate)

That's 41 tokens; decoding stops at the blank line before def format_invoice because the model emits its end-of-middle token. ~41 × 6 ms ≈ 250 ms.

4. Post-processing (~3 ms). The text parses as part of the function, doesn't repeat the suffix, contains no secrets, and doesn't match the public-code index. The suggestion is sent back.

5. Display and reuse. Ghost text appears ~410 ms after the pause, above the p50 budget because this is a three-line suggestion; single-line ones finish well inside it. The developer types sub: the plugin sees the typed characters match the start of the suggestion, so it just shortens the ghost text locally. No new request. They press Tab.

6. Telemetry. shown, then accepted (3 lines, 132 characters). 30 s later the plugin checks the region still contains ~the same text and sends retained_30s. That retained-code rate is the metric the team optimizes.

The cancelled case. Had the developer typed ) while the request was in flight, the plugin would cancel it (DELETE), and the gateway would tell the replica to drop the sequence and free its KV blocks. With half of requests cancelled, freeing that GPU work promptly is a real saving.

Where each piece runs:

Component Runs as Example technology If it fails
Plugin + context engine Inside the IDE TypeScript (VS Code), Kotlin (JetBrains) No suggestions; editor unaffected
Gateway Regional stateless service Envoy + auth service Client fails over to next region
Model servers GPU pools per region vLLM/TensorRT-LLM with a FIM code model Shed load: increase debounce, shorten max tokens
Post-processor In the gateway path Tree-sitter parsing, secret regexes, public-code index Skip optional filters per policy, never the enterprise ones
Telemetry Event stream Kafka → warehouse Metrics delayed

18–32 min Deep dive

You I'd go deeper on the client (when to request and what to send), the model and serving setup, and how quality is measured.

Deep dive 1 · Client: triggering, caching and cancellation

  • Debounce: wait ~50–100 ms after a keystroke. Too short floods the servers; too long feels slow. Tune per language from telemetry.
  • Don't request when it's pointless: mid-identifier when the language server already shows completions, inside comments (configurable), right after a closing bracket at the end of a block.
  • Typed-through cache: if what the user types matches the start of the current suggestion, keep showing the remainder. Cache recent suggestions by (file, cursor context) so undo/redo doesn't re-request.
  • Cancellation: every new request cancels the previous one for that editor; the server must actually stop work, not just discard the result.
  • Multiple candidates: request 1 by default; generate 2–3 only when the user explicitly cycles through suggestions.

Deep dive 2 · Context selection

  • Prefix and suffix: the suffix matters a lot for fill-in-the-middle; without it, the model happily writes code that already exists below the cursor.
  • Neighbouring files: open tabs are a strong signal of what's relevant. Score windows of ~60 lines by token overlap (Jaccard) with the code around the cursor and include the best few within a token budget.
  • Repo-level context: a local index of symbols (function signatures, class definitions) lets the plugin include definitions of names used near the cursor. More context costs prefill time, so it's a latency trade-off measured by acceptance rate.
  • Prompt order for caching: put stable content (snippets, top of file) first and the volatile part (lines near the cursor) last, so consecutive requests share the longest prefix.

Deep dive 3 · Model and serving

  • Model size: small enough for ~6 ms per token at moderate batch sizes. Typical choices are 3–15B models trained or fine-tuned with fill-in-the-middle on code.
  • Session affinity: consistent hashing on session_id with bounded load keeps a developer's requests on one replica so the prefix cache hits.
  • Short outputs: cap max_tokens (e.g. 64 for multi-line) and stop at block boundaries; long suggestions are rarely accepted whole.
  • Speculative decoding: code is predictable, so a small draft model (or n-gram lookup from the context) gets high acceptance rates and cuts decode latency.
  • Regions: serve from regions close to users; 100 ms of extra RTT is a third of the budget.
  • Overload: degrade by raising the debounce, lowering max_tokens, or skipping multi-line, rather than letting latency climb past the point where suggestions are useless.

Deep dive 4 · Measuring quality

  • Online: acceptance rate, characters accepted per developer per hour, and retention (accepted code still there after 30 s or 5 min). Acceptance alone rewards short, safe suggestions; retention catches suggestions accepted and then deleted.
  • Offline: a benchmark built from real edits: take a repository at a commit, blank out a span that was later written, and check whether the completion passes the tests or matches. Run every model or context change against it before an A/B test.
  • A/B tests: split by developer, not request, to avoid mixing experiences; watch latency alongside acceptance.

Deep dive 5 · Enterprise privacy and safety

  • Zero retention: prompts and suggestions are processed in memory and not logged; only counts and timings are kept for telemetry.
  • Public-code filter: compare suggestions of ~150+ characters against an index of hashed public code and block or annotate matches with their licence.
  • Secrets: never suggest strings that look like keys; strip them from prompts before sending.
  • Exclusions: admins can exclude paths (e.g. secrets/, generated code) from context.

32–37 min Trade-offs

Decision Chosen Alternative Why
Model size Small FIM code model (3–15B) Frontier model Latency budget; frontier models suit chat and agents, not keystroke-time completion
Context Prefix + suffix + similar snippets from open files Full repo retrieval every request Most of the gain for little latency; repo index added selectively
Routing Session affinity for prefix cache Least-loaded ~4× less prefill compute
Trigger Debounce + client-side reuse Request on every keystroke Halves load with no quality loss
Quality metric Retained code after 30 s Acceptance rate alone Resists gaming by trivially short suggestions
Privacy Zero retention for enterprise Log prompts for debugging Required by customers; debug with synthetic repos

Build first: plugin with debounce and cancellation, prefix/suffix prompts, a FIM model in one region, acceptance telemetry. Then neighbouring-file snippets, session affinity, multiple regions, the offline edit benchmark and enterprise controls.

37–40 min Wrap-up and likely follow-ups

Close with: "A latency-first design: the plugin debounces, cancels and reuses suggestions, and sends prefix, suffix and the most similar snippets from open files, ordered so consecutive prompts share a cacheable prefix. A small fill-in-the-middle model in nearby regions with session affinity answers in ~300 ms. Suggestions are trimmed, parsed and filtered, and retained-code telemetry drives model and context changes."

Likely follow-ups:

  • Next-edit suggestions? Predict the next edit location and change (not just insertion at the cursor) using recent edit history as context; same serving stack, different training data.
  • How would you personalize to a company's codebase? Retrieval from a repo index first; fine-tuning on the company's code (LoRA per tenant) if retrieval isn't enough.
  • On-device? A 1–3B model can run locally for single-line completion; use the server for multi-line.

Further reading

What interviewers listen for

  • A latency budget broken down to milliseconds, including the debounce.
  • Client-side intelligence: cancellation, typed-through reuse, context selection.
  • Fill-in-the-middle and why the suffix matters.
  • Prefill-dominated cost and prefix caching through session affinity.
  • A quality metric beyond raw acceptance.

Red flags

  • Using a large chat model at keystroke time.
  • No cancellation of stale requests.
  • Ignoring the code after the cursor.
  • Measuring success only by request count or acceptance.

Discussion

Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.