Walkthrough
Build it yourself, part by part.
Some products need more than a moment of computing for each person. A coding assistant, a notebook, an agent that works on someone's files: each user needs a machine that is theirs, with their things still on it tomorrow.
The hard part is not starting machines. It is paying for them only while they are used, and getting the same one back afterwards. This example does both in one function.
-
One function decides everything
Every request that needs a user's machine calls sandboxFor. It looks up the sandbox that user had. If it is running, use it. If it is paused, resume it. If they never had one, or it is gone, start one and remember it.
The rest of your product never thinks about any of this again. It asks for the user's sandbox and gets a running one.
server.mjs
async function sandboxFor(user) { const id = users[user] if (id) { try { const sb = await annex.get(id) if (sb.status === 'running') return id if (sb.status === 'paused') return (await annex.resume(id)).id } catch (err) { if (!(err instanceof AnnexError && err.status === 404)) throw err } } const sb = await annex.start({ route: 'cheapest', vcpu: 1, memory_gib: 1 }) await annex.ready(sb.id) users[user] = sb.id save() return sb.id } -
Pause when they go quiet
A timer looks at when each user last ran something. After five quiet minutes their sandbox is paused. Their files stay exactly as they were; the next request finds it paused and resumes it.
What a paused sandbox costs depends on where it runs. Many providers release the machine and bill only for its disk; a few keep billing. Each sandbox says which, so you can show it or route around it.
server.mjs
setInterval(async () => { for (const [user, at] of lastUsed) { if (Date.now() - at < IDLE_MS) continue lastUsed.delete(user) await annex.pause(users[user]).catch((err) => console.error(`pausing ${user}: ${err.message}`)) console.log(`${user}: paused after ${IDLE_MS / 60000} quiet minutes`) } }, 30_000) -
Use it like any other machine
With the sandbox in hand, running a command for a user is one call. The example is a command box in the browser; in a real product this is where your agent's tools go.
server.mjs
const id = await sandboxFor(user) lastUsed.set(user, Date.now()) const r = await annex.run(id, command, { timeout: 120 }) return json(200, { output: r.output, exit: r.exit_code })
Before you rely on it
- The example's sign-in is a name in a cookie, so anyone can be anyone. Use your product's own.
- The list of who has which sandbox is a small file here. In a product it is one more field on the user in your own records.
- To give each new user a ready environment, start their sandbox from a template.
- Set limits on sandboxes at once and on monthly spend, so one user can't use what the others need.