Course contents

17. Real-World System Design Lesson 20 of 20

AI Agent Platform

Design a multi-tenant agent platform: MCP tool calls in sandboxes, task queues and checkpoints, LLM quota sizing, budgets, human approval and crash recovery.

25 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Size the platform by tasks/s × LLM calls and tokens per task, and by concurrent runs = arrival rate × run duration.
  • The model proposes tool calls; the runtime enforces allow-lists, scoped short-lived credentials and sandboxed execution via MCP servers.
  • Accept tasks onto a durable queue (202 + task id); runners execute and checkpoint them in the background.
  • The LLM quota is the real capacity limit: runners beyond it only produce 429s.
  • Budgets bound runaway loops; approvals checkpoint and release the runner instead of blocking it.
  • Leases redeliver a crashed runner’s tasks; at-least-once execution means tools must be idempotent.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An AI agent platform runs tasks that an LLM carries out step by step: the model decides the next action, the platform executes it (usually a tool call), the result goes back into the model's context, and the loop repeats until the task is done or a limit is hit. A multi-tenant platform does this for many users and teams at once, with shared LLM capacity, shared tools and strict isolation between tenants.

As a design exercise it is a job system wrapped around an expensive, rate-limited, non-deterministic dependency. Most of the hard parts are classic: queues, leases, checkpoints, budgets, idempotency, observability. The new parts are the tool boundary and the cost model.

Why it exists

A chat request is one model call. A task like "triage the new issues and open fixes for the trivial ones" is tens of model calls and tool calls over minutes or hours, some of which change real systems. Running that inside a web request fails on every axis: connections time out, restarts lose the work, a burst of tasks gets rejected, nobody can approve a risky step, and nobody can say afterwards what the agent did or what it cost. The platform exists to make those runs durable, bounded, safe and observable.

How it works

Requirements and estimates. Functional: submit a task, follow its progress, approve or reject sensitive actions, get the result; tools added by teams without changing the runtime. Non-functional: tasks survive crashes, one tenant cannot starve others, every action is auditable, spend is capped. An illustrative estimate (the numbers in the lesson): 12 new tasks per second at peak, ~10 LLM calls and ~20k tokens per task, so ~120 LLM calls and ~240k tokens per second. Most of those tokens are context re-sent on every call, so prompt caching and context trimming matter more than server count. With 60 s per run, Little's law gives 12 × 60 ≈ 720 runs in progress.

The agent loop. A runner holds the task's message history, calls the LLM with the available tool definitions, receives either a final answer or a tool-use request, executes the tool, appends the result and calls the LLM again. The loop is sequential per task, so a run spends most of its wall-clock time waiting on the model.

Tools through MCP. The Model Context Protocol standardises how an application (the MCP client, here the runtime) talks to tool providers (MCP servers). Messages are JSON-RPC 2.0; the client lists tools with tools/list and invokes one with tools/call; servers can also expose resources (readable data) and prompts. Transports are stdio for local servers and Streamable HTTP for remote ones, where the protocol specifies OAuth-based authorization. A platform typically runs a registry of approved MCP servers and decides per tenant and per task which tools an agent may see.

The tool boundary. The model only proposes a call. The runtime validates it against the task's allow-list and argument schema, obtains a short-lived credential scoped to this task and tool (from a secrets vault or token exchange), and the MCP server executes code in a sandbox: a fresh container or microVM with CPU, memory and time limits, a read-only base image and no network egress unless the tool requires specific destinations. Tool results and fetched documents are untrusted input; a prompt injection in a web page must not be able to grant new tools or exfiltrate credentials.

Accept, queue, run. The API validates the task, stores it, enqueues it and answers 202 Accepted with a task id; progress streams to the client (SSE, WebSocket) or arrives by webhook. Runner pools take tasks from the queue under a lease, renew the lease with heartbeats while they work, and write a checkpoint after each step: plan, message history, tool results, pending actions. Durable-execution engines (workflow systems that persist every step) are a common way to get this without building it.

Capacity is the LLM quota. Providers limit requests and tokens per minute, or sell provisioned throughput. Since each run mostly waits on the model, the number of runs you can usefully execute at once is set by that quota, not by runner CPU. Runner concurrency should follow the quota (per model, per region), with a token-aware admission check before each call. Past it, extra calls receive 429 Too Many Requests; retries spend the same quota again.

Budgets and loop detection. Each task carries limits: maximum steps, tokens, cost and wall-clock time, plus loop detection (the same tool with the same arguments several times in a row, no progress between steps). Hitting a limit stops the run cleanly: checkpoint, partial result, or escalation to a human. Per-tenant budgets and quotas keep one customer's runaway agents from consuming the shared LLM capacity.

Human approval. Sensitive actions (merging, sending, paying, deleting) require approval. The runner checkpoints the state and the exact pending action, emits an approval request and releases its slot. The approval (or rejection) is an event that re-enqueues the task; any runner resumes from the checkpoint and executes exactly the approved action, with the approver recorded in the audit log.

Failure handling. If a runner dies, its lease expires and the queue redelivers the task; another runner resumes from the last checkpoint. Delivery is at least once, so the step that was running may run again: side-effecting tools take an idempotency key, or the runtime records the intent before the call and checks it on resume. Tasks that keep failing go to a dead letter queue for inspection instead of retrying forever.

Observability and evaluation. Each task is a trace: a span per LLM call and per tool call with model, tokens, cost, latency, tool name and arguments (with sensitive values redacted). Dashboards show cost per task and tenant, steps per task, budget hits, 429 rate and tool error rates. Recorded tasks become an evaluation set: before a model or prompt change ships, replay them and compare success rate, steps and cost.

When to use it

  • Tasks need many dependent steps with tools and take longer than a request should.
  • Several teams or tenants share LLM capacity and tools, so isolation, quotas and audit are required.
  • Some actions are risky enough to need approval, and you must be able to show afterwards who approved what.

When not to

  • A single model call (classification, summarisation, extraction) answers the request: call the model from the service, with a timeout and a rate limiter.
  • The workflow is fixed and known in advance: a regular workflow or a pipeline with one or two model calls is cheaper, faster and easier to test than an agent deciding the steps.
  • Hard real-time latency is required: an agent loop is seconds to minutes by nature.

Trade-offs

Choice You gain You pay
Queue + background runners instead of synchronous requests Durable tasks, absorbed bursts, fast acceptance Status APIs, streaming progress, more moving parts
Checkpoint after every step Cheap crash recovery and approvals, replayable runs Storage, a little latency per step, schema for state
Tight budgets Bounded cost and capacity per task Hard tasks stop early or escalate more often
More autonomy (fewer approvals) Faster, less human effort Larger blast radius when the agent is wrong
Shared LLM quota Higher utilisation, lower cost Noisy neighbours unless per-tenant limits exist
Fresh sandbox per tool call Strong isolation, no leftover state Start-up latency and cost; warm pools need care

Alternatives

  • Direct model calls in the service for single-step features, with a timeout, a rate limiter and a fallback.
  • A workflow engine with model steps: fixed control flow, model calls as activities. Predictable and testable; the model does not choose the steps.
  • Batch APIs for offline, non-interactive work: much higher throughput per dollar, results within hours.
  • Hosted agent services from model providers: less to run, but less control over tools, data residency and observability.

Failure modes

  • Runaway loops: a prompt or model change makes agents repeat steps; capacity and spend explode. Budgets, loop detection and per-tenant quotas contain it.
  • Quota exhaustion and retry storms: 429s retried without backoff burn more quota. Admit calls against the quota, back off with jitter, shed or delay low-priority tasks.
  • Lost or duplicated side effects after a crash: missing checkpoints lose work; missing idempotency repeats a payment or an email.
  • Prompt injection through tool results: untrusted content steers the agent. Keep permissions outside the model's reach, isolate tools, require approval for sensitive actions.
  • Credential leakage: long-lived or broad tokens in the agent's context. Use short-lived, scoped credentials injected at the tool boundary, never shown to the model.
  • Stuck approvals: tasks waiting forever. Give approvals a deadline and a default (usually reject).
  • Silent quality regressions after a model update: no evaluation set, no alert. Replay recorded tasks before rollout.

In production

Route model calls through an LLM gateway that enforces per-tenant quotas, tracks tokens and cost, and fails over between models or regions. Keep runner concurrency per model in line with the purchased quota. Store checkpoints in a durable store with the task id as key and write them before side effects. Run tools from a curated MCP server registry, each server with its own identity and least-privilege credentials, in sandboxes with no default egress. Emit traces with GenAI semantic conventions (OpenTelemetry has them) so LLM and tool spans line up with the rest of your telemetry. Alert on cost per task, budget-hit rate, 429 rate and tool error rate, not only on latency.

Common misconceptions

  • "More runners make agents faster." Only until the LLM quota is used; after that they add 429s.
  • "A queue fixes overload." It absorbs bursts. If tasks arrive faster than runners finish them, the backlog grows until the queue is full.
  • "The model decides which tools it may use." The model proposes; the runtime authorises. Permissions must not depend on what the prompt says.
  • "Checkpoints mean exactly-once." A crash between a side effect and its checkpoint repeats the step. Tools need idempotency.
  • "Waiting for approval is just a long tool call." Holding a runner for hours wastes a slot and loses the wait on restart. Checkpoint and release.

Interview angle

Start with requirements and numbers: tasks per second, steps and tokens per task, run duration, concurrent runs, cost per task. Draw the accept-queue-run shape early and explain why. Interviewers then probe the scarce resource (how you size against the LLM quota and handle 429s), safety (tool allow-lists, sandboxing, scoped credentials, prompt injection, approvals), durability (leases, checkpoints, idempotent tools, dead letters) and cost control (budgets per task and tenant, caching). Close with observability and evaluation: how you would detect that a new model loops more before users do.

Model assumptions

The simulation is a simplified model, not a benchmark, and durations are compressed: one agent run, minutes in reality, takes about 600 ms of simulated time (lognormal, cv 0.3–0.4; 1500 ms with cv 1.0 for looping agents). The engine has no LLM or tool model. LLM capacity is represented by the runner slot count (one slot = one concurrent run within the quota); 429s, token accounting and costs are described, not simulated. Runner pools are queue consumers; the task queue redelivers a task whose lease (visibility timeout, 2 s in the crash step) expires without an acknowledgement. The agent loop, MCP tool calls, credentials, sandboxing, checkpoints and the approval flow are scripted illustrations over scenery nodes, not simulated behaviour. Task arrivals are Poisson. Estimates in the text (tasks per second, LLM calls and tokens per task) are illustrative orders of magnitude.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements and a first estimate

    Users hand the platform tasks ("triage these issues", "fix the failing test"). An agent works on each one in a loop: ask the LLM what to do next, call a tool, feed the result back, repeat until done. The animation follows one task through that loop (scripted illustration).

    Illustrative numbers: a peak of 12 new tasks per second, about 10 LLM calls and 20k tokens per task (most of it context re-sent on every call). That is about 120 LLM calls and 240k tokens per second, and token spend, not servers, is the main cost.

    Runs are long: if a task takes 60 s, Little’s law gives 12 × 60 ≈ 720 runs in progress at once. In this first design the Agent Runtime handles 12 runs at once and the user waits on the open request. Durations are compressed: one run takes ~600 ms of simulated time.

    Scene: Users send 12 tasks per second to the Agent API, which calls the Agent Runtime and waits. The runtime is about two-thirds busy and every task succeeds. A scripted task goes runtime → LLM → runtime → MCP tool → runtime → LLM → runtime and back to the user.

    Key idea: Size an agent platform by tasks/s × LLM calls and tokens per task, and by concurrent runs = arrival rate × run duration.

  2. 2. Tools through MCP, run in a sandbox

    Tools live behind MCP servers (Model Context Protocol). The runtime connects as an MCP client, discovers tools with tools/list and invokes one with tools/call, JSON-RPC messages over stdio or Streamable HTTP. A server can also expose resources and prompts. New tools plug in without changing the runtime.

    The model only proposes a call. The runtime checks it against the task’s allow-list, fetches a short-lived token scoped to this task and tool from the vault (the yellow packet), and the MCP server runs the code in a sandbox: a fresh container with CPU, memory and time limits and no network access unless the tool needs it.

    Treat tool results and fetched content as untrusted input: a prompt injection in a web page must not be able to grant itself new tools. The sequence is a scripted illustration.

    Scene: Scripted: the LLM proposes a tool call; the runtime gets a scoped token from the Secrets Vault, calls the MCP server, which runs the tool in a sandbox container; the result goes back to the LLM.

    Key idea: The LLM proposes, the runtime decides: allow-listed tools, scoped short-lived credentials, sandboxed execution.

  3. 3. Holding requests open does not scale

    Traffic grows to 30 tasks per second. The runtime can finish about 20 per second (12 runs at once, ~600 ms each). Its slots fill, its small waiting line fills, and new tasks are rejected (red packets).

    The deeper problem is the shape: real runs take minutes. An HTTP request held open that long ties up a connection and a worker, is cut by proxies and mobile networks, and is lost entirely if the runtime restarts. Retrying it starts the whole run, and its token bill, again.

    Scene: At 30 tasks per second the Agent Runtime is saturated with a full waiting line, and many tasks fail.

    Key idea: A minutes-long task is not a request: holding the connection open couples users to runtime capacity and loses work on every restart.

  4. 4. Accept the task, run it in the background

    The API now stores the task and puts it on a queue, answering at once with a task id (HTTP 202). Users follow progress over a stream or a webhook. Runner pools take tasks off the queue; each slot runs one agent loop and writes checkpoints (plan, message history, tool results) to a state store.

    No task is rejected any more and the API answers in milliseconds. But two pools of 8 slots finish about 27 runs per second against 30 arriving: the backlog grows. The queue absorbs the gap; it does not close it.

    Scene: The Agent API enqueues each task on the Task Queue and answers at once; Runners A and B consume tasks. Nothing fails, but the backlog in the queue grows because 16 slots finish fewer tasks than arrive.

    Key idea: Accept fast, run asynchronously, checkpoint often: the queue separates user-facing latency from run time.

  5. 5. Size the runners to the LLM quota

    Every running agent spends most of its time waiting on the LLM, so the real limit is the LLM quota: requests and tokens per minute, or provisioned concurrency. Here the quota supports about 24 concurrent runs, so the pools grow to 12 slots each.

    The pools now finish about 40 runs per second, the backlog stays near empty and the runners sit around three-quarters busy.

    More runners than the quota buys nothing: the extra calls get 429 Too Many Requests, retry, and burn more of the same quota. The engine models the quota as the runner slot count.

    Scene: Both runner pools have 12 slots, matching the LLM quota. They finish more tasks than arrive and the queue stays nearly empty.

    Key idea: Runner concurrency should follow the LLM quota; scaling runners past it only converts backlog into 429s.

  6. 6. An agent that never stops

    A new prompt version makes some agents loop: they re-read the same files, retry a failing tool, or keep "verifying" their work. The average run is now 2.5× longer and the spread is far wider: a few runs go on and on.

    Each looping run holds an LLM lane. The pools finish only about 16 runs per second, so the backlog grows by more than ten tasks per second and every user waits longer. Tokens per task, and the bill, rise by the same factor.

    Scene: Runs take 2.5 times longer with a heavy tail. Both runner pools are fully busy and the Task Queue backlog grows quickly.

    Key idea: Agent run time is unbounded by default; a few looping runs consume the shared LLM capacity everyone needs.

  7. 7. Step, token and cost budgets

    Every task now carries budgets: at most N steps (LLM calls), a token and dollar ceiling, and a wall-clock limit. The runtime also detects loops: the same tool called with the same arguments several times in a row. A run that hits a limit stops, saves its checkpoint and reports a partial result or asks a human.

    Capping the tail brings the average run back to about 600 ms. The pools again finish about 40 runs per second and the backlog stays near empty. Per-tenant budgets also stop one customer’s runaway agents from using up everyone’s quota.

    Scene: With budgets, runs are short again. Both runner pools have spare capacity and the Task Queue stays nearly empty.

    Key idea: Budgets turn an unbounded loop into a bounded job: cap steps, tokens, cost and time per task and per tenant.

  8. 8. Pause for a human without holding a runner

    Some actions need a person: merging code, sending an email to a customer, spending money. When the agent reaches one, the runner checkpoints the state, records the pending action, notifies an approver and releases its slot. Nothing waits in memory while a human decides; that can take hours.

    The approval arrives as an event that re-enqueues the task. Whichever runner picks it up (here Runners B) loads the checkpoint and executes exactly the approved action. The sequence is a scripted illustration over live background traffic.

    Scene: Scripted: Runners A checkpoints a task to the State Store and asks the API to notify the Approver, then is free. The approval re-enqueues the task; Runners B loads the checkpoint and performs the approved tool call.

    Key idea: Human-in-the-loop = checkpoint, release, resume on an event. Never block a runner (or an LLM lane) on a person.

  9. 9. A runner pool dies mid-task

    One second in, Runners A crashes with tasks in progress. Nobody acknowledged those tasks, so the queue still owns them. Runners renew a lease with heartbeats; here a lease expires 2 s after the last one. Then the tasks are delivered again and Runners B picks them up and resumes from their last checkpoint.

    While B works alone it finishes about 20 runs per second, fewer than arrive, so the backlog grows until A is replaced 4.5 s in, then drains. No task is lost or dead-lettered.

    A resumed task may repeat the step that was running at the crash, so tools must be idempotent (pass an idempotency key) or the step must be checkpointed before its side effect.

    Scene: Runners A goes offline after one second. About two seconds later its unfinished tasks are redelivered to Runners B. The backlog grows until Runners A returns at 4.5 seconds, then drains. No task fails.

    Key idea: Leases + checkpoints make runner crashes cost a little time, not the task; at-least-once means tools must be idempotent.

  10. 10. Observe every step, then decide

    Run each task as a trace: one span per LLM call and tool call, with tokens, cost, latency and the tool arguments. That is how you find the looping prompt, the slow MCP server or the tenant burning the quota, and it feeds evaluation: replay recorded tasks against a new model or prompt before rollout.

    The trade-offs: tight budgets fail hard tasks, loose ones waste money; more autonomy means fewer approvals but more blast radius; one shared quota is cheaper, per-tenant quotas are fairer; checkpointing every step costs storage and latency but makes crashes and approvals cheap.

    Scene: The full platform: Agent API, Task Queue, two runner pools sized to the LLM quota, MCP server with sandbox, Secrets Vault, State Store and Approver. Everything is healthy.

    Key idea: An agent platform is a job system around a scarce, expensive dependency: queue it, budget it, sandbox it, trace it.