Skip to content

An open-source, faster Devin alternative

TypeScript

shard PoolStock into 8 DOs to kill burst claim serialization

Brian Reardon861ed837ee7f
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 235f5d72..c56d0de8 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1006,6 +1006,16 @@ function indexSandboxFromSSE(
return new Response(resp.body.pipeThrough(stream), resp);
}
+// Stock shard fan-out (see pool_stock.ts for sizing): shard 0 uses the bare
+// cellID as its DO name — that's the pre-sharding instance, kept addressable so
+// its stock drains via claims + surplus-trim instead of stranding until TTL.
+const POOL_STOCK_SHARDS = 8;
+
+function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectStub {
+ const name = shard === 0 ? cellID : `${cellID}#${shard}`;
+ return env.POOL_STOCK.get(env.POOL_STOCK.idFromName(name));
+}
+
// edgeClaimEligible: a create qualifies for the edge fast path only when it
// asks for exactly what pool boxes are manufactured as — base template at the
// default shape (4GB/1cpu/default disk), no guest-side customization (envs,
@@ -1184,13 +1194,30 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// through to the normal cell create, which is never worse than before.
if (env.EDGE_CLAIM !== "0" && env.POOL_STOCK && edgeClaimEligible(bodyText)) {
try {
- const stub = env.POOL_STOCK.get(env.POOL_STOCK.idFromName(cell.cell_id));
+ // Sharded stock (see pool_stock.ts): a single DO serializes burst claims
+ // (~2ms each → ~90ms queue tail at 100-way), so claims spread across
+ // POOL_STOCK_SHARDS instances. Shard 0 keeps the legacy unsharded name so
+ // the pre-sharding DO (holding the fleet's stock at cutover) drains as a
+ // first-class shard instead of hoarding reservations until TTL. One empty
+ // shard (404) gets one retry on a different shard before the CP fallback.
+ const claimBody = JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } });
mark("cap");
- const r = await stub.fetch("https://pool-stock/claim", {
- method: "POST",
- body: JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } }),
- });
- if (r.ok) {
+ // Sample up to 3 distinct shards (random walk with a random stride
+ // coprime-ish to 8) — at full stock the first hit ends it; under sparse
+ // stock (small cells, mid-battery drain) 3 samples cut the false-fallback
+ // rate from ~(empty/8)² to ~(empty/8)³ for ~10ms per extra probe.
+ let r: Response | null = null;
+ let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);
+ const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));
+ for (let attempt = 0; attempt < 3; attempt++) {
+ r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim", {
+ method: "POST",
+ body: claimBody,
+ });
+ if (r.ok) break;
+ shard = (shard + stride) % POOL_STOCK_SHARDS;
+ }
+ if (r && r.ok) {
const box = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string };
mark("claim");
const token = await mintSandboxToken(env.SESSION_JWT_SECRET, caller.orgID, box.id, box.workerID);
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 4f22084a..323cc7af 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -40,15 +40,20 @@ interface PoolStockEnv {
// stays well under the cell's 15-min destroy backstop so an unclaimed box is
// released back to the pool (cheap) long before the cell would destroy it.
const ENTRY_TTL_MS = 10 * 60_000;
-// Sized for the ComputeSDK full battery (sequential 100 → staggered 100 @
-// 200ms → burst 100, back-to-back ≈ 300 boxes): the stock must hold ≥100 at
-// the moment burst fires, with the CP pool (OPENSANDBOX_POOL_TARGET × workers)
-// and refill pacing sized to match.
-const LOW_WATER = 100;
-const RESTOCK_BATCH = 50; // max boxes reserved per single edge-reserve call
-const TARGET_STOCK = 200; // fill the stock up to here (≈ the whole hot pool)
+// SHARDED: a Durable Object processes requests ~serially (~2ms/claim), so one
+// stock DO serializes a burst — measured claim;dur 12ms solo → 47ms at 50-way,
+// ~90ms projected at 100-way. The edge spreads claims across POOL_STOCK_SHARDS
+// (index.ts) DO instances; 8 shards cuts the 100-way queue tail to ~25ms, and
+// past ~8 the alarm/restock machinery and shard-empty retries outgrow the gain.
+// Sizing below is PER SHARD; fleet stock = SHARDS × TARGET_STOCK = 200, matching
+// the ComputeSDK full battery (sequential 100 → staggered 100 @200ms → burst
+// 100 back-to-back ≈ 300 boxes; burst needs ≥100 on hand) with the CP pool
+// (OPENSANDBOX_POOL_TARGET × workers) and refill pacing sized to match.
+const LOW_WATER = 12;
+const RESTOCK_BATCH = 25; // max boxes reserved per single edge-reserve call
+const TARGET_STOCK = 25; // per-shard fill level (× 8 shards = 200 fleet)
const ALARM_INTERVAL_MS = 10_000; // proactive top-up cadence
-const RESTOCK_MAX_CALLS = 4; // reserve calls per restock pass (batch × calls ≥ TARGET)
+const RESTOCK_MAX_CALLS = 2; // reserve calls per restock pass (batch × calls ≥ TARGET)
// Synthetic org that owns parked pool boxes (db.PoolOrgID). Used as the cap
// token subject for reserve/release calls — those endpoints are org-agnostic,
@@ -193,6 +198,14 @@ export class PoolStock {
for (const e of this.stock) (now - e.atMs < ENTRY_TTL_MS ? fresh : stale).push(e);
this.stock = fresh;
if (stale.length > 0) await this.release(stale);
+ // Surplus trim: release anything above the per-shard target back to the
+ // pool. This is how the pre-sharding legacy DO (which becomes shard 0 and
+ // held the whole fleet's stock) sheds down to TARGET_STOCK so the other
+ // shards can reserve those boxes; it also self-heals any future oversizing.
+ if (this.stock.length > TARGET_STOCK) {
+ const surplus = this.stock.splice(TARGET_STOCK);
+ await this.release(surplus);
+ }
if (this.stock.length < TARGET_STOCK) await this.restockToTarget(cell);
this.persist();
// Keep the loop alive — stock stays full and fresh between bursts.