Skip to content

An open-source, faster Devin alternative

TypeScript

perf(edge,sdk): cut burst-create subrequest fan-out (prewake→stock-prep + alarm keep-warm, single-flight cold auth/create-context, stock telemetry) and activate SDK HTTP/2 for real (undici hard dep + awaited dispatcher)

Brian Reardone3d03383b313
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index e6a16daa..613ff1fe 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -356,6 +356,9 @@ interface AuthEntry {
lastBumpMs: number;
}
const authCache = new Map<string, AuthEntry>();
+// In-flight auth misses, keyed by API-key hash — single-flights concurrent cold
+// lookups so a burst doesn't fan out N identical colo/D1 reads (see authenticate).
+const authInflight = new Map<string, Promise<Caller | null>>();
const orgPolicyCache = new Map<string, { policy: OrgPolicy | null; cachedAtMs: number }>();
// The create concurrency cap counts running sandboxes from the global
// sandboxes_index — a per-create D1 read. That index already trails events, so
@@ -443,6 +446,29 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
return cached.caller;
}
+ // Single-flight the cold miss: a burst-100 of a fresh (uncached) key otherwise
+ // fires ~100 identical colo-gets + api_keys D1 reads from this one isolate,
+ // piling onto the concurrent-subrequest fan-out that gates burst creates.
+ // Coalesce by hash so only the leader touches colo/D1; the rest await it.
+ // Deleted on settle, so a revoked key still re-checks within AUTH_TTL_MS.
+ let inflight = authInflight.get(hash);
+ if (!inflight) {
+ inflight = resolveAuthMiss(env, hash);
+ authInflight.set(hash, inflight);
+ void inflight.finally(() => {
+ if (authInflight.get(hash) === inflight) authInflight.delete(hash);
+ });
+ }
+ return inflight;
+}
+
+// resolveAuthMiss is the (coalesced) cold path for authenticate(): colo tier →
+// D1 → populate both caches. Kept separate so authenticate() can single-flight
+// it per key hash. Negatives are never cached (a freshly-created key must work
+// at once).
+async function resolveAuthMiss(env: Env, hash: string): Promise<Caller | null> {
+ const nowMs = Date.now();
+ const nowSec = Math.floor(nowMs / 1000);
// Colo tier: a fresh box's sub-ops usually land on isolates that never saw
// this key. cachedAtMs travels with the entry so the total staleness bound
// (revocation lag) stays AUTH_TTL_MS, not colo-TTL + isolate-TTL stacked.
@@ -506,16 +532,56 @@ async function listActiveCells(env: Env): Promise<CellRow[]> {
return cells;
}
-// loadCreateContext fetches the three org-keyed reads the create hot path needs
-// — org policy, running-sandbox count, active-cells list — in a SINGLE D1 round
-// trip via db.batch(), instead of three sequential awaits. Under a cold burst
-// (fresh isolates, caches empty) that collapses ~3×D1-latency into one. Each
-// piece still honours + populates its existing per-isolate cache, so warm/
-// sustained traffic skips D1 entirely and only the cold misses are batched.
+// In-flight create-context loads, keyed by org — single-flights concurrent cold
+// loads so a burst-100 for one org does ONE org/count/cells load instead of 100
+// (see loadCreateContext).
+const createCtxInflight = new Map<
+ string,
+ Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }>
+>();
+
+// loadCreateContext is a thin coalescing wrapper over loadCreateContextCold: a
+// fully-warm isolate returns immediately (no map churn); otherwise concurrent
+// cold loads for the same org share one in-flight load. The concurrency-count
+// snapshot is shared across the coalesced creates — no weaker than the existing
+// gate, which already reads low under burst (the sandboxes_index count trails
+// create events), so a same-instant burst overshoots identically today.
async function loadCreateContext(
env: Env,
orgID: string,
ctx?: ExecutionContext,
+): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }> {
+ const nowMs = Date.now();
+ const oc = orgPolicyCache.get(orgID);
+ const cc = concurrencyCountCache.get(orgID);
+ if (
+ oc !== undefined && nowMs - oc.cachedAtMs < ORG_POLICY_TTL_MS &&
+ cc !== undefined && nowMs - cc.cachedAtMs < CONCURRENCY_COUNT_TTL_MS &&
+ activeCellsCache !== null && nowMs - activeCellsCache.cachedAtMs < CELL_TTL_MS
+ ) {
+ return { org: oc.policy, activeCount: cc.count, cells: activeCellsCache.cells };
+ }
+ let inflight = createCtxInflight.get(orgID);
+ if (!inflight) {
+ inflight = loadCreateContextCold(env, orgID, ctx);
+ createCtxInflight.set(orgID, inflight);
+ void inflight.finally(() => {
+ if (createCtxInflight.get(orgID) === inflight) createCtxInflight.delete(orgID);
+ });
+ }
+ return inflight;
+}
+
+// loadCreateContextCold fetches the three org-keyed reads the create hot path
+// needs — org policy, running-sandbox count, active-cells list — in a SINGLE D1
+// round trip via db.batch(), instead of three sequential awaits. Under a cold
+// burst (fresh isolates, caches empty) that collapses ~3×D1-latency into one.
+// Each piece still honours + populates its existing per-isolate cache, so warm/
+// sustained traffic skips D1 entirely and only the cold misses are batched.
+async function loadCreateContextCold(
+ env: Env,
+ orgID: string,
+ ctx?: ExecutionContext,
): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }> {
const nowMs = Date.now();
const oc = orgPolicyCache.get(orgID);
@@ -1321,20 +1387,30 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// 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 box: { id: string; workerID: string; region: string; sandboxDomain: string } | null = null;
+ let box: { id: string; workerID: string; region: string; sandboxDomain: string; stock?: number } | null = null;
let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);
const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));
+ let shardHit = -1; // which shard served (telemetry, see #7)
+ let probes = 0;
for (let attempt = 0; attempt < 3 && !box; attempt++) {
+ probes++;
+ const tryShard = shard;
const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim", {
method: "POST",
body: claimBody,
});
shard = (shard + stride) % POOL_STOCK_SHARDS;
if (!r.ok) continue;
- box = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string };
+ box = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string; stock?: number };
+ shardHit = tryShard;
}
if (box) {
mark("claim");
+ // Stock telemetry (#7): shard that served, probes used, and stock left in
+ // that shard after the pop — surfaced via Server-Timing so a burst run can
+ // correlate latency with shard balance / stock depletion. dur is a value
+ // here, not a duration.
+ phases.push(`shard;dur=${shardHit}`, `probes;dur=${probes}`, `stock;dur=${box.stock ?? -1}`);
const token = await mintSandboxToken(env.SESSION_JWT_SECRET, caller.orgID, box.id, box.workerID);
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID });
@@ -1352,17 +1428,13 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
workerID: box.workerID,
};
if (box.sandboxDomain) resp.sandboxDomain = box.sandboxDomain;
- // Pre-wake the box's VmSession OFF the response path: the DO hibernated
- // after the manufacture dial, and its isolate wake (~180ms, measured via
- // do−doin) otherwise lands on the customer's first exec. waitUntil runs
- // after the 201 is sent, so unlike the reverted inline /status verify
- // this cannot tax create latency.
- ctx.waitUntil(
- env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(box.id))
- .fetch("https://do/status")
- .then(() => {})
- .catch(() => {}),
- );
+ // NOTE: the VmSession pre-wake was MOVED off this create hot path to
+ // stock-prep (pool_stock.ts reserveOnce). At burst-100 the per-create
+ // prewake fanned out ~100 DO /status subrequests from the create
+ // isolate, saturating its subrequest budget — create p100 549ms at
+ // 100-way vs ~140ms at 30-way. Warming at reserve keeps the DO hot for
+ // the common case; a box that re-hibernates before claim wakes on the
+ // host dial / first exec as before.
// Finalize off the create isolate: enqueue a tiny message (one cheap
// send) instead of running the CP fetch + D1 insert here. ~100 inline
// finalizes otherwise accumulate on the isolate and stall the burst (dev
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 95e1a0d7..534240b0 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -30,6 +30,11 @@ interface StockEntry {
interface PoolStockEnv {
SESSION_JWT_SECRET: string;
+ // VmSession DOs are pre-woken here at stock-prep (see reserveOnce) instead of
+ // on the create hot path — a burst-100 otherwise fires ~100 prewake
+ // subrequests from the create isolate, saturating its subrequest budget.
+ // Optional so the binding can be absent mid-cutover (prewake just skips).
+ VM_SESSIONS?: DurableObjectNamespace;
}
// Stock tuning. TARGET_STOCK mirrors ~the whole per-cell hot pool so every
@@ -176,7 +181,9 @@ export class PoolStock {
if (!entry) {
return new Response(JSON.stringify({ error: "stock empty" }), { status: 404 });
}
- return Response.json(entry);
+ // `stock` = entries left in this shard after the pop (telemetry #7): lets the
+ // create path surface shard depletion via Server-Timing.
+ return Response.json({ ...entry, stock: this.stock.length });
}
// rememberCell persists the cell coordinates so the alarm can restock even on
@@ -229,10 +236,33 @@ export class PoolStock {
}
if (this.stock.length < TARGET_STOCK) await this.restockToTarget(cell);
this.persist();
- // Keep the loop alive — stock stays full and fresh between bursts.
+ // Keep the SITTING stock's VmSession DOs warm. A DO hibernates ~10s after
+ // its last activity, so a box reserved minutes ago is cold at claim and its
+ // first exec pays the ~180ms isolate wake. reserveOnce warms freshly-reserved
+ // boxes; this tick re-warms the ones that sit, so a burst against a full-but-
+ // aged pool still lands on warm DOs. Off the response path (alarm + waitUntil).
+ this.prewakeStock();
+ // Keep the loop alive — stock stays full, fresh, and warm between bursts.
await this.state.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
}
+ // prewakeBox wakes one box's VmSession DO isolate (best-effort, off any hot
+ // path). Shared by reserveOnce (fresh boxes) and the alarm (sitting stock).
+ private prewakeBox(sandboxID: string): void {
+ const vs = this.env.VM_SESSIONS;
+ if (!vs) return;
+ this.state.waitUntil(
+ vs.get(vs.idFromName(sandboxID)).fetch("https://do/status").then(() => {}).catch(() => {}),
+ );
+ }
+
+ // prewakeStock re-warms every box currently in stock (per-shard ≤ TARGET_STOCK,
+ // so ≤38 DO pokes per tick per shard). Runs on the alarm so aged stock never
+ // goes cold before a burst claims it.
+ private prewakeStock(): void {
+ for (const e of this.stock) this.prewakeBox(e.id);
+ }
+
private persist(): void {
// allowUnconfirmed skips the output gate: the claim response leaves ~10ms
// sooner instead of waiting for the write to be durable. Failure window
@@ -296,6 +326,10 @@ export class PoolStock {
atMs: now,
});
added++;
+ // Pre-wake the box's VmSession DO now (stock-prep), off any hot path, so
+ // the create burst doesn't fan out ~100 prewake subrequests from the
+ // create isolate. The alarm (prewakeStock) keeps it warm while it sits.
+ this.prewakeBox(b.sandboxID);
}
this.persist();
return added;
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index 1cc0e534..f18a844c 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -8,18 +8,17 @@
"name": "@opencomputer/sdk",
"version": "0.15.1",
"license": "MIT",
+ "dependencies": {
+ "undici": "^6.0.0 || ^7.0.0"
+ },
"devDependencies": {
"@types/node": "^25.3.0",
"tsx": "^4.21.0",
"typescript": "^5.4.0",
- "undici": "^7.29.0",
"vitest": "^1.6.0"
},
"engines": {
"node": ">=18"
- },
- "optionalDependencies": {
- "undici": "^6.0.0 || ^7.0.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
@@ -2178,7 +2177,6 @@
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
"integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=20.18.1"
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 5c1d11cd..17290bed 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -53,10 +53,9 @@
"@types/node": "^25.3.0",
"tsx": "^4.21.0",
"typescript": "^5.4.0",
- "undici": "^7.29.0",
"vitest": "^1.6.0"
},
- "optionalDependencies": {
+ "dependencies": {
"undici": "^6.0.0 || ^7.0.0"
}
}
diff --git a/sdks/typescript/src/http2.ts b/sdks/typescript/src/http2.ts
index ba1e05fc..919bec89 100644
--- a/sdks/typescript/src/http2.ts
+++ b/sdks/typescript/src/http2.ts
@@ -11,27 +11,32 @@
//
// `allowH2` negotiates per-origin via ALPN, so HTTP/1.1-only origins keep
// working unchanged — enabling it globally is safe. Browser-guarded (no global
-// dispatcher there) and a graceful no-op if undici isn't present, so it never
-// breaks a browser bundle or a stripped-down install. Opt out with
-// OPENCOMPUTER_DISABLE_HTTP2=1.
+// dispatcher there). Opt out with OPENCOMPUTER_DISABLE_HTTP2=1.
-let configured = false;
+let configurePromise: Promise<void> | null = null;
-export function configureHttp2(): void {
- if (configured) return;
- configured = true;
-
- const isNode = typeof process !== "undefined" && !!process.versions?.node;
- if (!isNode) return;
- if (process.env?.OPENCOMPUTER_DISABLE_HTTP2) return;
-
- // Dynamic import so browser bundlers never pull undici into the graph, and a
- // missing undici (it's an optional dependency) degrades cleanly to HTTP/1.1.
- import("undici")
- .then(({ Agent, setGlobalDispatcher }) => {
+// configureHttp2 installs the HTTP/2-capable global dispatcher on Node and
+// RESOLVES ONLY ONCE IT IS INSTALLED. The entry point (index.ts) awaits it at
+// module load, so by the time an importer can issue a request the dispatcher is
+// already swapped — otherwise the first burst of requests races the async
+// `import("undici")` and leaks onto HTTP/1.1 (the exact failure that made this a
+// silent no-op in practice). Memoized + never rejects, so importing the SDK can
+// safely `await` it without a try/catch and without repeating the work.
+export function configureHttp2(): Promise<void> {
+ if (configurePromise) return configurePromise;
+ configurePromise = (async () => {
+ const isNode = typeof process !== "undefined" && !!process.versions?.node;
+ if (!isNode) return; // browser: no global dispatcher to set
+ if (process.env?.OPENCOMPUTER_DISABLE_HTTP2) return;
+ try {
+ // Dynamic import so browser bundlers never pull undici into the graph.
+ // undici is a hard dependency on Node (see package.json) so this resolves;
+ // the catch keeps a stripped-down/browser install degrading to HTTP/1.1.
+ const { Agent, setGlobalDispatcher } = await import("undici");
setGlobalDispatcher(new Agent({ allowH2: true }));
- })
- .catch(() => {
+ } catch {
/* undici unavailable — keep the default HTTP/1.1 dispatcher */
- });
+ }
+ })();
+ return configurePromise;
}
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index b7d9522b..180427b1 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -2,8 +2,13 @@ import { configureHttp2 } from "./http2.js";
// Switch the Node global fetch dispatcher to HTTP/2 on import (browser-safe
// no-op). Multiplexes concurrent requests over one connection — a large burst
-// win for create(). See http2.ts.
-configureHttp2();
+// win for create(). Top-level await so the dispatcher is installed BEFORE the
+// importer can issue any request (a dynamic `import("@opencomputer/sdk")` — how
+// the leaderboard adapter loads us — fully settles this first); otherwise the
+// first burst races the async undici import and leaks onto HTTP/1.1. The SDK is
+// ESM-only, so top-level await breaks no existing (already-ESM) consumer, and
+// configureHttp2 never rejects. See http2.ts.
+await configureHttp2();
export {
Sandbox,