DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

Queueing agent runs against a concurrency cap: backpressure, fairness and limit errors

The first version of most agent backends starts a sandbox whenever a request arrives. It works until the day twenty users click at once, or one user's agent fans out into fifty parallel tool calls. Then starts begin to fail with limit errors, the agent retries them, and the retries make it worse.

Every sandbox platform has a concurrency cap. On Sandscale it is the number of boxes running at once, which the pricing page lists per plan: 3 on Free and 30 on the first paid tiers. Your backend needs to treat that cap as a resource it schedules, not as an error it occasionally hits. This post builds a small queue that does.

What the queue has to do

  1. Never start more than the cap. Keep a count of running jobs and only start a new one when there is a free slot.
  2. Share slots fairly. One user's agent that submits fifty jobs should not make everyone else wait behind it.
  3. Apply backpressure. When the queue itself is full, refuse new work at the door with a clear message, instead of growing without limit.
  4. Tell limit errors apart. "No free slot right now" means wait. "This month's allowance is used up" or "someone pulled the kill switch" means waiting will not help.
  5. Adapt when the cap is lower than you thought. Another service sharing the organization, a plan change or sandboxes leaked by a crashed process can all leave fewer free slots than your configuration says.

Know your limits

The API can tell you where you stand. GET /api/v1/sandbox/quota returns active_instances and max_instances, along with vCPU and memory use against their maximums, per the API reference. It needs the sandboxes:create permission. Reading it at startup is a better way to set maxConcurrent than a hardcoded number, and it shows you whether something else is already holding slots.

When a start is refused for a limit, the reference lists 429 quota_exceeded for POST /instances. The TypeScript SDK raises those as LimitExceededError with a retryAfterMs taken from the Retry-After header when the server sends one. Two of its subclasses matter for scheduling. FreeMonthlyLimitError means the Free allowance for the billing period is used, and it renews at a date the error carries. KillSwitchError, a separate class, means the organization stopped its agents on purpose.

The queue

This uses @sandscale/sdk 1.0.0. Each job runs a Python program in its own sandbox and resolves with its output.

import { Sandscale, LimitExceededError, FreeMonthlyLimitError, KillSwitchError } from '@sandscale/sdk';

type Job = { tenant: string; code: string; attempts: number; resolve: (out: string) => void; reject: (e: unknown) => void };

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export class RunQueue {
  private queues = new Map<string, Job[]>(); // one FIFO per tenant
  private order: string[] = []; // round-robin over tenants with waiting jobs
  private active = 0;
  private limit: number;
  private halted: Error | undefined;

  constructor(private sandscale: Sandscale, private maxConcurrent: number, private maxWaiting = 1000) {
    this.limit = maxConcurrent;
  }

  submit(tenant: string, code: string): Promise<string> {
    if (this.halted) return Promise.reject(this.halted);
    const waiting = [...this.queues.values()].reduce((n, q) => n + q.length, 0);
    if (waiting >= this.maxWaiting) return Promise.reject(new Error('queue full, try again later'));
    return new Promise((resolve, reject) => {
      this.enqueue({ tenant, code, attempts: 0, resolve, reject }, false);
      this.pump();
    });
  }

  private enqueue(job: Job, front: boolean) {
    const q = this.queues.get(job.tenant) ?? [];
    if (front) q.unshift(job);
    else q.push(job);
    this.queues.set(job.tenant, q);
    if (!this.order.includes(job.tenant)) this.order.push(job.tenant);
  }

  private next(): Job | undefined {
    const tenant = this.order.shift();
    if (tenant === undefined) return undefined;
    const q = this.queues.get(tenant)!;
    const job = q.shift()!;
    if (q.length > 0) this.order.push(tenant); // back of the line, so other tenants get a turn
    else this.queues.delete(tenant);
    return job;
  }

  private pump() {
    while (!this.halted && this.active < this.limit) {
      const job = this.next();
      if (!job) return;
      this.active++;
      void this.execute(job).finally(() => {
        this.active--;
        this.pump();
      });
    }
  }

  private async execute(job: Job) {
    let boxId: string | undefined;
    let region: string | undefined;
    try {
      const box = await this.sandscale.sandboxes.create({ template: 'builtin:python', timeoutSeconds: 900 });
      boxId = box.id;
      region = box.region;
      // A slot worked, so creep back toward the configured limit.
      this.limit = Math.min(this.maxConcurrent, this.limit + 1);
      await this.sandscale.sandboxes.writeFile(box.id, '/workspace/main.py', job.code, { region });
      const run = await this.sandscale.sandboxes.run(box.id, ['python3', 'main.py'], { region, timeoutSeconds: 300 });
      job.resolve(run.stdout);
    } catch (err) {
      if (err instanceof KillSwitchError || err instanceof FreeMonthlyLimitError) {
        this.halt(err); // waiting will not help; stop and tell a person
        job.reject(err);
      } else if (err instanceof LimitExceededError && !boxId && job.attempts < 5) {
        // Refused at start: the cap is lower than we thought. Shrink, wait, and put the job back in front.
        this.limit = Math.max(1, this.active - 1);
        job.attempts++;
        await sleep(err.retryAfterMs || Math.min(30000, 1000 * 2 ** job.attempts));
        this.enqueue(job, true);
      } else {
        job.reject(err);
      }
    } finally {
      if (boxId) await this.sandscale.sandboxes.stop(boxId, { region }).catch(() => undefined);
    }
  }

  private halt(err: Error) {
    this.halted = err;
    for (const q of this.queues.values()) for (const job of q) job.reject(err);
    this.queues.clear();
    this.order = [];
  }
}
Enter fullscreen mode Exit fullscreen mode

How it behaves

Slots

active counts running jobs and limit is how many may run. pump() starts jobs until the two meet, and every job that finishes calls pump() again, so a freed slot is used without a timer or polling loop.

Fairness

Jobs wait in one FIFO per tenant, and order cycles through tenants that have work. After a tenant's job starts, the tenant goes to the back of the line. If tenant A submits six jobs and tenant B submits two, they start interleaved instead of B waiting for all of A's. A tenant can be a user, a workspace or a customer; pick the unit whose waiting you care about.

Backpressure

submit() refuses new work once maxWaiting jobs are queued. A refusal at submit time is easy to show to a user or an agent: "busy, try again shortly". A queue that grows without bound turns a burst into an outage, where every job eventually times out.

Refused starts

If create fails with a LimitExceededError, the job never got a sandbox, so it is safe to try again. The queue shrinks its own limit below the current number of running jobs, waits for the time the server asked for, or backs off exponentially when it did not say, and puts the job back at the front of its tenant's line. Each successful start raises limit by one again, back toward the configured maximum. This is the same idea TCP uses for congestion: back off quickly, recover gradually.

The check !boxId matters. A limit error after the sandbox started is a different situation and is not retried here.

When to stop

A FreeMonthlyLimitError or a KillSwitchError halts the whole queue: every waiting job is rejected with that error and new submissions are refused. Retrying either would produce a stream of identical refusals. The right response is a message to a person: upgrade or wait for the period to renew, or find out why the kill switch is on. Our post on kill switch design covers how clients should react to it.

Cleanup

Every job stops its sandbox in finally, and each sandbox has a timeoutSeconds lifetime as a backstop. Leaked sandboxes are the most common reason the real free capacity is lower than the configured cap, so both halves matter.

Beyond one process

This queue lives in memory, which is fine for a single worker. With several workers sharing one organization's cap, you need the counter in a shared place: a database row with a conditional update, a Redis semaphore, or a single dispatcher process that owns the queue. The rules stay the same: count slots, share them fairly, refuse at the door, retry only refused starts, and stop on errors that waiting cannot fix.

A few more things worth adding:

  • Priorities. Interactive requests from a person waiting on a screen may deserve to jump ahead of batch jobs. Give them a separate queue that next() checks first, with a cap so batch work still progresses.
  • Deadlines. A job that has waited longer than its caller will wait should be dropped from the queue instead of started.
  • Metrics. Queue length, wait time and refused starts per tenant tell you when to raise maxConcurrent, or when a plan change is due.

What this means for agents

Agents make bursty traffic burstier. A planner that decides to "run these ten checks in parallel" creates ten jobs at once. Two habits help: let the tool layer, not the model, decide concurrency, and return a clear, model-readable message when the queue is full, so the agent can run checks one at a time instead of retrying all ten. Our post on designing a run_code tool shows a result shape that tells the model whether a retry is worth it.

Originally published on the Sandscale blog.

Top comments (0)