Design an AI Agent Platform
Product teams want to ship AI agents: an LLM that is given a goal, decides which tool to call next, looks at the result, and keeps going until the job is done. One team builds a support agent that looks up orders and issues refunds; another builds a data agent that writes and runs Python against a warehouse; a third automates IT tickets.
Design the shared platform that runs these agents. Runs can take seconds or hours, make dozens of model and tool calls, and touch real systems with real money. Agents can loop, hallucinate tool arguments, or be manipulated by text they read in a web page or email. Some actions must wait for a human to approve them.
In 45 minutes, cover the execution loop and how it survives crashes, the tool registry and sandboxed code execution, memory, human-in-the-loop approvals, and how operators observe runs and cap their cost.
Sketch on the HLD board, write your answer in the Design doc, and size it with the Estimator. Start the mock interview from the timer for a 45-minute run.
Design Path · AI & ML Systems · problem 54 of 70
Ask before you design. Try answering each yourself, then compare.
- Who defines agents and tools?
Typical answer
Platform users (internal teams) register tools with schemas and owners, and configure agents as a system prompt, a model and a set of allowed tools.
- What scale?
Typical answer
About 1 M agent runs/day, averaging 12 steps and ~2 minutes each; a few long runs last hours.
- Which models?
Typical answer
Any model behind the company LLM gateway: hosted APIs or self-hosted open-weights models. The platform is model-agnostic.
- Do agents run arbitrary code?
Typical answer
Yes, about 30% of runs execute generated Python. It must be isolated from our network and other tenants.
- Which actions need approval?
Typical answer
Anything tagged risky by the tool owner (payments, emails to customers, deletes) or above a configurable amount. Approvals can take hours.
- What are the cost expectations?
Typical answer
Each agent has a per-run budget (for example $0.50) and each team a monthly budget; runaway loops must be stopped automatically.
Requirements
Functional
- Register tools with JSON schemas, owners, auth scopes and risk levels.
- Configure agents (model, instructions, allowed tools, budgets) and start runs via API.
- Execute the plan-act-observe loop with streaming progress events.
- Run generated code in an isolated sandbox.
- Pause runs for human approval and resume on decision.
- Short-term and long-term memory per agent and user.
- Trace every step with tokens, cost and latency.
Non-functional
- 1 M runs/day, ~4,000 concurrent runs at peak; step overhead added by the platform < 100 ms.
- No step lost or executed twice on worker crash (exactly-once effects for idempotent tools).
- Sandbox start p95 < 300 ms; strict isolation between tenants.
- Runs stop within one step of exceeding their budget.
Out of scope
- Training or fine-tuning models.
- Building the individual tools themselves.
- A visual agent builder UI.
Back-of-the-envelope estimates
Here a "write" is an agent run and a "read" is one step (model call) inside it.
- Runs: 1 M/day ≈ 12/s average, ~35/s peak. At ~2 minutes each, ~1,400 runs are live on average and ~4,000 at peak.
- Model calls: 12 steps × 1 M = 12 M/day ≈ 140/s, ~420/s at peak.
- Tokens (assumption): the context grows each step to ~8k input tokens on average, so ~96 B input tokens/day. At an assumed $1 per million input tokens that is ~$96k/day; reusing cached prompt prefixes at an assumed 90% discount on 70% of tokens brings it nearer $35k/day.
- Sandboxes: 30% of runs execute code, ~3 M sandbox sessions/day; with warm pools a few hundred microVMs are idle and ready at any time.
- Traces: ~200 KB per run ≈ 200 GB/day, kept 30 days hot.
Tokens dominate cost and are driven by step count and context growth, so the design caps steps, compacts context, and reuses prompt prefixes. Concurrency of long-lived runs, not QPS, drives the runtime.
API
POST /v1/tools {name, description, input_schema, endpoint|sandbox, scopes, risk}
POST /v1/agents {name, model, instructions, tools[], budget:{steps, usd}}
POST /v1/runs {agentId, input, idempotencyKey} -> {runId}
GET /v1/runs/{id}/events -> SSE: step.started, llm.delta, tool.called,
approval.requested, run.completed
POST /v1/approvals/{id} {decision: approve|reject, editedArgs?, comment}
POST /v1/runs/{id}/cancelRuns are asynchronous resources with an event stream rather than a long blocking call, because they outlive HTTP timeouts and may pause for hours waiting on a person.
Data model
run_events(run_id, seq, type, payload, created_at) is an append-only log in a partitioned key-value store keyed by run_id: every model response, tool call, tool result, approval and budget charge is an event, and the current run state is a fold over the log. That gives crash recovery, replay for debugging and an audit trail.
tools(name, version, schema, owner_team, risk, scopes) and agents(id, model, instructions, tool_names[], budget) sit in a relational store. approvals(id, run_id, tool, args, status, expires_at, decided_by) is relational too (queried by approver). Long-term memory is a vector index of facts with (user_id, agent_id, text, source_run, created_at), filtered by user. Spans and usage go to a trace store and a usage table aggregated per team.
High-level design
A caller starts a run through the agent API, which authenticates it, checks the team budget and enqueues the run on the run queue. A worker in the agent runtime leases the run and executes the loop one step at a time. Each step: rebuild the context from the run state store (instructions, compacted history, recalled facts from agent memory); ask the planner LLM for the next action, constrained to the agent's tool schemas; validate the arguments; ask policy and approvals whether the call is allowed; then send it to the tool gateway. The gateway looks the tool up, injects short-lived credentials scoped to this run, and either calls an external API through an egress proxy or runs code in a sandbox executor. The result is appended to the run log before the next step starts, so a crashed worker's run is picked up by another worker from the last checkpoint.
If policy requires approval, the runtime records an approval event, releases the worker and the run sleeps; the request is pushed to the user through the API. A decision re-enqueues the run. Every step emits spans with tokens, cost and latency to traces and cost, which also enforces budgets and kills runaway runs. Progress is streamed to the caller as events.
Open the HLD board and press Reference to see the architecture diagram.
Deep dives
A durable agent loop
Model each run as an event-sourced state machine: planning → awaiting_tool → awaiting_approval → ... → done. Before executing a tool, write a tool.called event with an idempotency key derived from run_id and step number; after it returns, write tool.result. On recovery, a step with a call but no result is retried with the same key, and tools that move money must honour it. Leases with heartbeats let a dead worker's runs move within seconds. Waiting (approvals, long tool jobs) holds no worker: the run is parked in storage and re-enqueued by the event that wakes it. Context is rebuilt from the log each step, with older steps compacted into a summary once the prompt passes a threshold.
Tools, sandboxes and prompt injection
Every tool has a schema, an owner and scopes; the planner only sees tools the agent is allowed, and arguments are validated against the schema before execution. Credentials never enter the prompt: the gateway mints short-lived tokens bound to the run and the user on whose behalf it acts. Generated code runs in a microVM or user-space kernel sandbox with CPU, memory and time limits, a read-only base image, no network by default and an allowlist when needed; a warm pool keeps start time near 150 ms. Text from tools, web pages or emails is untrusted data: it is wrapped and labelled as such, and high-risk actions require policy checks that do not depend on the model's judgement, so injected instructions cannot directly trigger a refund.
Human approval without blocking
Tool owners tag risk levels; a policy engine evaluates each call with the arguments and context (amount, recipient domain, data sensitivity) and returns allow, deny or needs_approval. For approval, the runtime stores the exact proposed call, shows the approver a readable diff or preview, and parks the run. Approvers can approve, reject or edit arguments, and the decision is written to the log with who and when. Approvals expire (for example 24 h), after which the run continues with a rejection observation so the agent can explain or choose another path. Batching similar approvals and learning auto-approve rules from history keeps humans from becoming the bottleneck.
Observability and cost limits
Emit a trace per run with a span per model call and tool call, carrying tokens, cost, latency, model and tool versions. Operators need a run viewer that replays the event log step by step; that is how agent bugs are actually debugged. Budgets exist at three levels: per run (steps, dollars, wall-clock), per agent and per team per month. The runtime reserves the estimated cost before each model call and stops the run when it would exceed its cap. Loop detection (the same tool and arguments repeated, or no new information for N steps) ends runs early. Offline evaluation replays a suite of recorded tasks against new prompts and models before rollout.
Failure modes
- If a runtime worker crashes mid-step, its lease expires and another worker replays the run log and retries the pending step with the same idempotency key.
- If the LLM provider is down or throttling, runs pause with backoff and resume; the gateway can fail over to a second model for agents that allow it.
- If a tool is slow or failing, the gateway applies per-tool timeouts and circuit breakers and returns an error observation the agent can reason about.
- If an agent is hijacked by injected text, policy checks, scoped credentials and approvals bound the damage to what the run was allowed to do anyway.
Core algorithm in code
from dataclasses import dataclass, field
@dataclass
class Tool:
name: str
fn: callable
risky: bool = False
cost_usd: float = 0.0
@dataclass
class Budget:
max_steps: int
max_usd: float
spent_usd: float = 0.0
steps: int = 0
class BudgetExceeded(Exception):
pass
class AgentRun:
LLM_CALL_USD = 0.01 # assumed average cost of one planning call
def __init__(self, planner, tools, budget, approve):
self.planner, self.budget, self.approve = planner, budget, approve
self.tools = {t.name: t for t in tools}
self.trace = [] # durable step log in a real system
self.seen_calls = set()
def _charge(self, usd):
self.budget.spent_usd += usd
if self.budget.spent_usd > self.budget.max_usd:
raise BudgetExceeded("cost limit $%.2f reached" % self.budget.max_usd)
def run(self, goal):
history = [("goal", goal)]
try:
while True:
self.budget.steps += 1
if self.budget.steps > self.budget.max_steps:
raise BudgetExceeded("step limit reached")
self._charge(self.LLM_CALL_USD)
action, arg = self.planner(history)
if action == "finish":
self.trace.append(("finish", arg))
return arg
key = (action, arg)
if key in self.seen_calls: # cheap loop detection
history.append(("observation", "you already did this; try something else"))
self.trace.append(("loop-guard", action))
continue
self.seen_calls.add(key)
tool = self.tools.get(action)
if tool is None:
history.append(("observation", "unknown tool " + action))
continue
if tool.risky and not self.approve(action, arg):
history.append(("observation", "human rejected " + action))
self.trace.append(("rejected", action))
continue
self._charge(tool.cost_usd)
obs = tool.fn(arg)
self.trace.append((action, arg, obs))
history.append(("observation", obs)) # tool output is data, not instructions
except BudgetExceeded as e:
self.trace.append(("stopped", str(e)))
return "stopped: " + str(e)
def scripted_planner(plan):
"""Stands in for the LLM: returns the next scripted action."""
it = iter(plan)
return lambda history: next(it, ("finish", "gave up"))
tools = [
Tool("search_orders", lambda q: "order 8812: 2 items, shipped late", cost_usd=0.001),
Tool("issue_refund", lambda amt: "refunded $" + amt, risky=True),
Tool("send_email", lambda body: "email queued", risky=True),
]
approvals = {"issue_refund": True, "send_email": False}
plan = [("search_orders", "customer 51"), ("search_orders", "customer 51"),
("issue_refund", "20"), ("send_email", "Sorry for the delay"), ("finish", "refund issued, email skipped")]
run = AgentRun(scripted_planner(plan), tools, Budget(max_steps=10, max_usd=0.50),
approve=lambda a, x: approvals[a])
print("result:", run.run("Customer 51 complains about a late order"))
for step in run.trace:
print(" ", step)
print("spent $%.3f in %d steps" % (run.budget.spent_usd, run.budget.steps))
runaway = AgentRun(lambda h: ("search_orders", "q%d" % len(h)), tools, Budget(max_steps=50, max_usd=0.05),
approve=lambda a, x: True)
print("runaway agent:", runaway.run("loop forever"))
Trade-offs
- Checkpointing every step to a durable log makes runs crash-proof and debuggable but adds a write of latency and storage per step.
- MicroVM sandboxes give strong isolation but cost more start time and memory than containers sharing a kernel.
- Requiring human approval for risky tools prevents costly mistakes but slows runs from seconds to hours.
- Letting the model plan freely handles novel tasks but costs more tokens and less predictability than fixed workflows with LLM steps.
- Long-term memory improves personalization but risks storing wrong or injected facts that persist across runs.
What a strong answer shows
- Treats a run as durable, resumable state, not a long in-memory loop.
- Handles tool side effects with idempotency and explicit retries.
- Isolates code execution and treats tool output as untrusted input.
- Designs approvals as asynchronous pauses with audit trails.
- Puts concrete budgets and loop detection in place, with token-based cost estimates.
- Provides traces and replay for debugging and evaluation.
Mistakes to avoid
- Running the loop inside one HTTP request with an in-memory state.
- Giving the agent broad, long-lived credentials or putting secrets in the prompt.
- Relying on the system prompt alone to stop prompt injection.
- Holding a worker thread while waiting hours for human approval.
- No per-run limits, so one looping agent burns a team's monthly budget overnight.
Follow-ups to expect
- How would you support multi-agent setups? (Agents as tools of a supervisor agent, each with its own budget and trace.)
- How do you evaluate a new model for an agent? (Replay a recorded task suite and compare success, cost and steps.)
- How would you let agents use a browser? (A sandboxed headless browser tool with screenshots and strict egress.)
- How do you keep memory correct? (Store provenance, let users view and delete, expire low-confidence facts.)