Over the past few months, daily task volume on Qoder Cloud Agents (QCA) grew a hundredfold, from the hundred-thousand range three months ago to more than 20 million. To support that growth, we rebuilt our orchestration and sandbox infrastructure. After more than three months of validation in production, P99 session startup latency was below 500 milliseconds, a single user could run 10,000 tasks concurrently, and overall sandbox cost fell to about 1% of the always-on baseline. With the same underlying model, our end-to-end effective-task score was 15.7 points higher than that of a comparable managed platform.


1. Why can’t “Agent in Sandbox” handle a hundredfold increase in scale?
One common way to deploy a cloud agent is Agent in Sandbox. The model-call and tool-dispatch loop (the harness), session state, and local toolchain all run in the same container or microVM, giving each session its own execution environment. It is a convenient starting point. The agent can read and write files directly, runtime state lives in the process, and there are no interfaces between services to design up front. But as tasks run longer and concurrency rises, that convenience becomes a constraint: if the task is to continue, the container hosting it cannot simply exit.
Production tasks often extend beyond a single online conversation. A code commit, a schedule, or a business event might trigger a task, and it might keep running after the user closes the page. The platform needs to let tasks outlive the client connection and resume after a process exits or a machine fails. Moving an agent to the cloud does not solve those problems by itself. Meanwhile, the sandbox is not working the whole time a task is alive. The agent may be waiting for a model response, a remote API, or human confirmation. If session state lives only in the container process’s memory, the platform cannot reclaim the container even when there is no local code to execute. As concurrency grows, the number of environments we have to keep depends more on how many tasks are unfinished than on how many are actually using a sandbox. Resource reclamation and task recovery pull in opposite directions:
- Keeping the container means continuing to reserve memory and other resources.
- Reclaiming it means solving state persistence, environment reconstruction, and execution resumption.
| Load dimension | 100,000 tasks per day (1×) | 20 million tasks per day (200×) | Bottlenecks to test |
|---|---|---|---|
| Task admission | Average ~1.2/s; peak ~6–9/s | Average ~231/s; peak ~1,200–1,850/s | Admission backpressure, scheduling shards, and hot session state |
| Command scheduling | Estimated peak ~30–74/s | Estimated peak ~6,000–15,000/s | Head-of-line blocking, hot partitions, and database lock contention |
| Streaming event writes | Before coalescing, estimated peak ~5,800–9,300/s | Before coalescing, estimated peak ~1.16–1.85 million/s | The cost of persisting individual fragments and contention with control-state updates |
| Sandbox concurrency | ~140–220 occupied sandboxes at peak | ~28,000–44,000 occupied sandboxes at peak | Provisioning speed, quotas and capacity distribution, reclamation lag, and orphaned instances |
Concurrent sandboxes ≈ task arrival rate × fraction of tasks using a sandbox × average occupancy time.Daily task volume alone therefore cannot tell us how many containers we need. Under the assumptions above, if every task that uses a sandbox creates a new environment and keeps it for 24 hours, the steady-state inventory reaches about 8 million. If average occupancy can be kept to 60 seconds, peak occupancy is in the tens of thousands. The difference comes from the retention policy, with task volume held constant. That makes the scaling problems concrete. Admission needs backpressure. Scheduling needs to avoid hot spots and blocking. The event path needs to distinguish control state from high-frequency output. The sandbox layer needs predictable provisioning and reclamation. Decoupling lets us address these separately, but each path still needs its own capacity design and overload protection. Seen in a longer historical context, the path cloud agent infrastructure has taken looks remarkably like the evolution from monolithic databases to distributed cloud-native databases:
Three generations of cloud agent infrastructure: 1.0 Monolithic → 2.0 Decoupled → 3.0 Serverless Harness
2. Serverless Harness: separating state, compute, and storage as in a cloud-native database
The two defining characteristics of serverless are event-driven execution and elasticity on demand. Borrowing the ideas of separate storage and compute and stateless compute nodes from distributed cloud-native databases, QCA turned its agent orchestration layer into a Serverless Harness with two clear architectural boundaries:
- Separate stateful and stateless components. Session history and task progress live in the database. A message queue (MQ) handles transitions and waits between steps. The harness workers that actually execute the work are stateless. A worker no longer owns a loop spanning multiple turns. It takes one atomic command from the queue, performs one inference or tool call, writes the result to the event bus, and immediately returns to the pool to serve an unrelated task.
- Separate compute and storage. Container CPU and memory are needed only during execution and can be reclaimed afterward. Workspace code, dependencies, and intermediate files live on independent cloud disks, in snapshots, and in object storage. Destroying a container does not destroy them. When the task needs them again, a new container can mount the workspace and continue.
- Route each step to the resource it needs; tasks without sandbox work skip the container wait. In practice, many steps need no sandbox. Initial inference, web retrieval, and remote business API calls take a sandbox-free fast path. Only when a local tool runs code or reads or writes files do we start a sandbox on demand in milliseconds. We can also batch consecutive file operations. After execution, a dynamic policy can quickly pause the sandbox to release compute and resume it on demand for the next tool call. Removing the container dependency from the other steps let us consistently keep QCA P99 session startup latency below 500 ms.
- Share stateless workers and scale independently. Because a worker is not tied to a session, many tasks can share compute at high density. Model inference, remote tools, and local sandboxes each scale according to their own utilization. A bottleneck in one component no longer means multiplying entire sets of containers.
- A single-node failure does not interrupt a long task. We persist session events and workspace files without relying on live migration of an entire process’s memory. Even if a worker suddenly crashes or is preempted, another worker in the shared pool can use the durable history to take over the next step in milliseconds.
- Drain nodes without disrupting tasks during releases or scale-down. When sessions lived in process memory, restarting for a release meant cutting off long tasks or waiting hours to deploy. With stateless, single-step execution, a departing node only drains the step it is running, usually a few seconds to a little over ten seconds. Other nodes naturally take the later steps. The platform can release frequently or scale down while long-running tasks continue without users noticing.
3. At peak traffic, the model is only one of the agent’s bottlenecks
Many teams expect model compute to account for all the bottlenecks in an agent platform handling tens of millions of tasks. As we scaled, the first bottlenecks we encountered were in the relational database and message queues the agent engine depends on. Here are some real examples of how they arose.
1. The typewriter effect and a million small database writes
Users like to see the agent stream its reasoning and replies as it produces them. In the capacity calculation above, writing each fragment to the database before pushing it to the client, as a conventional web app might, would immediately amplify peak load to on the order of a million database writes per second. Making a relational database absorb that load directly would overwhelm it with needless tiny writes.
We split preview from persistence, sent the first tokens straight through, and coalesced what followed. Incremental fragments form a live preview stream. They bypass the relational database and reach the frontend’s long-lived connection through lightweight publish/subscribe. Only when a text block, reasoning block, or tool call closes do we write it as a durable event. The database stores complete content instead of every intermediate stage of token generation.
On the push path, the worker adds no buffering to the first few frames, keeping time to first token low. It then combines later fragments from the same block over short windows to reduce the message count. The two optimizations cut database write frequency and push overhead, respectively. Relational database writes attributable to streaming fell below 1% of their previous volume, while the frontend kept its smooth typewriter effect.
Separating preview from persistence brought streaming database writes below 1% of their previous volume.
2. How can one slow session or one large customer hold up an entire queue?
Agent workloads naturally mix tasks of very different lengths. Requests arriving in the same second might include a simple question, a heavy code analysis that takes five minutes, and a large customer suddenly launching hundreds of thousands of batch tasks. Traditional fixed-partition ordered queues expose two problems at once. First, thousands of sessions hash to the same partition. Just one session at its head waiting on a model rate limit or slow tool can block hundreds of unrelated users. Second, at scale, a high-volume customer can consume all available processing capacity in one burst and starve ordinary users’ tasks.
LiteTopic dynamic queues: per-session ordering and fair consumption across users
We replaced the traditional fixed partitions with RocketMQ LiteTopic dynamic lightweight queues. We create queues at the granularity each workload needs and isolate them through fair consumption:- Choose the granularity dynamically: session or user. Where operations must occur in strict order within a session, we give each session an independent lightweight queue. This preserves order within a session and isolates sessions from one another. For concurrent multi-tenant scheduling, we create queues at the user (tenant) level and consume them fairly. A large customer can submit hundreds of thousands of batch tasks at once, but they drain from that customer’s queue according to its quota. Other users keep their turns, and low-volume users’ tasks avoid starvation.
- Suspend a single queue without dead-lettering tasks or holding up other users. When a tenant reaches a rate limit, upstream inference fluctuates, or a worker drains gracefully, the consumer does not return a failure. A failure would send an otherwise normal task to the dead-letter queue and interrupt it. Instead, the consumer suspends only the affected LiteTopic and redelivers after a quiet delay of tens to hundreds of milliseconds. Other users and sessions on the same machine continue at full speed.
3. Reassessing the cost of reliability at scale
Some early reliability measures needed a second look as the platform grew. Scanning tables, keeping a ledger, and retaining results all made sense individually. Repeating each operation for every command multiplied the overhead with scale. Here are a few of the engineering changes we made.
The control plane originally dispatched commands using a classic outbox. Pending commands were stored in the database, and a background job scanned for them periodically and delivered them to the message queue. This provided a durable record, but also made the database handle continuous polling. As command volume grew, scan overhead became noticeable, some queries risked becoming slow SQL, and a command entering the system had to wait for a scan before it could be sent.
We changed the normal path to dispatch asynchronously as soon as the state has been persisted. Only a failed send enters transactional compensation. This reduces both database polling and the wait before dispatch. The important change was removing continuous scanning from the normal path. Simply increasing the scan frequency would have put more pressure on the database.
We gave the execution layer’s deduplication ledger the same attention. Message queues occasionally redeliver. Executing the same command twice can mean paying for a second model call or, worse, performing a write twice. The original PostgreSQL deduplication table also stored large results for replay. At scale, large-field writes and row locks quickly became new bottlenecks. We moved the ledger to Redis. Each command uses a tiny hash recording who is running it, when it expires, and whether it finished. Identifying a duplicate command does not require storing its entire result.
Both changes redraw the database’s responsibilities on the main path. Business state that needs to persist still goes to the database. But every message delivery and every deduplication check need not involve the relational database. At scale, performance work means revisiting which reads and writes must happen and which extra operations can move off high-frequency paths, as well as making individual operations faster.
4. Three engineering decisions behind sandbox costs of about 1% of the always-on baseline
The orchestration layer handles task throughput at high concurrency, while sandbox infrastructure directly affects platform running costs. By moving from always-on compute to on-demand allocation and tiered reclamation, we reduced overall sandbox costs to about 1% of the always-on baseline. During one measurement period, sandbox expenses accounted for about one-thirtieth of the platform’s total cost.
Maintaining that cost level at scale means addressing three questions. How do we retain user data after reclaiming resources? How do we avoid interrupting work still in progress? And when an underlying operation fails, how do we ensure the resources are eventually released?
Sandbox cost optimization strategies
First decision: reclaim compute and keep the workspace
Enterprise tasks often last hours, even though they need a sandbox to execute commands for only a few minutes. To be clear, what users share is the stateless worker pool. By default, each session has its own strictly isolated sandbox and cloud disk, with no reuse across sessions (to support general-purpose workloads). We manage the sandbox lifecycle through three cost tiers. Creating a session does not allocate a container: it begins with no sandbox. A tool call starts one on demand. After execution, the current cluster compute utilization determines the reclamation schedule. At peak load or in a serverless pool, we can quickly pause to release compute. Off peak, a dynamic idle window keeps the container warm for the same session. When the window expires, we destroy the compute container and retain only its detached cloud disk. If the user returns within 24 hours, a new container can remount the original disk in seconds and continue with the same workspace.
After 24 hours, the cost of keeping the disk matters. Keeping every historical session’s cloud disk would leave millions of block-storage volumes accruing charges, offsetting some of the savings from reclaiming compute. But deleting the disk outright at expiry would lose the workspace if the user returned to continue the task.
We automatically take a cloud disk snapshot before deleting the disk. The system releases the original disk only after confirming that the underlying snapshot is ready. If the snapshot fails, it retains the disk for the next retry, prioritizing workspace recovery. When a user returns after the retention period, the system restores the workspace from the snapshot without manual intervention and cleans up the snapshot as soon as restoration finishes.
Second decision: dynamic idle reclamation and a dev server someone forgot to stop
For on-demand reclamation to save money without hurting the experience, the timing cannot be one-size-fits-all, and we must define what “idle” actually means.
We did not hard-code one idle timeout. Instead, we adjust the idle window according to current cluster compute utilization. Off peak, when compute is plentiful, we allow a longer window so successive interactions can reuse a warm container and avoid repeated starts and stops. At peak load, we shorten the threshold and reclaim idle sandboxes sooner, freeing their CPU and memory for new tasks and keeping overall compute cost down.
The more aggressively we reclaim, the more precisely we must identify idle sandboxes. Suppose an agent is running an eight-minute build or test script. If the inspection loop checks only for recent interactive requests, tightening the threshold at peak load could mark a working container as idle and destroy it, interrupting the task.
Conversely, the presence of a live process in a container is not sufficient reason to keep it alive. A dev server the agent started while debugging may never have been stopped. If any background process can block reclamation, a sandbox might hold compute indefinitely, defeating dynamic reclamation.
We therefore apply different keepalive rules to different operations. The server automatically renews keepalives for in-flight synchronous operations and proxied long-lived connections, revoking the corresponding keepalive as soon as the request ends. Detached background processes do not count as activity by default. A background batch job that really does need to keep running must ask the sandbox daemon for a time-limited keepalive lease, with a default of 30 minutes and a hard limit of two hours.
When a lease expires, it automatically stops blocking idle reclamation. In effect, the sandbox lifecycle itself becomes a tool the agent can call. The infrastructure no longer has to guess whether a running process is a legitimate batch job or a forgotten dev server. The agent explicitly declares the lease it needs. We can then shorten idle windows at peak load to control cost, without killing a long compilation in progress or letting a leftover development server occupy a sandbox indefinitely merely because its process is alive.
Third decision: smooth bursts with middleware and reconcile resources continuously
At 20 million tasks per day, business traffic often arrives in pulses. A large customer’s batch can trigger a flood of wake-up requests, followed by a wave of idle reclamations as demand subsides. Meanwhile, even if only one in ten thousand underlying cloud API calls times out or partially fails, hundreds of unclaimed “orphaned sandboxes” can be left behind each day. Over a month, they can consume a substantial share of cluster quota.
We follow three principles for elastic provisioning and resource cleanup at scale:
- When the sandbox layer cannot absorb a sudden burst of pause and resume operations, smooth it with middleware. The underlying infrastructure has a physical limit on how many concurrent pauses and resumes it can process in a short period. Rather than sending bulk wake-ups or reclamations straight through to its APIs, we use middleware such as message queues for asynchronous buffering and steady consumption. We absorb the peak first, then dispatch at the rate the sandbox pool can actually sustain. This protects underlying services from cascading timeouts while allowing business tasks to progress through a surge.
- Divert traffic when capacity is insufficient; return a failure when capacity is unknown. The platform manages both an elastic serverless sandbox pool and a larger multi-cluster Kubernetes fallback pool. Atomic reservations in short transactions control utilization. Overflow goes to the fallback pool only when the preferred pool is confirmed to have reached a threshold, such as 90% utilization. If fluctuating capacity metadata makes the current state uncertain, we return a failure rather than interpreting “unknown” as “full.” That prevents a large traffic shift to the backup pool from expanding a failure while the preferred pool’s status is unclear.
- A 200 response from the deletion API does not prove the underlying resources were released. We manage the intent to delete separately from the actual infrastructure state. Once persisted, the intent survives a temporary timeout from the underlying API. A background reconciliation loop checks the entire resource tree and marks deletion complete only after confirming that all associated resources are gone. The system also inventories resources from the infrastructure side to identify and clean up unowned assets missing from business records. Continuous reconciliation and reverse inventory have kept the orphaned sandbox rate below 1 in 100,000 over sustained operation.
5. After the harness went serverless, task quality actually improved
Breaking the system into so many parts raises an obvious question. We split the agent loop into a stateless execution pool, asynchronous queues, and on-demand sandboxes. Throughput went up and costs fell to 1%, but did the quality of the agent’s work suffer?
Our results went the other way. In an internal benchmark covering several kinds of real engineering and business tasks (eight evaluation sets, 310 cases per combination), we compared the end-to-end performance of the same underlying model on different managed harnesses:
| Evaluation (8 sets, 310 cases per combination) | Same-model baseline A · QCA | Same-model baseline A · comparison platform | Another primary model B · QCA |
|---|---|---|---|
| Mean effective-task score | 85.9 (+15.7 points) | 70.2 | 81.5 |
| Task invocation success rate | 96.8% (+19.1%) | 77.7% | 93.2% |
(Note: The platforms differ in their default parameters, tool configurations, and execution budgets. The figures reflect end-to-end delivery across each platform’s complete execution path rather than a model-only leaderboard comparison.)With the same model, effective-task scores differed by more than ten points and invocation success rates by nearly twenty percentage points. The reason is fairly simple. Many tasks fail because the environment trips up the model partway through work it is capable of doing. A compilation is reclaimed six minutes in. An external tool falters and the whole session errors out. Context gets abruptly truncated as the window fills. Locally, a person can retry. In an unattended cloud environment, these events can cause the task to fail outright. Once the platform takes care of context compression, per-session backoff and retries, long-task keepalives, and result checks, the model no longer spends its limited turns on errors and restarts. It can put those turns into the work itself. Scale itself brings another practical benefit. When each business built its own local or single-machine agent, the team that hit a problem had to deal with it alone. Now that 20 million tasks run on a common managed foundation every day, unusual edge cases surface daily. Each real failure we catch in production is promptly added to our offline evaluation set. Once a fix goes live, every business on the platform benefits the next day.