AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals
How to design an AI coding agent in real interview order, across three product shapes (inline autocomplete, an interactive agent in the terminal or IDE, and background agents in cloud sandboxes that open pull requests): Tab requests per second, tokens per agent session with and without prompt caching, and containers at peak as the numbers that matter, an API with cancellable autocomplete, text-anchored edits and permission requests, an explainer on where an autocomplete's 300 ms go, the design built in passes, one bug fix walked from keystroke to merged PR, a lab on finding the right code (grep vs an embedding index vs both), a lab on applying edits (whole file, line numbers, search/replace, unified diff, a fast apply model), a lab on sandboxes and warm pools, evals (SWE-bench Verified, Terminal-Bench, pass^k), cost per task, prompt vs train, and what happens when each part fails.
The 1-minute answer
How this page follows the interview
Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.
The generic agent loop (its token cost, durable runs, the lethal trifecta) is Part 28; serving models is Part 22; eval statistics and judges are Part 36. This page is what's specific to coding agents. Designed from public material only: no product's source code and no employer's internal systems.
Requirements and numbers
Agree the three shapes, then size Tab requests per second, tokens per agent session, and containers for background tasks. Change any input: each number comes with the decision it forces.
Functional
- Autocomplete of the next edit as you type (Tab)
- An agent that answers questions about the repo, plans, edits files and runs commands, in the IDE or terminal
- Background agents that take a task, work in the cloud and open a pull request
- Rules per repo (CLAUDE.md, AGENTS.md), permissions per user and org, undo
- Model choice; usage and cost visible per session and team
Non-functional
- Tab: suggestion within ~300 ms of a keystroke, p95
- Agent: first token in ~2–3 s; long sessions affordable (caching)
- Edits apply reliably; failures are loud, not silent
- Commands can't write outside the project or reach unknown hosts; credentials never exposed
- Code stays where policy says: no plaintext code stored server-side for indexing
Out of scope (say it)
Training frontier models, the serving stack (Part 22), the generic agent platform (Part 28), and eval statistics in depth (Part 36).
Capacity calculator
Inputs are round teaching numbers ❓, chosen so Tab lands on Cursor's published 400 M+ requests a day ✅ Cursor Tab RL. Cross-check: Claude Code's docs put the average at ~$13 per developer per active day, under $30 for 90% of users ✅ CC docs.
- Tab is requests × a deadline: volume decides the fleet, the deadline decides the model size.
- Agents resend context: tokens = turns × context per turn; caching reads most of it at 0.1×.
- Containers by Little's law: busy = arrivals per second × seconds per task.
Core entities and the API
Five calls cover the three shapes. What interviewers listen for: autocomplete that cancels, edits anchored on text that fail loudly, permission requests at the boundary, and background tasks that are asynchronous and idempotent.
| Entity | Key fields | Note |
|---|
Where do Tab's 300 milliseconds go?
A suggestion is useful only if it arrives before the next keystroke makes it stale. Add up the round trip, the prefill of whatever isn't cached, and the decode. Pick a setup, or type your own numbers.
What the sources say
- Every action: Cursor's Tab model "runs on every user action, handling over 400 million requests per day". ✅ Cursor Tab RL
- Fewer, better: its online-RL model makes 21% fewer suggestions with a 28% higher accept rate. ✅ Cursor Tab RL
- Fast loop: 1.5–2 hours to roll out a checkpoint and collect the data for the next step. ✅ Cursor Tab RL
- Distance matters: a far region alone can spend the budget, so serve Tab from regions near users. 🔶
Speeds and gaps are rounded teaching values; nobody publishes Tab's latency split ❓. "Stale" assumes keystrokes arrive at random: the chance the next key lands before the reply is 1 − e−time ÷ gap.
High-level design
Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.
Walk one task, box by box
Priya, at a Bengaluru payments company (Kaveri Pay, made up), finds that a refund of ₹10.005 rounds to ₹10.00. She fixes it with the agent in her terminal, hands the other call sites to a background agent, and the fix becomes an eval task. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.
Arrows show who calls whom, and the numbers give the order. Replies go back along the same line. Token counts and times are illustrative.
What keeps it fast and cheap
A 40-turn session resends its whole context every turn. These six details are what keep sessions in seconds per turn and cents per task.
Data and database choices
The code mostly stays where it is. Sessions are append-only logs, checkpoints are content-addressed snapshots of touched files, the index holds embeddings and encrypted paths, and background tasks are rows in a leased queue.
| Data | Pick | Considered | Why not those |
|---|
The one thing to know: the Merkle diff
# Which files changed since the last sync?
# Each node: hash = H(children's hashes).
def changed(local, remote):
if remote and local.hash == remote.hash:
return [] # whole subtree same
if local.is_file:
return [local.path] # re-embed this file
out = []
for name, child in local.children.items():
other = remote.children.get(name) if remote else None
out += changed(child, other)
return out
# deleted files: names in remote, not in localIllustrative. Cursor builds its first view of a codebase with a Merkle tree "which lets it detect exactly which files and directories have changed without reprocessing everything" ✅ Cursor indexing
Why it's built like that
- Equal root, nothing to do: one hash compare per sync when nothing changed. ✅ Cursor indexing
- Walk only changed subtrees: a 400K-file repo with 30 edits re-embeds 30 files. 🔶
- Reuse a teammate's index: a similarity hash of the tree finds a close copy; time to first query fell from 4.03 hours to 21 s at the 99th percentile. ✅ Cursor indexing
- Prove access: results come back only for files whose content hash the client can compute. ✅ Cursor indexing
More database questions
Deep dive: finding the right code
Before it can change anything, the agent has to find the code. Agentic search (grep, glob, read, the way a person would) is exact and never stale, but vague questions in huge repos take many rounds and tokens. An embedding index finds code by meaning in one call, but must be built, synced and secured, and blurs exact names. Repo size, how vague the asks are, and how fast the code changes decide which wins. Pick a preset, then change the numbers.
grep: an exact name is found in one round (97%); a vague ask succeeds per round with chance q ÷ (1 + log₁₀(files ÷ 1,000)) for up to the max rounds; each grep prints ~1% of files as matches (capped at 250 lines) and the agent reads two slices. Index: one query returns 8 chunks; it misses when the file you need changed since the last sync (hot factor × churn × half the sync interval ÷ files). Both: grep first for names, the index first for vague asks, each falling back to the other. The curves keep churn per file fixed as the repo size changes. Every rate is a rounded teaching value 🔶; grep and semantic search together is what Cursor found works best ✅ Cursor semsearch.
The rules this lab teaches
- Start with grep: nothing to build, sync or secure, and never stale. ✅ Cherny 2026
- Add an index for big repos and vague asks: one query instead of six rounds of guessing terms. ✅ Cursor semsearch
- Never edit from the index: it finds the file; the agent reads the live file. 🧭
- Keep reads small: slices and capped output, or the search eats the context. ✅ Context eng.
Real numbers to quote
Claude Code: "Early versions of Claude Code used RAG + a local vector db, but we found pretty quickly that agentic search generally works better" (Boris Cherny, Feb 2026, on X). ✅ Cherny 2026
Cursor (Nov 2025): semantic search gave "on average 12.5% higher accuracy in answering questions"; code retention +2.6% on codebases of 1,000+ files; grep plus semantic search is best. ✅ Cursor semsearch
Anthropic (Sep 2025): just-in-time agents keep "lightweight identifiers (file paths, stored queries, web links, etc.)" and load data at runtime. ✅ Context eng.
Deep dive: applying edits reliably
The model knows what to change; getting that change into the file is its own problem. Rewriting the whole file is slow and gets lazy; line numbers drift; search/replace and diffs anchor on text but fail when the copied text doesn't match; a fast apply model rewrites the file at ~1,000 tokens/s from a sketch. Loud failures cost a retry; silent ones ship bugs. The bars compare all five formats on your numbers; pick a preset, then change them.
Output tokens: whole file = lines × tokens per line; line-number diff = 2 × edit + 2 lines; search/replace = 2 × (edit + 2 × context) + 3 lines; unified diff = 2 × edit + 2 × context + 2 lines; apply = a sketch of edit + 4 lines, then the apply model writes the file. Loud failures are retried (tries = 1 ÷ (1 − p)) and each retry re-reads the file. Failure rates are rounded teaching values 🔶; the ~1,000 tokens/s apply speed is Cursor's ✅ Cursor apply.
Three rules, in order
- Write only the change: the frontier model's output speed is the bottleneck. ✅ Cursor apply
- Anchor on text, never line numbers: "models are notoriously bad at counting line numbers". ✅ Cursor apply
- Make failure loud: an exact match that fails says so; then show the diff and run the tests. 🧭
Numbers to quote
Cursor (May 2024): "~1000 tokens/s (around 3500 char/s) on our 70b model using … speculative edits", "~13x speedup over vanilla inference using Llama-3-70b". ✅ Cursor apply
Aider (Dec 2023): on 89 refactoring tasks GPT-4 Turbo scored 20% with search/replace blocks and 61% with a simplified unified diff: "3X" less lazy. ✅ Aider udiff
Aider's leaderboard reports a "correct edit format" rate per model, next to its score: the format is part of the result. ✅ Aider formats
Deep dive: running code safely, at scale
An agent runs commands it wrote after reading text it didn't (repo files, issues, web pages). Asking permission for each one wears people out; safety has to be enforced by the operating system. Locally that's a sandbox around each command; in the cloud it's a container per task, which turns safety into capacity planning.
Permissions: allow, ask, deny
- Modes: plan (read-only research), default (reads only), accept-edits (file edits and common file commands), and bypass, which Claude Code says to use only in isolated environments like containers and VMs. ✅ CC docs
- Rules by scope: user, project and org-managed rules; "always allow" writes a rule so the same call never asks again. ✅ CC best practices
- Hooks: a PreToolUse hook runs before a tool call and "can block it". ✅ CC docs
- Codex's version: read-only, workspace-write (the default low-friction mode), danger-full-access; approvals on-request or never. ✅ Codex docs
Isolation: files, network, secrets
- Files: read and write in the working directory; "blocking the modification of any files outside of it". ✅ CC sandboxing
- Network: only through "a unix domain socket connected to a proxy server running outside the sandbox"; allowed domains start empty. ✅ CC sandboxing
- OS primitives: bubblewrap on Linux, Seatbelt on macOS; result: 84% fewer permission prompts internally. ✅ CC sandboxing
- Secrets outside: git credentials never in the sandbox; a git proxy checks the push and attaches the token. ✅ CC sandboxing
- Cloud tasks: Codex disables internet during the task after setup (configurable since June 2025); Cursor's cloud agents run in isolated VMs with network access. ✅ Codex launch
How many containers, and how many warm?
Busy containers follow Little's law. Warm spares are a separate question: every task takes a ready container and a replacement starts booting, so the pool only has to cover the boots in flight, which a cached image makes short. Pick a preset, then change the numbers.
Base-stock model: boots in flight N ~ Poisson(arrivals × boot time); a task waits when N ≥ spares; average wait = E[(N − spares)⁺] ÷ arrivals (Little's law); idle spares = E[(spares − N)⁺]. Busy = arrivals × task time. A cached image boots in boot + 5 s; otherwise boot + clone + install. Prices and times are teaching values ❓; Codex tasks take 1–30 minutes ✅ Codex launch.
Prompt injection through the repo
- Untrusted input everywhere: READMEs, issues, comments, test output and web pages all reach the model. ✅ CC sandboxing
- Break the trifecta: private data + untrusted content + a way out; the egress allow-list removes the way out (Part 28). 🧭
- Deny rules for secrets: no reads of .env or key files, whatever the prompt says. 🧭
- Review before merge: a person reads every agent PR; CI runs again outside the sandbox. 🧭
Undo: checkpoints and git
- Checkpoints: code captured "before each prompt"; rewind restores code, conversation or both. ✅ CC docs
- Their limit: "A file that only Bash commands changed isn't tracked"; "Not a replacement for version control". ✅ CC docs
- Git is the real undo: agent work on a branch, small commits; background agents only ever push branches. ✅ Cursor cloud
- Outside effects can't be undone: a migration or a deploy needs a person's approval, not a checkpoint. 🧭
Evals, cost per task, and prompt vs train
A coding agent is a model, a prompt, a set of tools and a harness, and a change to any of them can make it worse. Gate every change on your own tasks, run several times each, and watch what each task costs.
The release ladder for a model, prompt or tool change
pass@k vs pass^k
pass@k = 1 − (1 − p)k: a user who can pick the best of k. pass^k = pk: an agent that must work every time ✅ τ-bench. Assumes tries are independent 🔶.
Benchmarks: useful, with limits
What does one task cost?
Every turn resends everything so far: input = n·S + a·n(n−1)/2 (Part 28 derives it). Cache multipliers are Anthropic's standard rates for a 5-minute cache ✅ Claude caching; prices are teaching values ❓.
Prompt a frontier model, or train your own?
Tick what's true for this step.
Cost and latency per task
- Cache the prefix: stable content first; 1-hour TTL at 2× write price for long gaps between turns. ✅ Claude caching
- Route by step: frontier for planning and edits, small models for summaries, titles and search. 🧭
- Subagents: exploration costs tokens there, not in the main context. ✅ Context eng.
- Compaction: summarise near the limit instead of resending 150K tokens a turn. ✅ Context eng.
- Your own fast models: Cursor trains Tab, apply and Composer, which it pitches as four times faster than similar models. ✅ Cursor Composer
Safe rollouts and guardrails
- Pin model versions: a provider's update is a new candidate. 🧭
- Graders the agent can't edit: hidden tests; flag diffs that touch tests. 🔶
- Evidence in every PR: Codex cites terminal logs and test outputs so reviewers can check. ✅ Codex launch
- Budgets: turn, token and time limits per task; a stop after repeated identical failures. 🧭
A task's lifecycle
A background task (and, more loosely, an interactive one) moves from queued to merged. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.
Edge cases interviewers love
Failure, monitoring and recovery
A coding agent fails loudly (a provider is down, the pool is empty) and quietly (cache misses that double the bill, edits that apply wrongly, a model that's worse on your repos). Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.
Tracing it back: a good session vs a bad one
Every span carries the session, turn and versions. Times are from the user's message; illustrative. In the bad session a timestamp at the top of the prompt breaks the cache, grep prints the whole repo, an edit misses its anchor, and a prompt waits for a user who's gone for coffee.
How one failure becomes three
What you'd alert on (SLOs)
| Signal | Target | Alert |
|---|
Incident playbook
The toolkit
Name the technique, then say where it goes in this design.
Making it fast, and who owns what
Tab lives in milliseconds, agent turns in seconds, background tasks in minutes and reviews in hours. Spend engineering where the user waits, and remember review is the real bottleneck. Bars are sizing estimates, not measured figures.
| Team | Owns | Paged when… |
|---|
Senior follow-ups beyond the happy path
Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.
Practice ladder
Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.
Sources
- Claude Code: Best practices for agentic coding, Anthropic (18 Apr 2025; now part of the Claude Code docs)
- Making Claude Code safer with sandboxing, Anthropic (20 Oct 2025)
- Effective context engineering for AI agents, Anthropic (29 Sep 2025)
- Building effective agents, Anthropic (19 Dec 2024)
- Claude Code docs: permission modes, checkpointing, hooks, sandboxing, costs (checked Nov 2026)
- Prompt caching, Claude API docs (checked Nov 2026)
- Boris Cherny on agentic search vs RAG in Claude Code, post on X (1 Feb 2026)
- Improving Cursor Tab with online RL, Cursor (12 Sep 2025)
- Editing files at 1000 tokens per second, Cursor (14 May 2024)
- Improving agent with semantic search, Cursor (6 Nov 2025)
- Securely indexing large codebases, Cursor (27 Jan 2026)
- Composer: building a fast frontier model with RL, Cursor (29 Oct 2025)
- Cloud agents, Cursor docs (checked Nov 2026)
- Introducing Codex, OpenAI (16 May 2025, updated 3 Jun 2025)
- Sandboxing, Codex docs (checked Nov 2026)
- SWE-bench: Can language models resolve real-world GitHub issues?, Jimenez et al. (Oct 2023)
- Introducing SWE-bench Verified, OpenAI (13 Aug 2024)
- Terminal-Bench 2.0 paper (17 Jan 2026)
- τ-bench, Yao et al. (17 Jun 2024)
- Edit formats, Aider docs (checked Nov 2026)
- Unified diffs make GPT-4 Turbo 3X less lazy, Aider (21 Dec 2023)
Checked 11 November 2026. Claude Code: Anthropic's best-practices post (18 Apr 2025, now part of the docs), 'Making Claude Code safer with sandboxing' (20 Oct 2025: filesystem and network isolation, bubblewrap and Seatbelt, 84% fewer permission prompts, the git proxy), 'Effective context engineering for AI agents' (29 Sep 2025: just-in-time context, compaction, subagents returning 1,000–2,000 tokens), 'Building effective agents' (19 Dec 2024), and the Claude Code docs on permission modes, checkpointing, hooks, sandboxing and costs (undated live docs, checked Nov 2026). Boris Cherny's note on dropping RAG for agentic search is a post on X (1 Feb 2026), labelled as such. Prompt caching multipliers are from Anthropic's prompt-caching docs (0.1× reads on most models; 1-hour TTL at 2×). Cursor: the Tab online-RL post (12 Sep 2025), instant apply (14 May 2024), semantic search (6 Nov 2025), secure codebase indexing (27 Jan 2026), Composer (29 Oct 2025) and the cloud-agents docs. OpenAI: 'Introducing Codex' (16 May 2025, updated 3 Jun 2025) and the Codex sandboxing docs. Benchmarks: SWE-bench (Oct 2023), SWE-bench Verified (13 Aug 2024), the Terminal-Bench 2.0 paper (17 Jan 2026), τ-bench (17 Jun 2024), Aider's edit-format docs and unified-diff post (21 Dec 2023). Leaderboard scores move weekly, so none is quoted as current. The labs use rounded teaching values and simple models (Little's law, a base-stock pool, geometric search rounds) and say so. Nothing here comes from any product's source code or any employer's internal systems.
System Design Mastermind · AI / ML systems
Series homeAll of AI / ML systems
8 published · 1 comingLLM and ML systems, where interviews are heading.
LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes
Chat API (auth, token limits, history, safety, SSE with resumable event ids) → router picks model (easy turns to a small one), version (registry canary split) and a replica with the prefix cached → vLLM-style engines batch continuously up to the time-per-token target. Admit by priority because GPUs take minutes to add; ship every model change through evals, shadow and canary, with rollback by one number.
RAG assistant over company docs system design: retrieval, permissions and answers you can trust
Ingestion (change events + full sync → parse → chunk with a context line → embed only changed chunks) fills a versioned index of keywords, vectors and allowed principals. Serving rewrites the question, runs hybrid search with the permission filter inside it, reranks 150 → 8, answers only from numbered sources, checks grounding and re-checks cited docs. A golden set gates every change.
AI agent platform system design: tools, durable runs, approvals and agents you can trust
A durable orchestrator runs each agent as workflow code: pin the version, call the model through a caching gateway, record every step so crashes resume. The model only proposes tool calls; a tool gateway validates, authorizes with the user's own token, adds idempotency keys and parks irreversible steps for approval. Budgets stop runaways; end-state evals with k tries gate every release.
Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish
Validate the file, split it into ~20-minute shards, lease them to GPU workers on spot that load the model once and run hundreds of rows at a time with the shared prompt cached. Each attempt writes its own file; one conditional commit per shard makes output exactly-once. Golden set and canary shard gate every new version.
Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a day
Hash at upload against known-bad lists, score every policy with small classifiers in ~50 ms, two lines per policy: remove above, allow below, and the band between goes to an LLM that reads the policy, then a review queue ordered by severity × reach × likelihood. Every decision logged with a reason, appealable, and gated by golden set → shadow → canary.
Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests
Several sources (two-tower ANN search, like-your-likes, trending, a fresh pool) retrieve a few thousand items; a light ranker keeps a few hundred; a heavy multi-task ranker predicts finish, like, share and skip; a value model and re-rank add diversity, in ~200 ms. Events stream back to features in seconds and to incremental training in minutes; models ship via interleaving and A/B tests.
LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rollouts
Every product calls an AI gateway: versioned config, input guards (PII mask, a small injection classifier, an LLM judge only when unsure), output guards on streamed chunks, a trace per request. Off the path: sampled traces judged online, people calibrating the judges, failures turned into regression tests, and every change gated by a paired eval with error bars, then shadow, canary and A/B.
AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals
Three shapes, one backend: a small self-served Tab model per keystroke; an agent loop with a context engine (grep plus an optional index), a cached prompt to a frontier model, text-anchored edits or a fast apply model, permissions and an OS sandbox; and background agents in a container per task that open a PR. An eval harness gates every change on pass^k.