Structuring the Training Loop Clock When a Real API Is Your Environment Step
Decoupling rollouts from the trainer keeps slow APIs from stalling GPUs.

To use an API as an RL environment, connect action execution, state inspection, and reset through a rollout service rather than embedding API orchestration in the trainer. Schedule rollouts asynchronously, isolate each episode’s state, and compute rewards from verified outcomes. The training loop must handle latency that varies, side effects that build up, and external concurrency limits, so it cannot treat environment steps as ticks of a fixed-interval clock.
Why the classic RL training clock breaks when the environment is a real API
The classical RL loop assumes that the environment lives inside the training process. Its synchronous reset() and step() calls operate in memory, respond in microseconds, and are effectively free. Thousands of environment copies can run in a single process, sometimes on a single GPU. That arrangement makes synchronized execution practical. The trainer can advance environments together without spending much of its time waiting for them.
An API-backed environment breaks that timing assumption. Unlike CartPole in the trainer’s memory, a coding agent needs a machine with a filesystem, a shell, and processes that survive between calls. That machine becomes the rollout unit, and its execution time depends on the work performed inside it. An external API adds latency controlled by another system. As a result, rollout batching, GPU scheduling, and state management need a different architecture.
What makes an API environment step structurally different from an in-memory simulator step
The response to an API call may show the effects of every write made before it but reveal only part of the state. A fixed response cannot represent that history. A stateless mock that returns “captured” before capture occurs teaches the agent a sequence that the real API would reject. For training, the environment must keep the effects of earlier actions while showing the agent only what its interface exposes.
Apple’s LOOP paper formalizes this interaction as a partially observable Markov decision process. Its 32-billion-parameter agent, trained in AppWorld, outperforms the much larger OpenAI o1 agent by 9 percentage points. AppWorld supports interactive coding with API calls through direct function calls or REST against a stateful multi-app environment. This is a concrete result from environment-based training. The partial-observability framing describes the conditions under which the agent learns, rather than an abstract complication added to the task.
Variable latency and external parallelism constraints break two further assumptions. When interactions run in sequence, each can take a very different amount of time, so a synchronized batch leaves fast workers waiting for slow ones. Rate limits, credential scoping, and shared state restrict safe concurrency, while two agents reading and updating the same resource can produce lost writes. The training system must therefore track how much compute is available and how much parallel work the environment can safely take on.
Why coupling rollout orchestration to the training loop makes all three problems worse
Embedding rollout orchestration inside the trainer binds two different resource profiles. Rollout execution is I/O-intensive, involving sandbox creation, long-lived tool sessions, and coordination across concurrent instances. Training is GPU-intensive, involving forward and backward passes and gradient synchronization. Their waiting conditions are fundamentally different. When one loop controls both workloads, a delayed environment response can stall GPU work that depends on completing the batch.
ProRL Agent identifies conflicting system requirements and difficulty migrating either side as consequences of this coupling. The conflict extends beyond immediate utilization. Adding a runtime, API integration, or fault-injection mode can require changes that propagate into training code, making environment improvements harder to separate from trainer changes. SkyRL-Agent identifies a related scheduling failure in naive asynchronous batching, where the dispatcher waits for the slowest rollout before releasing the next wave. Asynchrony inside a batch does not remove the barrier between batches, so the slowest environment interaction still governs the pace.
How to connect a real-world API to an RL training loop with rollout as a service

ProRL implements rollout as an independent HTTP service. The trainer submits task instances and receives completed trajectories and rewards, while the service handles environment execution, tool use, evaluation, and inference coordination. This creates a distinct orchestration boundary. API calls can now run outside the trainer’s control flow, though the training data still needs their results to be complete. The service can manage their variable duration without making every request a synchronous trainer operation.
The rollout service must also own the environment lifecycle. Microsoft’s MAI-Thinking-1 creates a fresh container for each agentic task and destroys it when the task ends, while Liquid AI’s LFM2.5 gives the sandbox its own place in the pipeline. Isolation belongs at this service boundary. For API-backed tasks, that ownership includes tool sessions, outcome evaluation, and enforcement of rate limits and concurrent session caps. Those controls take more than a container of its own.
Kimi K3 describes “million-token agentic RL with persistent rollout and sandbox states” and uses “resumable microVM sandboxes” to preserve long-lived model and environment state. Checkpointing must extend beyond the model’s weights. Files, processes, and history are part of the world in which the next action will occur. A rollout service that can only create and destroy environments cannot meet that requirement, even if it provides adequate isolation for short tasks.
How to batch and schedule rollouts when API latency is variable and unpredictable
In bounded asynchronous batching, the dispatcher sends a wave of requests and waits for every result before releasing another wave. The batch still has a synchronization barrier. A rollout delayed by an API response or retry holds up new work even after other rollouts have finished. Decoupling moves this failure out of the trainer, but leaves the timing problem intact.
An asynchronous pipeline removes that wave-by-wave dependency. The gain comes from changing dispatch while keeping the training algorithm unchanged. For API-backed environments, the relevant principle is that slow responses should not prevent completed rollouts from making room for further work. GPU utilization then depends on how effectively the dispatcher coordinates available rollout work and generation.
If an API restricts request throughput, the rollout service must queue work within that allowance while allowing the rest of the batch to proceed. Concurrency also needs a state-aware boundary. Writes scoped per agent or per rollout prevent independent rollouts from overwriting each other’s changes to a shared resource. Scheduling therefore has to account for both request capacity and state isolation, because an apparently busy pipeline can otherwise generate invalid experience.
Structuring rollout episodes when stateful API side effects accumulate across steps
Resetting an API-backed episode means restoring a known environment state. A sequence of writes may need to be undone before another episode can begin from the same conditions. Isolation provides a cleaner reset boundary. Each rollout can start in its own sandbox, use it once, and replace it when the episode ends. The reset() operation then becomes part of environment provisioning.
The starting state must also be useful for learning. Pre-seeded realistic data exposes the agent to the kinds of records and relationships it will encounter in production, whereas an empty environment does not provide that distribution. Known data also supports later outcome verification. Kimi’s resumable sandboxes keep the API-side state needed to pick up an interrupted long-horizon episode, which a fresh starting point would lose.
Each episode needs a set limit on the number of steps. A discount factor close to 1 gives little preference to prompt completion, so relying only on the agent’s willingness to stop can produce impractically long trajectories. The step limit and discount factor must be chosen together, and because API latency varies, wall-clock duration does not consistently measure how much chance an agent has to act. When agents share state, one agent’s write may erase another’s work, so the rollout service must enforce write scoping to keep that interference from shaping the reward for the action being evaluated.
Designing reward signals when the environment’s state is the only ground truth
An API action does not establish whether the task succeeded. The reward function must inspect the resulting state after the action sequence and evaluate the domain’s actual success conditions. The scalar reward is what the agent optimizes. A CRM agent that creates a task with the right field values but the wrong assignee may score well if the verifier checks fields without checking ownership. That gap limits training progress regardless of how well the optimizer follows the supplied signal.
The rollout service therefore needs a state-inspection interface that lets a verifier query the outcome, as well as an action-execution interface. Verifiability makes an environment useful for training. GLM-5 constructs over 10k verifiable environments across thousands of repositories, making outcome evaluation part of the environment infrastructure at scale. The breadth of available tasks is useful only when their completion can be judged reliably.
Fault injection makes this judgment more demanding. If a rollout encounters an injected 429 or 503, the reward function must distinguish a policy failure from an environment condition when evaluating the result. The fault must be visible to the verifier. Deterministic injection and trajectory labels give the verifier the context it needs to judge how the agent behaved under the imposed condition. Without that context, resilience training cannot reliably tell whether the policy mishandled a situation it could have recovered from or the environment kept it from finishing.
What the simulator must provide to make API-backed RL training practical

A practical API simulator must keep state throughout the rollout and allow that state to be checked afterward. The add-list-delete cycle is the minimum behavioral test, with a record appearing after creation and disappearing after deletion. The sequence must be internally consistent. More complex workflows need this same consistency, because later actions must see the effects of earlier ones.
Isolation must remain intact as rollout concurrency grows. Cursor’s training of Composer required hundreds of thousands of concurrent sandboxed environments in the cloud, illustrating the scale the surrounding infrastructure may need to support. Shared-state leakage invalidates that parallelism. Each instance must also begin with realistic, known data so that learning conditions are useful and expected outcomes are computable. For long-running episodes, the same isolation boundary must allow checkpointing and resumption as well as disposal.
The simulator must make failure conditions reproducible. Required fault modes include latency, 429s, 503s, malformed responses, and connection resets, with deterministic injection and labels in the trajectory. Latency exercises the rollout pipeline, while labeled faults let the verifier evaluate behavior under known adverse conditions. They are part of the training environment’s semantics.
The simulator must be checked against the real API on an ongoing basis to keep those semantics true to it. A simulator that drifts can reward workflows the production system rejects, creating confidence without generalization. The training environment must run locally or in CI without live credentials or using up the live API’s rate-limit budget, because real API limits leave too little room for hundreds of thousands of concurrent rollouts. The prerequisite for production-relevant learning is therefore a stateful, isolated, verifiable simulator that reproduces API behavior without making production access the training clock.


