All posts
System Design Mastermind · Part 28
  • System design
  • Interview prep
  • AI agents
  • AI/ML systems
  • Durable execution

AI agent platform system design: tools, durable runs, approvals and agents you can trust

How to design a platform that runs many teams' tool-using AI agents, in real interview order: tokens per run, concurrency and cost as the numbers that matter, an API with 202 run ids, approvals for exact arguments and versioned tools, an explainer on what tool definitions cost, a durable orchestrator, tool gateway, user-scoped credentials, approvals and a sandbox built in passes, one refund run walked end to end through a crash and an injected instruction, a lab on the loop's tokens, time and reliability, a lab on crashes, idempotency keys and parked runs, evals with end states and pass^k, LLM judges, rollouts, the lethal trifecta, prompt vs tools vs fine-tune, and what happens when each part fails.

25 Oct 2026 · 35 min read · interactive

Share

The 1-minute answer

An agent is a model calling tools in a loop; the platform is everything that makes that loop safe, durable and affordable for many teams. A client starts a run and gets a run id at once (202), then follows its events. A durable orchestrator runs the loop as workflow code: it pins the agent's version (prompt, model, tools, budgets), calls the model through an LLM gateway that keeps the system prompt and tool definitions as a cached prefix, and records every step as an event so a crash or deploy resumes from the last finished step. The model only proposes tool calls; a tool gateway validates them against versioned schemas, checks the user's permission and the tool's policy (allow, ask a person, deny), attaches the user's own narrow OAuth token, and sends an idempotency key (run + step) with every side effect. Irreversible steps park the run until a person approves the exact arguments. Code runs in a sandbox with no secrets. Budgets (steps, tokens, dollars, time) and loop detection stop runaways. Every release is gated by task suites scored on end states, several tries each, then canaried, and tool results are treated as untrusted input.

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.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

New to tool calling, tokens and prompt caching? Foundations F18 (AI foundations: inference, RAG and agents) explains them. Serving the model is Part 22; retrieval is Part 25. Here, both are just things the agent calls. Designed from public material only.

Requirements and numbers

Agree what the agents do, how long runs last and whose permissions they use, then size tokens per run, concurrency and cost. Runs per second is small; everything else isn't. Change any input: each number comes with the decision it forces.

Functional

  • Teams register agents: prompt, model, tools, budgets, approval rules
  • Start a run from chat, Slack, an API or a schedule; follow its steps live
  • Agents call tools (internal APIs, MCP servers, a code sandbox) as the user
  • A person approves irreversible steps; can answer, cancel, or take over
  • Every run's steps, tokens and cost are visible and auditable

Non-functional

  • No side effect happens twice, whatever crashes
  • An agent can never do more than its user could
  • A cost cap per run and per tenant, enforced mid-run
  • First event within 1 s; runs survive deploys
  • New agent versions measured before they reach users

Out of scope (say it)

Training models, serving the LLM (Part 22), retrieval internals (Part 25), browser automation, multi-agent research systems in depth.

Capacity calculator

Every input is an assumption 🔶: say it out loud. Prices are round teaching numbers for a mid-sized hosted model; check your provider. Cache reads at 10% and writes at 125% of the input price are Anthropic's prompt-caching prices. ✅ Anthropic 2024

Three rules for this estimate
  1. A day is 86,400 seconds, and runs bunch into working hours: use a peak factor of 2–4.
  2. Concurrency = arrival rate × time in the system (Little's law), for working runs and for waiting ones separately.
  3. Every call re-sends the history: input per run = n × (prompt + tools) + added × n(n − 1) ÷ 2.
They'll push on thisAnswer out loud, then open.

Core entities and the API

A run is the unit of work; an event is the unit of durability; a tool version is the unit of trust. What they listen for: 202 and a run id, an idempotency key, approvals for exact arguments, and the model only proposing.

EntityKey fieldsNote
Request
Response

Tool definitions are paid for on every call

The model only knows a tool from its definition: name, description, JSON schema, examples. Every definition goes into every model call of every run. Change the numbers and see what loading tools on demand saves.

Why it matters

  • Real numbers: 58 tools across five MCP servers took ~55K tokens before the conversation began; Anthropic has seen 134K. ✅ Anthropic Nov 2025
  • On demand: a search tool cut that by 85%, and raised Opus 4's MCP eval accuracy from 49% to 74%. ✅ Anthropic Nov 2025
  • Too many tools confuse: Shopify saw boundaries blur past ~20 tools and the agent struggle past 50. ✅ Shopify Aug 2025
  • Caching helps the bill, not the window: cached definitions are cheap but still fill context and attention. 🔶

950 tokens per tool is 55K ÷ 58, Anthropic's example rounded. The search tool's own definition is a 500-token teaching guess. ❓

They'll push on thisAnswer out loud, then open.

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.

They'll push on thisAnswer out loud, then open.

Walk one run, box by box

A support agent refunds a broken order: tools, an approval, a crash in the middle, then an injected instruction and a new version. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.

On the wire

Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.

What makes the loop production-ready

A demo agent is a while-loop. These six details are what separates it from a platform.

    Data and database choices

    The event history is the run: everything else (the prompt, the current step, the cost) can be rebuilt from it. Big results live beside it by reference; credentials never touch it.

    DataPickConsideredWhy not those

    The one thing to know: the loop as workflow code

    # One agent run as durable workflow code.
    # Illustrative; names are made up.
    def run_agent(run):                          # deterministic
        agent = registry.pin(run.agent)          # version fixed
        msgs = [system(agent), task(run.input)]
        for step in range(agent.max_steps):
            check_budgets(run)                   # $, tokens, time
            reply = activity(llm.call, agent, msgs)   # recorded
            if reply.is_final:
                return finish(run, reply)
            for call in reply.tool_calls:        # parallel if independent
                decision = policy(call, run.user)     # allow / ask / deny
                if decision == ASK:
                    wait_for_signal(approval(call), timeout=24*h)
                key = f"{run.id}:{step}:{call.id}"
                result = activity(tools.call, call, key)  # retried, same key
                msgs.append(tool_result(call, trim(result)))
            msgs = compact_if_needed(msgs)
        return stop(run, "step budget")

    Illustrative. Model and tool calls are recorded activities; the loop itself is deterministic so it can be replayed. 🧭

    Why the split matters

    1. Workflow code is deterministic; activities (model calls, tool calls) do the I/O and are recorded. ✅ Pydantic AI docs
    2. On a crash, replay uses the recorded results instead of calling the model again, so the run reaches the same point. ✅ Pydantic AI docs
    3. A failed activity restarts from its beginning, so its side effects must be idempotent. ✅ Pydantic AI docs
    4. Payloads are capped (2 MB by default in Temporal): big tool results go to object storage. ✅ Pydantic AI docs

    More database questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: the loop's tokens, time and reliability

    Every step re-sends the system prompt, the tools and the whole history, and every step is a chance to go wrong. The top chart shows the prompt size at each step against the context window; the bottom one shows the run's cost adding up. Pick a preset, then change the switches and numbers.

    Teal: prompt tokens sent at each step (darker part read from cache). Dashed: the context window and the compaction threshold. Apricot: cost so far; dashed: budget. Teaching latencies and prices. 🔶

    The rules this lab teaches

    1. Input grows with the square of the steps. 8 steps send 92,400 input tokens; 40 send 1.42 million. 🧭
    2. Caching is the first lever: the history is an unchanged prefix, read at 10% of the price. In the lab: $0.30 → $0.08 a run. ✅ Anthropic 2024
    3. Reliability multiplies: 99% per step is 67% over 40 steps. Validation and retries, or fewer steps, are the fix. 🧭
    4. Long runs hit the wall: compaction, clearing old tool results and sub-agents keep the context bounded. ✅ Anthropic Sep 2025

    Real numbers to quote

    Anthropic: agents use about 4× the tokens of chat, multi-agent systems about 15×; token usage alone explained 80% of performance variance on BrowseComp. ✅ Jun 2025

    Programmatic tool calling: one code step making 20+ tool calls saved 19+ model passes and 37% of tokens on complex research tasks. ✅ Nov 2025

    Sub-agents return a condensed summary, often 1,000–2,000 tokens, instead of their whole context. ✅ Sep 2025

    They'll push on thisAnswer out loud, then open.

    Deep dive: runs that survive crashes, retries and waiting for people

    Runs last minutes and wait hours; deploys land in the middle of them. The strip shows one interrupted run: what re-runs after the crash, and which re-runs repeat a side effect. Pick a preset, then change the switches and numbers.

    Top: the run before the crash (dots = side effects). Bottom: what runs again after it. Red fill: a side effect that happens twice. Teaching model: interruptions arrive at a steady rate while a run holds a worker. 🔶

    Three rules, in order

    1. Record each step before the next one starts; resume by replaying the record, not by re-running the run. ✅ Anthropic 2025
    2. Key every side effect with run + step, so the one in-flight step can safely run again. ✅ Stripe docs
    3. Park waiting runs: a durable timer or signal, not a thread. On replay, approval listeners run again, so their effects must be idempotent too. ✅ Pydantic AI docs

    How real platforms do it

    Anthropic's research agents: restarting is expensive, so they resume from where errors occurred, with retry logic and regular checkpoints, and use rainbow deployments so running agents aren't disrupted. ✅ Jun 2025

    LinkedIn reused its production messaging system as the orchestration layer (ordered, persistent delivery) for its Hiring Assistant agents. ✅ via InfoQ Sep 2025

    They'll push on thisAnswer out loud, then open.

    Deep dive: evals, rollouts, cost and guardrails

    A new prompt, model or tool description can make the agent quietly wrong on one kind of task while the average improves, and a wrong refund looks exactly like a right one in the logs. Ship agent changes like risky deploys, and design so a fooled model can't do damage.

    The release ladder

      One try or k tries? pass@k vs pass^k

      tau-bench: gpt-4o solved 61% of retail tasks on one try, but under 25% of tasks were solved in all 8 tries. Users meet every try. ✅ tau-bench 2024

      Judges for agents: useful, with limits

      The lethal trifecta: check the combination

      Tick what the agent's tools can do, then what protects it.

      Simon Willison named the trifecta in June 2025; Invariant Labs showed it with a GitHub issue that made an agent leak private repos. ✅ Willison · Invariant

      Prompt, tools or fine-tune?

      Tick what's true for the agent.

      Cost and latency per run

      1. Cache the stable prefix: system prompt and tools first, unchanged; append, never rewrite. ✅ OpenAI docs
      2. Fewer tools in context: load definitions on demand. ✅ Anthropic Nov 2025
      3. Route by step: a small model for easy steps, the strong one to plan. 🧭
      4. Fewer round trips: parallel tool calls; one code step for many calls. ✅ Anthropic Nov 2025
      5. Batch what can wait: scheduled agents go to cheaper batch capacity and run off-peak. 🧭

      Guardrails, in layers

      1. Least functionality and permission: granular tools, the user's narrowest OAuth scope. ✅ OWASP LLM06
      2. Complete mediation: authorization enforced by the gateway and services, not the model. ✅ OWASP LLM06
      3. People for high-impact actions, approving exact arguments. ✅ OWASP LLM06
      4. Tool results are data: mark them, flag instruction-like text, cut a trifecta leg. ✅ Willison 2025
      They'll push on thisAnswer out loud, then open.

      A run's lifecycle

      Every run moves through a small state machine. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.

      NormalSomething went wrongGreyed out: not possible from the current state.

      Edge cases interviewers love

      They'll push on thisAnswer out loud, then open.

      Failure, monitoring and recovery

      An agent platform fails loudly (runs stall) and quietly (runs do the wrong thing, twice, or expensively, with green graphs). The quiet ones matter more. 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 healthy run vs a looping one

      Every span carries the run id, agent version and model. Times are seconds from the start. In the bad trace a tool keeps timing out, the model keeps trying, and the loop detector stops the run.

      How one failure becomes three

      What you'd alert on (SLOs)

      SignalTargetAlert

      Incident playbook

        The toolkit

        Name the technique, then say where it goes in this design.

        They'll push on thisAnswer out loud, then open.

        Making it fast, and who owns what

        A run's time is model calls in a row; its real-world duration is often a person. Bars are sizing estimates, not measured figures.

        TeamOwnsPaged 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

        Checked October 2026. Numbers come from primary sources with their dates: Anthropic's engineering posts on building agents (19 Dec 2024), the multi-agent research system (13 Jun 2025), context engineering (29 Sep 2025) and advanced tool use (24 Nov 2025), and its prompt-caching prices (writes 1.25×, reads 0.1× of input, from the Aug 2024 launch page); Shopify's Sidekick post (26 Aug 2025); the tau-bench paper (2024) and the CaMeL paper (2025); OWASP LLM06:2025; the MCP authorization spec (2026-07-28 revision); Pydantic AI's Temporal docs; Stripe's idempotency docs; OpenAI's prompt-caching guide. LinkedIn's agent platform is cited through InfoQ's summary (15 Sep 2025) because LinkedIn's own post couldn't be fetched unattended. The GitHub MCP exploit is Invariant Labs' own research write-up (26 May 2025); the lethal trifecta is Simon Willison's (16 Jun 2025). Techinterview.org is a third-party prep site, used only to cross-check what interviewers expect. Nothing here comes from any employer's internal systems. Both labs use rounded teaching values: per-step success rates, latencies, interruption rates and prices are assumptions.

        System Design Mastermind · AI / ML systems

        Series home

        All of AI / ML systems

        8 published · 1 comingLLM and ML systems, where interviews are heading.

        22

        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.

        34 min · interactive Preview
        25

        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.

        34 min · interactive Preview
        28

        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.

        You're reading this Preview
        31

        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.

        34 min · interactive Preview
        34

        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.

        34 min · interactive Preview
        35

        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.

        34 min · interactive Preview
        36

        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.

        33 min · interactive Preview
        37

        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.

        34 min · interactive Preview
        ··

        Feature store and training platform

        Coming next

        More posts