Use case

Split a big job across a fleet of agents.

Five hundred files to migrate, or ten thousand documents to read. One agent takes a week. Fifty take an afternoon, if they can share the work without tripping over each other.

The problem

Splitting a job across many machines is easy to say and fiddly to build. Each machine has to know what is left, nobody should do the same piece twice, and a machine that dies shouldn't take its piece with it.

The usual answer is to set up a queue and a store of your own, and hand every sandbox the keys to them.

How Annex does it

  1. Start a task

    A task groups sandboxes working on the same thing, on any mix of providers. Each sandbox in it is handed a short-lived pass to the task's queues and storage, and nothing else.

  2. Put the work on a queue

    Each sandbox claims a job, does it, and marks it done. A job claimed by a sandbox that died goes back on the queue for another.

  3. Collect the results

    Sandboxes write what they found into the task's shared storage. Your app, or the agent in charge, reads it from there.

What it looks like

Every sandbox in a task already has what it needs to claim work.

Inside a sandbox

curl -X POST "$ANNEX_URL/v1/workspaces/$ANNEX_WORKSPACE_ID/tasks/$ANNEX_TASK_ID/queues/jobs/claim" \
  -H "Authorization: Bearer $ANNEX_TASK_TOKEN" \
  -d '{"max": 1}'

Walkthrough

Build it yourself, part by part.

Some jobs are one job done two hundred times: move every file to the new API, run every shard of the tests, read every page on a list. One machine does them one after another. A fleet does them at once.

The usual way to build that is a queue service, a place for results and something to restart what fails. Here those come with the sandboxes, and the whole thing is two short files.

The queueone job a slipThe resultskept as they arrive

The whole thing is about 60 lines. Get the code →

  1. Start a fleet that shares one task

    The first sandbox makes a task. Every other sandbox joins it by naming it. Sandboxes of one task share queues of jobs and a store for results, wherever each one happens to run.

    Then the jobs go on the queue, one message each. Nothing is assigned to anyone: each sandbox takes the next job when it is free, so fast machines simply do more.

    fleet.mjs

    // The first sandbox makes the task; the rest join it.
    const first = await annex.start({ route: 'cheapest', vcpu: 1, memory_gib: 1 })
    const rest = await Promise.all(Array.from({ length: size - 1 }, () =>
      annex.start({ route: 'cheapest', vcpu: 1, memory_gib: 1, task: first.task })))
    const fleet = [first, ...rest]
    
    for (const url of jobs) await annex.push(first.task, 'jobs', { url })
  2. The worker is plain curl

    Every sandbox runs the same small script: claim a job, do it, write the result, say it's done, take the next. It stops when the queue stays empty.

    It needs no key of yours. Annex puts its own address and a token in every sandbox's environment, and that token works for this one task and nothing else.

    A job that was claimed and never finished, because its sandbox was lost or its command hung, comes back for another sandbox after two minutes. A job that fails five times is set aside so it can't hold up the rest.

    worker.sh

    T="$ANNEX_URL/v1/workspaces/$ANNEX_WORKSPACE_ID/tasks/$ANNEX_TASK_ID"
    api() { curl -fsS -X "$1" "$T$2" -H "Authorization: Bearer $ANNEX_TASK_TOKEN" -H 'Content-Type: application/json' ${3:+-d "$3"}; }
    field() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
    
    do_job() { curl -fsSL --max-time 30 "$1" | wc -w | tr -d ' '; }
    
    empty=0
    while [ "$empty" -lt 3 ]; do
      msg=$(api POST /queues/jobs/claim '{"max":1,"visibility_seconds":120}')
      id=$(printf %s "$msg" | field id)
      if [ -z "$id" ]; then empty=$((empty + 1)); sleep 2; continue; fi
      empty=0
      url=$(printf %s "$msg" | field url)
      words=$(do_job "$url" 2>/dev/null || echo 0)
      key=$(printf %s "$url" | tr -c 'a-zA-Z0-9' '-')
      api PUT "/kv/results-$key" "{\"value\":{\"url\":\"$url\",\"words\":$words,\"by\":\"$ANNEX_SANDBOX_ID\"}}" >/dev/null
      api POST "/queues/jobs/messages/$id/ack" >/dev/null
    done
  3. Collect, and leave nothing running

    When every worker has ended, the results are read from the store in one go and the fleet is stopped. Results are kept apart from the queue on purpose: the queue is for coordinating, the store is for what you want to keep.

    fleet.mjs

    await Promise.all(fleet.map(async (sb) => {
      await annex.upload(sb.id, '/tmp/worker.sh', worker)
      return annex.run(sb.id, 'sh /tmp/worker.sh', { timeout: 3600 })
    }))
    const results = (await annex.kv(first.task, 'results-')).map((r) => r.value)
    console.table(results)
    await Promise.allSettled(fleet.map((sb) => annex.stop(sb.id)))

Before you rely on it

  • The job in the example is small on purpose: fetch a page and count its words. Replace one function in the worker with your own work.
  • A fleet can land on several providers at once. Cheapest fills the least expensive account first and moves on when it is full.
  • Set a limit on sandboxes at once before a large run, and ask Annex for a plan first if you want the cost before you spend it.

Get the code on GitHub

Related use cases