LevelUpWith

Explore / AI Engineering

Production AI Agents: Sandboxes, Gates and Durable Runs

Run AI agents safely in production. Isolate them in sandboxes, keep hours-long work alive with durable execution, put approval gates on risky actions, trace every step, and control spending across Claude, OpenAI, Gemini and open-weight models.

Read lesson 1 free →

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor.

Photographic 3D course artwork for Production AI Agents: Sandboxes, Gates and Durable Runs

Expert · 48 levels · 4 free · Created Nov 2026 · Professionally curated by levelupwith.com

What's inside

  1. Level 1: Why Agents Need IsolationFree
    Learn why an agent that runs model-written code or calls tools is running untrusted code, and how a mistake, a hallucination or a prompt injection becomes real damage when nothing contains it.
    • Explain why code an agent generates should be treated as untrusted, even when it comes from a frontier model you pay for
    • Name the main ways an unisolated agent causes harm: destroying files, leaking secrets, abusing the network and exhausting resources
    • Run a small Python or TypeScript agent loop on your laptop and list everything it could touch on your machine
  2. Level 2: Threat Modelling an Agent's Blast RadiusFree
    Build a practical threat model for one agent by listing its tools, data, credentials and network reach, and marking where trust boundaries must sit.
    • Draw a trust-boundary diagram for an agent, separating the model, the orchestrator, the execution environment and outside services
    • Rank threats by likelihood and impact, including indirect prompt injection through files, web pages and tool output
    • Write a one-page threat model that later lessons will use to choose a sandbox and its controls
  3. Level 3: Containers as Sandboxes: What Docker Really Isolates
    Understand how namespaces, cgroups and seccomp isolate a container, why the shared host kernel is the weak point, and how to harden a container for running agent code.
    • Explain what a container isolates and what it doesn't, especially the shared kernel and the risk of container escape
    • Run agent-generated code in a hardened container: non-root user, read-only root filesystem, dropped capabilities, no-new-privileges and a seccomp profile
    • Show that the hardening works by running escape and privilege-escalation probes from inside the container
  4. Level 4: gVisor: A User-Space Kernel for Untrusted Code
    Learn how gVisor's runsc runtime intercepts system calls in a user-space kernel to shrink the host's attack surface, and what that costs in compatibility and performance.
    • Explain how gVisor sits between the workload and the host kernel, and how that differs from a plain container
    • Configure Docker to run an agent's code with the runsc runtime and confirm it is running under gVisor
    • Measure startup time and system-call-heavy workloads under runc and runsc, and record which workloads struggle
  5. Level 5: Firecracker MicroVMs: Hardware-Level Isolation
    Understand how Firecracker microVMs use KVM and a minimal device model to give each agent its own kernel, and when that stronger boundary is worth the extra operational work.
    • Compare the isolation boundaries of containers, gVisor and microVMs, and say which threats each one actually stops
    • Boot a Firecracker microVM and run an agent-generated script inside it
    • Decide, with written reasons, which isolation level your Level 2 threat model needs
  6. Level 6: Hosted Sandboxes: E2B, Modal, Daytona, Cloudflare
    Compare hosted sandbox platforms on isolation technology, lifecycle API, startup time, persistence and pricing model, and weigh building your own against buying one.
    • Create a sandbox, run code and read back files with at least two hosted providers from Python or TypeScript
    • Build a comparison matrix of hosted providers using each vendor's current documentation, not marketing claims or conference slides
    • Write down the build-versus-buy trade-offs for your team: data residency, vendor lock-in, cost at scale and incident ownership
  7. Level 7: Vendor Code-Execution Tools: Claude, OpenAI, Gemini
    Learn how the code-execution tools built into model APIs work, what you give up in control and visibility, and when they are a better choice than running your own sandbox.
    • Call the built-in code-execution tool from the Claude, OpenAI and Gemini APIs side by side on the same task
    • List what you can and cannot control in a vendor-run sandbox: network, packages, file persistence, data retention and logs
    • Choose between a vendor tool, a hosted sandbox and a self-run sandbox for three example workloads, with reasons
  8. Level 8: Locking Down Network Egress
    Apply default-deny networking to sandboxes, route allowed traffic through an allowlisting proxy, and close common exfiltration paths such as DNS and package registries.
    • Run a sandbox with no network by default, then allow only named hosts through an egress proxy
    • Show exfiltration attempts over HTTP, DNS and package installs, then block each one
    • Log every outbound request with the agent run that made it so it can be audited later
  9. Level 9: Keeping Secrets Out of the Sandbox
    Keep long-lived credentials away from agent code and prompts by injecting short-lived tokens at a proxy boundary, and catch secrets that leak into output.
    • Explain why API keys in environment variables, files or prompts are readable by any code the agent runs
    • Add credentials at an egress proxy so the sandbox can call one API without ever seeing the key
    • Add secret scanning to tool output and logs, and confirm it flags a planted canary token
  10. Level 10: Resource Limits and Sandbox Lifecycle
    Protect hosts and budgets from runaway agent code with CPU, memory, disk, process and wall-clock limits, and manage sandbox creation, teardown and orphan clean-up.
    • Set and test CPU, memory, disk, process-count and timeout limits against a fork bomb, a memory leak and an infinite loop
    • Build a lifecycle wrapper that always tears down sandboxes, even when the agent crashes
    • Write a reaper job that finds and kills orphaned sandboxes and reports what they cost
  11. Level 11: Why Long-Running Agents Fail
    Map how agent runs that last hours break, through process crashes, deploys, sandbox timeouts and provider errors, and identify which state must survive each failure.
    • List the failure modes of a long agent run and how often each one is likely to happen
    • Separate an agent's state into transcript, sandbox filesystem, running processes and side effects already applied to the outside world
    • Kill an agent mid-run and record exactly what was lost and what was already done
  12. Level 12: Snapshot, Pause and Resume a Sandbox
    Use provider snapshot and pause/resume features to keep sandbox state across idle periods and crashes, and learn what survives a resume and what doesn't.
    • Pause and resume a sandbox with its memory and filesystem kept, then do the same with the filesystem only, and compare the results
    • Explain which state is lost across a resume, such as open network connections and timers, and handle it in code
    • Track snapshot IDs and retention limits in your own database, because providers expire snapshots on different schedules
  13. Level 13: Rehydrating Agent Work from Scratch
    Rebuild a working sandbox when no snapshot is available, using a repeatable setup script, saved artifacts and version control as the real source of truth.
    • Write a repeatable setup script that rebuilds an agent's environment from a clean image
    • Save work as it happens to durable storage such as git branches or object storage, so a lost sandbox costs minutes, not hours
    • Test rehydration by destroying a sandbox mid-task and resuming the work on a fresh one
  14. Level 14: Checkpointing the Agent Loop
    Save the agent loop's own state (messages, tool calls, results and step counter) after every step, so a crashed run continues where it stopped instead of starting over.
    • Design a checkpoint schema for an agent run in Postgres, with a step-level record of each model call and tool call
    • Resume a crashed loop from its last checkpoint without repeating model calls that already finished
    • Handle context-window growth on resume by compacting or summarising the history, and note what information that loses
  15. Level 15: Durable Execution: Workflows, Activities, Replay
    Understand the durable-execution model behind engines like Temporal and Inngest: an event history that is replayed to rebuild state, and the determinism rules it imposes.
    • Explain how workflow code, activities or steps, and the event history work together to survive crashes
    • Spot code that breaks replay determinism, such as reading the clock, random numbers or direct I/O inside workflow code
    • Draw the line between deterministic orchestration and non-deterministic work like model calls and tool calls
  16. Level 16: Running an Agent Loop on Temporal
    Move an agent loop onto Temporal, with model calls and tool calls as activities that have their own timeouts, retry policies and heartbeats.
    • Implement an agent workflow in Python or TypeScript where every model call and tool call is a Temporal activity
    • Set retry policies and timeouts for each activity, marking errors that must not be retried as non-retryable
    • Kill the worker mid-run and watch the workflow resume on a new worker without losing progress
  17. Level 17: Agents on Inngest and Other Workflow Engines
    Build the same agent on Inngest's step functions and compare it with Temporal and other engines on programming model, hosting, waiting for events and operating cost.
    • Implement the agent loop with Inngest steps so finished steps are memoised and skipped when the run retries
    • Pause a run until an outside event arrives, such as a webhook or a user reply, without holding a process open
    • Write a comparison of Temporal, Inngest and at least one other engine for your use case, and say plainly where practice is still unsettled
  18. Level 18: Idempotent Tools: Making Retries Safe
    Design tools so a retried or replayed call can't repeat a side effect, using idempotency keys, deduplication records and the outbox pattern.
    • Derive stable idempotency keys from the workflow run and step, and pass them to downstream APIs that accept them
    • Add a deduplication table so a tool that sends email or creates records gives the same result when called twice
    • Write a chaos test that forces retries at every step and proves each side effect happens exactly once
  19. Level 19: Background Agents: Triggers, Queues and Handoff
    Turn the durable agent into a background worker that starts from issues, webhooks or schedules, runs with limited concurrency, can be cancelled, and delivers its results.
    • Trigger agent runs from a webhook or queue message, with per-tenant concurrency limits and back-pressure
    • Add cancellation and progress reporting so a user can check on or stop a run that has been going for hours
    • Deliver results in a reviewable form, such as a pull request or a report, and notify the person who asked
  20. Level 20: The Model Proposes, the Platform Decides
    Treat every tool call as a proposal that a policy layer outside the model must allow, deny or send for approval before anything runs, and log each decision for audit.
    • Put an enforcement point between the agent loop and its tools that blocks any call the platform hasn't approved
    • Sort an agent's tools into allow, deny and needs-approval classes based on side effects and how easily they can be undone
    • Record every proposal, decision and reason in an audit log tied to the run's ID
  21. Level 21: Policy as Code with OPA and Cedar
    Write the rules for agent tool calls as versioned, testable policies in a policy engine such as Open Policy Agent (Rego) or Cedar, so they stop living as if-statements spread through the agent code.
    • Write allow, deny and needs-approval policies for tool calls, using the tool name, arguments, tenant and environment
    • Check every proposed tool call against the policy engine from a Python or TypeScript agent loop, and fall back to deny when the engine can't be reached
    • Unit-test policies against a table of good and bad tool calls before deploying them
  22. Level 22: Short-Lived, Scoped Credentials for Agents
    Swap long-lived API keys in the agent's environment for credentials that a broker issues per task, scoped to the job and quick to expire, using token exchange and cloud role-assumption patterns.
    • Design a credential broker that issues each agent run a token limited to one task, one resource set and a short lifetime
    • Keep secrets outside the sandbox by injecting them at a proxy or tool boundary, so the model never sees them
    • Revoke a run's credentials mid-flight and check that its later tool calls fail safely
  23. Level 23: Prompt Injection: The Agent Threat Model
    Learn how untrusted content in web pages, files, issues, emails and tool results can hijack an agent, and why private data plus untrusted input plus a way to send data out is the combination that turns injection into data loss.
    • Map every route by which untrusted text reaches the model in an agent you are designing
    • Find the tool combinations that make data theft possible and remove at least one part of each
    • Reproduce an indirect prompt injection against a toy agent in a sandbox
  24. Level 24: Defending Against Injection by Design
    Apply architectural defences that don't rely on the model resisting persuasion: keeping trusted instructions separate from untrusted data, quarantining untrusted content with a separate model, tracking where data came from, and narrowing tool capabilities, with an honest note that no defence is complete yet.
    • Build a two-model pattern where a quarantined model reads untrusted content and returns only data that fits a fixed structure
    • Tag tool outputs as trusted or untrusted and block high-risk actions whose arguments came from untrusted sources
    • Explain why classifier-based injection filters reduce risk without removing it
  25. Level 25: Human Approval Gates for Side Effects
    Pause a durable agent run before payments, deletes and production changes, wait as long as needed for a human decision, and resume or abort cleanly using workflow signals.
    • Sort tool actions into auto-approve, require-approval and forbidden tiers by how reversible they are and how much damage they can do
    • Build an approval step on a durable-execution engine that can wait hours without holding compute or losing state
    • Handle approval timeouts, rejections and expired requests without leaving partial side effects behind
  26. Level 26: Approvals Humans Can Actually Judge
    Design approval requests that resist rubber-stamping and tampering: show dry-run diffs, keep a signed record of exactly what was approved, require a second approver for critical actions, and keep an audit trail.
    • Generate a dry-run preview showing the exact effect of a proposed action before anyone approves it
    • Bind each approval to a hash of the exact action so the agent cannot change the arguments after approval
    • Track approval volume and approve rates to spot reviewer fatigue
  27. Level 27: Computer-Use and Browser Agents: Extra Risks
    Learn why agents that see screens and click buttons widen the attack surface: on-screen injection, signed-in sessions, actions that can't be undone, and mistakes that are hard to see. Compare the computer-use and browser tools that Claude, OpenAI and Gemini document today.
    • Compare the vendor-documented computer-use and browser tools, including their safety guidance and limits
    • List the risks specific to screen-driven agents, such as injected page content, session hijacking and misclicks
    • Decide when a browser agent is the right tool and when an API integration is safer
    • Learners finish the lesson by trying computer-use and browser tools themselves: they run the same small task through the Claude, OpenAI and Gemini tools against a throwaway test page that contains pla
  28. Level 28: Containing Browser Agents in Practice
    Run browser and computer-use agents in throwaway, isolated browser environments with domain allowlists, separate credentials, confirmation before risky actions, and a screenshot record of every step.
    • Start a disposable sandboxed browser that only reaches allowlisted domains
    • Step in before form submissions, purchases and logins, and send them to the approval gate
    • Record screenshots and actions for every step so a run can be audited later
  29. Level 29: OpenTelemetry GenAI Conventions: Model Calls
    Instrument model calls with the OpenTelemetry GenAI semantic conventions (span names, gen_ai.* attributes, token usage), noting that they are still in Development status and that attribute names can change between versions.
    • Emit a correctly named model-call span with provider, model, token-usage and finish-reason attributes in Python and TypeScript
    • Pin and record which version of the conventions your instrumentation follows, and plan for migrating to newer versions
    • Compare spans from Claude, OpenAI, Gemini and open-weight model calls in one trace viewer
  30. Level 30: Tracing a Whole Agent Run End to End
    Build one connected trace for an agent run, with agent-invocation and tool-execution spans, by carrying trace context across queues, durable workflow steps and the sandbox boundary.
    • Model an agent run as nested agent-invocation, model-call and tool-execution spans
    • Carry W3C trace context through a queue, a workflow engine and code running in a sandbox
    • Keep traces readable when a durable run is retried or resumed hours later
  31. Level 31: Capturing Prompts Safely: Content, Privacy, Sampling
    Decide what prompt and completion content to record, and how: opt-in content capture, redacting secrets and personal data, retention periods, and sampling choices that keep debugging possible without leaking data or overspending.
    • Turn on GenAI content capture as opt-in, redacting secrets and personal data before export
    • Set up sampling so that every failed or expensive run is kept while routine successes are sampled
    • Set retention and access rules for traces that contain user data
  32. Level 32: Telemetry Pipelines and Agent Observability Tools
    Route agent telemetry through an OpenTelemetry Collector to one or more backends, and weigh vendor-neutral OTel against OpenInference and the native SDKs of LLM observability tools.
    • Configure an OpenTelemetry Collector to process and fan out GenAI traces to two backends
    • Compare OpenTelemetry GenAI conventions with OpenInference and with proprietary SDKs on lock-in and coverage
    • Build a dashboard of run success rate, latency, token usage and tool error rates
  33. Level 33: Replaying and Debugging Failed Runs
    Record model responses and tool results so a failed agent run can be replayed step by step offline, then branched from any step to test a fix.
    • Record a run's model and tool inputs and outputs well enough to replay it deterministically
    • Replay a failed run from a chosen step with a changed prompt, model or tool
    • Use durable-execution event history alongside traces to find where a run went wrong
  34. Level 34: From Production Traces to Regression Tests
    Turn failed and edge-case production runs into a growing regression suite, so fixes stay fixed when prompts, models or tools change.
    • Pull failing traces into versioned test cases with clear checks on the expected outcome
    • Run the suite in CI against replayed tools whenever a prompt, model or policy changes
    • Spot silent quality regressions after switching model versions
  35. Level 35: Living Within Provider Rate Limits
    Understand request and token rate limits across providers, read the rate-limit headers and error responses, and shape traffic with client-side token buckets and concurrency caps shared across many agents.
    • Parse rate-limit headers and 429 responses from different providers into one internal signal
    • Build a shared token-bucket limiter that many concurrent agent runs respect
    • Give interactive traffic priority over background agent work when capacity is short
  36. Level 36: Retries, Timeouts and Retry Budgets
    Retry the right failures with exponential backoff and jitter, set timeouts for streaming and long calls, and stop SDK retries, application retries and workflow-engine retries from multiplying into a retry storm.
    • Sort provider and tool errors into retryable, non-retryable and should-fall-back
    • Set connect, first-token and total timeouts for streaming model calls
    • Align SDK, application and durable-engine retry settings so a single failure doesn't set off a retry storm
  37. Level 37: Fallbacks Across Providers and Models
    Fail over between Claude, OpenAI, Gemini and self-hosted open-weight models using circuit breakers, while handling differences in tool-calling formats, context limits and behaviour that make a backup model not quite equivalent.
    • Build a provider-neutral interface for chat and tool calls with adapters for at least two vendors
    • Add a circuit breaker that sends traffic to a fallback model and recovers automatically
    • Run the regression suite against fallback models to find where their behaviour differs
  38. Level 38: Model Gateways: Centralising Access and Control
    Put a model gateway between agents and providers to centralise keys, routing, limits, fallbacks and logging, and weigh self-hosted against managed gateways on latency, lock-in and how much risk they concentrate in one place.
    • Route agent traffic through a gateway that keeps provider keys out of the agent runtime
    • Set per-team or per-tenant limits and fallback routes in the gateway
    • Assess the gateway as a single point of failure and plan for its outages
  39. Level 39: Token Budgets and Hard Spend Limits
    Measure cost from each provider's usage fields and enforce per-step, per-run and per-tenant token and dollar budgets that stop a runaway agent before the bill arrives.
    • Calculate the cost of each call and each run from usage data, including reasoning and cached tokens
    • Enforce hard budgets that end or pause a run cleanly when they are exceeded
    • Alert on unusual spend per run, agent and tenant
  40. Level 40: Prompt Caching for Long Agent Loops
    Structure agent prompts so stable prefixes such as system prompt, tool definitions and long context get cache hits, and compare explicit and automatic caching across providers using their current official pricing pages.
    • Arrange prompts and tool definitions so the cacheable prefix stays stable across turns
    • Measure cache hit rate and actual savings from cached-token usage fields
    • Compare explicit cache markers with automatic caching, including write costs, minimum prompt sizes and cache lifetimes
  41. Level 41: Right-Sizing Models: Routing Routine Steps to Cheaper Tiers
    Learn to send routine agent steps such as classification, summarising tool output and formatting to smaller or open-weight models, keep frontier models for planning and hard reasoning, and use evals to prove the cheaper route has not quietly lowered quality.
    • Build a step-level model router in Python or TypeScript that picks a Claude, OpenAI, Gemini or open-weight model by task type, and log each choice as a span attribute on the trace
    • Run a small eval set against the frontier and the cheaper model for one routine step, and decide from measured cost per task and pass rate whether to switch
    • Set an escalation rule that retries a step on the larger model when the smaller one fails a schema check or a confidence check, and cap how often it can escalate so costs do not creep back up
  42. Level 42: Kill Switches: Stopping Agents Fast and Safely
    Design layered kill switches: per run, per tenant, per tool and global. They stop agents mid-flight without corrupting durable state or leaving side effects half done, and they can be tested before the day you need them.
    • Add a kill-switch check, backed by a feature flag or config store, at the agent loop boundary and before every side-effecting tool call, and show that a durable workflow cancels cleanly and can be inspected afterwards
    • Revoke an agent's scoped credentials and block sandbox egress as a second, independent stop that still works when the orchestrator is unhealthy
    • Run a game-day drill that trips each switch level and records how long it took to stop, plus any side effects that leaked through
  43. Level 43: Agent Incident Response: Runbooks and Postmortems
    Turn traces, budgets and gates into an incident process built for agents: detect runaway spend, injection-driven actions or bad changes, contain them, rebuild the incident from replayed traces, and write a postmortem that fixes the platform rather than blaming the prompt.
    • Write alert rules for agent-specific signals, such as a spike in spend per run, repeated tool-call loops, a sudden jump in approval-gate denials and unexpected egress attempts
    • Use stored traces and replay to rebuild the timeline of a failed or harmful run, including which model output proposed each action and which policy allowed it
    • Produce a runbook and a blameless postmortem template that sort incidents by root cause (model, tool, policy, credential or infrastructure) and turn each one into a guardrail or test
  44. Level 44: Multi-Agent Coordination Without Runaway Loops
    Coordinate many agents at scale with orchestrator-worker and queue-based patterns. Shared budgets, leases and work claims stop duplicate or conflicting work, and hop limits and loop detection stop agents from triggering each other forever. Practice here is still unsettled.
    • Implement a work-claim system with leases and idempotency keys on a durable queue, so two agents cannot edit the same resource or repeat the same side effect
    • Carry a budget and a hop count in the context passed to every sub-agent, so the whole tree stops when either runs out, and show that one trace links the parent and child spans
    • Compare a single agent with an orchestrator and parallel workers on one task, measuring cost, latency and conflicts, and explain when multi-agent is not worth the extra complexity
  45. Level 45: Capstone Part 1: Architecture and Sandboxed Deployment
    Plan and deploy the capstone background agent: choose a sandbox and a durable-execution engine, write the threat model, and get a long-running agent loop running in an isolated sandbox with locked-down egress and no long-lived secrets.
    • Write a one-page design doc covering the threat model, the sandbox choice and its trade-offs, the durable-execution engine, the tool list with idempotency notes, and the side effects that need approval
    • Deploy the agent as a background job that runs in a sandbox, with egress limited to an allowlist and credentials issued as short-lived scoped tokens
    • Show that the run survives a forced worker restart by resuming from durable state without repeating any completed tool calls
  46. Level 46: Capstone Part 2: Gates, Traces and a Hard Budget
    Add the control and visibility layers to the capstone agent: a policy engine and human approval for risky actions, OpenTelemetry GenAI traces across every model and tool call, and a hard token and spend budget enforced by the platform rather than the prompt.
    • Put a policy check in front of every tool call, plus a human-approval gate that pauses the durable workflow for deletes, payments or production changes and resumes it after a decision
    • Instrument the agent with OpenTelemetry GenAI conventions so a single trace shows model calls, token usage, tool calls, policy decisions and approvals
    • Enforce a per-run budget that blocks further model calls once it is used up, with a gateway fallback to a second provider when the first is rate-limited
  47. Level 47: Capstone Part 3: Failure Testing and Hardening
    Test the capstone agent under realistic failures, including provider outages, rate limits, crashed workers, prompt-injection attempts, budget exhaustion and kill-switch trips, then fix what breaks and record the evidence.
    • Run a failure-injection suite (forced 429s and timeouts, a killed worker, a malicious document carrying injected instructions, a blocked egress attempt) and record how the agent responds to each
    • Confirm from traces that no side effect ran twice, no gated action ran without approval and no run went over its budget
    • Write a short hardening report listing each failure found, the fix applied and the regression test that now guards it
  48. Level 48: Final Challenge: Production Agent Platform Review Exam
    A comprehensive final challenge covering the whole course. Review a flawed production agent design and its traces, find the weaknesses in isolation, durability, control, observability, cost and incident readiness, and propose a fix for each.
    • Audit a given agent architecture and say where its sandboxing, egress, secrets, idempotency, policy gates or approval flows fall short, giving a concrete fix for each
    • Diagnose a failed run from its traces and cost data, name the root cause, and choose the right response from retries, a fallback, a kill switch or a policy change
    • Defend trade-off decisions, such as microVM versus container, a durable engine versus a plain queue, and a cheap model versus a frontier model, and say plainly where industry practice is still unsettled

Access

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor. Every level, the podcast edition and the AI tutor come with All Access at £4.99/month or any Creator plan — see pricing.

Read lesson 1 free →

More like this