Skip to article
API429 / Field notes

Gemini Managed Agents: Sandbox Isolation, Token Budgets, and Quota Controls

Control multi-step token consumption, remote Linux sandbox lifecycle, and 429 retry risk when running Google Gemini Managed Agents and autonomous tool loops.

Hourglass and a queue of paper request cards
Editorial photo illustration: Hourglass and a queue of paper request cards. Topic: Gemini Managed Agents: Sandbox Isolation, Token Budgets, and Quota Controls.

An ordinary chat completion processes one prompt and returns one response. An autonomous agent session—such as Google's Gemini Managed Agents invoked via the Interactions API (client.interactions.create with environment="remote") or custom multi-step agent harnesses—can execute dozens of reasoning turns, shell commands, file mutations, and web searches from a single user trigger. Without dedicated admission caps and per-task token ceilings, a handful of concurrent agent sessions can exhaust project-wide input_TPM and RPM limits and starve interactive traffic.

This guide defines the application-side controls required for Gemini Managed Agents and multi-turn tool loops: distinguishing direct Google sandbox sessions from standard OpenAI-compatible gateway routes, bounding cumulative token and step budgets, isolating remote sandbox files, and preventing duplicate side effects on retry. Pair these controls with AI API cost guardrails and Gemini API queue admission design.

Separate direct Google Managed Agents from standard gateway chat routes

In Google's official Managed Agents documentation and agent environment guide, managed agents (including the general-purpose Antigravity agent built with Gemini 3.8 Flash and the Deep Research agent) run inside a Google-hosted Linux sandbox or custom configuration created via client.agents.create(). Each invocation forks the base environment so runs start clean, and applications can inspect or transfer files inside the remote sandbox.

Before designing your routing layer, separate what runs on direct Google Interactions endpoints from what runs on OpenAI-compatible gateway endpoints:

Capability or surface Direct Google Interactions & Agents API OpenAI-compatible gateway (POST /v1/chat/completions) Application engineering rule
Hosted Linux sandbox (environment="remote") Native support via Google interactions.create and agent-environment file APIs Not part of standard chat completions; client owns local/container sandbox execution Never assume a chat gateway provisions remote Google sandboxes unless explicitly documented in public OpenAPI
Token consumption profile Multi-turn reasoning, code execution, and file reads can span 100k to multi-million cumulative tokens Per-turn prompt + tool-call history grows quadratically if unpruned Reserve a task-level token ceiling before admitting an agent run, not just a single-turn estimate
State & file persistence Forked per invocation in Google's sandbox; artifacts must be downloaded explicitly Application-managed state store, git worktree, or object storage Checkpoint completed tool outputs so a 429 on turn 8 does not re-execute turns 1–7
Credential & secret hygiene Sandbox environment variables and uploaded files Client-side tool execution environment Never inject production master keys or unredacted customer secrets into an autonomous sandbox

When your own application orchestrates agent loops over standard chat or responses endpoints (for example, through Claude Code, Cursor, or n8n), inspect the API429 documentation, model catalog, and Google provider guide to verify supported endpoints and exact model IDs.

Enforce task-level admission, step caps, and checkpointed recovery

Why do agent workloads trigger HTTP 429 storms so much faster than chat? Because every reasoning step re-sends accumulated conversation history, tool outputs, and file diffs. If five agent workers each run a 12-step loop with 40,000 context tokens per step, they consume 2.4 million input tokens in a few minutes.

Guard agent queues with four strict invariants:

  1. Dedicated agent bulkhead: Never allow autonomous agent tasks to share an unsegmented semaphore with sub-second user chat. Cap concurrent active agent sessions separately.
  2. Hard step and cumulative token budgets: Track steps_completed, cumulative_input_tokens, and cumulative_output_tokens per task ID. Halt the loop and transition to human review or summarized handoff as soon as the task approaches its budget ceiling.
  3. Checkpoint every external side effect: Before an agent step writes to a database, creates a pull request, or mutates an external system, record an idempotency ledger entry. If a subsequent reasoning turn hits HTTP 429, resume from the last verified checkpoint after waiting out the retry budget cooldown instead of restarting the entire agent task from scratch.
  4. Deliver completion asynchronously when tasks run long: For multi-minute research or coding tasks, pair agent execution with webhook callback verification or durable polling rather than holding a browser HTTP request open. Furthermore, log every tool invocation, sandbox file download, and cumulative token delta in your rate-limit observability pipeline so operators can audit exactly which step consumed the task budget.

Runnable offline Python agent task budget and checkpoint supervisor

The following self-contained Python 3.10+ module evaluates whether an autonomous agent session can advance to its next reasoning turn or must pause, checkpoint, or terminate based on cumulative tokens, step count, and cooldown state:

from __future__ import annotations
from dataclasses import dataclass, field


@dataclass
class AgentTaskState:
    task_id: str
    max_steps: int
    max_cumulative_tokens: int
    deadline_epoch: float
    steps_completed: int = 0
    cumulative_tokens: int = 0
    last_checkpoint_id: str = "init"
    completed_tool_ids: set[str] = field(default_factory=set)


@dataclass(frozen=True)
class StepSupervisorDecision:
    action: str          # "execute_turn", "defer_from_checkpoint", "halt_budget_exhausted"
    resume_checkpoint: str
    remaining_tokens: int
    remaining_steps: int
    reason: str


def evaluate_agent_turn(
    task: AgentTaskState,
    *,
    next_turn_estimated_tokens: int,
    cooldown_remaining_s: float,
    min_turn_duration_s: float,
    now_epoch: float,
) -> StepSupervisorDecision:
    remaining_steps = task.max_steps - task.steps_completed
    remaining_tokens = task.max_cumulative_tokens - task.cumulative_tokens
    remaining_time = task.deadline_epoch - now_epoch

    if remaining_steps <= 0:
        return StepSupervisorDecision(
            "halt_budget_exhausted", task.last_checkpoint_id, remaining_tokens, 0, "max_steps_reached"
        )
    if next_turn_estimated_tokens > remaining_tokens:
        return StepSupervisorDecision(
            "halt_budget_exhausted", task.last_checkpoint_id, remaining_tokens, remaining_steps, "cumulative_token_cap_exceeded"
        )
    if remaining_time < cooldown_remaining_s + min_turn_duration_s:
        return StepSupervisorDecision(
            "halt_budget_exhausted", task.last_checkpoint_id, remaining_tokens, remaining_steps, "task_deadline_exceeded"
        )
    if cooldown_remaining_s > 0.0:
        return StepSupervisorDecision(
            "defer_from_checkpoint", task.last_checkpoint_id, remaining_tokens, remaining_steps, "wait_for_rate_limit_cooldown"
        )
    return StepSupervisorDecision(
        "execute_turn", task.last_checkpoint_id, remaining_tokens - next_turn_estimated_tokens, remaining_steps - 1, "turn_admitted"
    )


def record_turn_checkpoint(
    task: AgentTaskState,
    *,
    checkpoint_id: str,
    tokens_used: int,
    tool_call_id: str | None = None,
) -> None:
    task.steps_completed += 1
    task.cumulative_tokens += max(0, tokens_used)
    task.last_checkpoint_id = checkpoint_id
    if tool_call_id:
        task.completed_tool_ids.add(tool_call_id)


if __name__ == "__main__":
    session = AgentTaskState(
        task_id="agent-run-42",
        max_steps=8,
        max_cumulative_tokens=160000,
        deadline_epoch=500.0,
    )
    record_turn_checkpoint(session, checkpoint_id="ckpt-step-1", tokens_used=28000, tool_call_id="tool-read-repo")
    d_ok = evaluate_agent_turn(
        session, next_turn_estimated_tokens=32000, cooldown_remaining_s=0.0, min_turn_duration_s=5.0, now_epoch=120.0
    )
    d_429 = evaluate_agent_turn(
        session, next_turn_estimated_tokens=32000, cooldown_remaining_s=6.0, min_turn_duration_s=5.0, now_epoch=125.0
    )
    print("Turn decision (healthy):", d_ok)
    print("Turn decision (after 429 cooldown):", d_429)

Review model token pricing on /en/pricing and general service details in /en/faq before sizing your per-task token caps.

FAQ

How does Google's Gemini Managed Agent sandbox handle state between invocations?

In Google's Managed Agents documentation, each invocation via client.interactions.create forks the base environment so every run starts from a clean sandbox state. Any files generated during execution must be explicitly listed and downloaded from the environment before the session closes.

Why should agent retries resume from a turn checkpoint instead of restarting the task?

Restarting a multi-step agent task from turn 1 after a turn-7 HTTP 429 wastes all tokens spent on turns 1–6, amplifies project-level input_TPM pressure, and risks repeating non-idempotent tool actions. Resuming from the last verified checkpoint preserves completed work.

Can one runaway agent loop cause 429 errors for unrelated chat users?

Yes. In direct Google Cloud projects, RPM, input_TPM, and RPD apply at the project level. If autonomous agents and live user chat share the same project or local worker pool without separate bulkheads and token caps, a single long-context agent loop can saturate input_TPM.

How should we size the token budget for a managed or custom agent task?

Set both a per-turn input token ceiling (pruning or summarizing old tool outputs) and a cumulative task token ceiling (for example, 150,000 to 500,000 total tokens depending on task complexity), and halt the loop automatically if either limit is reached.

Sources & further reading

  1. Google Gemini API Managed Agents overview
  2. Google Gemini API agent environment guide
  3. Google Gemini API custom agents guide
  4. Google Gemini API rate limits
  5. API429 customer documentation
  6. Current API429 public OpenAPI
  7. API429 public catalog contract

Put the next step into practice.

Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

Telegram