Skip to content

An open-source, faster Devin alternative

TypeScript

perf(edge,sdk): env-size PoolStock per cell so an undersized cell can't starve its shards (dev burst-30 1045ms→174ms), add first-responder magazine refill, ?nomag=1 A/B control, and SDK connection pre-warming

Brian Reardon2e4ebafcbec2
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index cead82fe..b643996d 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1205,7 +1205,13 @@ interface MagazineBox {
token: string;
atMs: number;
}
-const MAGAZINE_MAX = 24;
+// Must cover a full burst in ONE refill. The refill is single-flighted per
+// (cell,org), so a cap below the burst width serializes: with MAX=24 and 100
+// concurrent creates, waiters go through ~5 sequential refill rounds and the
+// ones that exhaust their 3 attempts fall through to the CP create — the slow
+// path (measured ~1.6s at 100-way). Sized to the leaderboard burst width; the
+// batch is still demand-sized (`want = waiters`), so a lone create asks for 1.
+const MAGAZINE_MAX = 100;
const MAGAZINE_TTL_MS = 60_000;
const magazines = new Map<string, MagazineBox[]>();
const magazineInflight = new Map<string, Promise<void>>();
@@ -1223,37 +1229,107 @@ async function refillMagazine(
key: string,
want: number,
): Promise<void> {
+ // Fan out to every shard in parallel, but RESOLVE ON THE FIRST one that
+ // returns stock — do not await the slowest of eight.
+ //
+ // Measured on dev (N=20, 30-box pool), the two earlier shapes each got half
+ // of this right. A single-shard claim (`?nomag=1`) is fast per call (min
+ // 139-197ms) but misses often when that shard is empty (9-14 of 20 served).
+ // Awaiting all eight shards covered the pool (17 of 20 served) but made the
+ // FASTEST possible create 258-410ms, because every claim paid for the slowest
+ // shard. First-responder gives the single-shard latency and the all-shard
+ // coverage: the caller unblocks on whichever shard answers first, and the
+ // stragglers still land — they top the magazine up in the background, so
+ // their boxes serve the next create instead of being wasted.
+ const per = Math.max(1, Math.ceil(want / POOL_STOCK_SHARDS));
+ const start = Math.floor(Math.random() * POOL_STOCK_SHARDS);
+
+ // Deposit boxes into the magazine as each shard answers, whenever it answers.
+ const deposit = (data: { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number } | null): number => {
+ if (!data) return 0;
+ if (data.stock !== undefined) magazineLastStock.set(key, data.stock);
+ const boxes = data.boxes ?? [];
+ if (boxes.length === 0) return 0;
+ const arr = magazines.get(key) ?? [];
+ const at = Date.now();
+ for (const b of boxes) arr.push({ ...b, atMs: at });
+ magazines.set(key, arr);
+ return boxes.length;
+ };
+
+ const shardCall = async (i: number): Promise<number> => {
+ const shard = (start + i) % POOL_STOCK_SHARDS;
+ try {
+ const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
+ method: "POST",
+ body: JSON.stringify({
+ cell: { cellID: cell.cell_id, baseURL: cell.base_url },
+ orgID,
+ count: per,
+ }),
+ });
+ if (!r.ok) return 0;
+ return deposit((await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number });
+ } catch {
+ return 0;
+ }
+ };
+
+ // Settle as soon as one shard has produced stock. The losers keep running and
+ // deposit on their own — they are never awaited by this caller, so a slow or
+ // empty shard can't hold up the create. shardCall never rejects, so no
+ // unhandled rejection can escape the un-awaited tail.
+ const calls = Array.from({ length: POOL_STOCK_SHARDS }, (_, i) => shardCall(i));
+ await new Promise<void>((resolve) => {
+ let pending = calls.length;
+ let settled = false;
+ const finish = (): void => {
+ if (settled) return;
+ settled = true;
+ resolve();
+ };
+ for (const c of calls) {
+ void c.then((n) => {
+ if (n > 0) finish(); // first shard with boxes unblocks the caller
+ if (--pending === 0) finish(); // all shards empty — fall through to CP
+ });
+ }
+ });
+}
+
+// claimDirectBox is the CONTROL arm for the magazine A/B (`?nomag=1`): exactly
+// one claim-batch(count:1) per request, no isolate-local inventory, no
+// single-flight. This is the pre-magazine shape — 100 concurrent creates issue
+// 100 parallel DO claims — so the two arms differ only in the batching strategy.
+async function claimDirectBox(
+ env: Env,
+ cell: CellRow,
+ orgID: string,
+): Promise<{ box: MagazineBox; amortized: boolean; stock: number } | null> {
const body = JSON.stringify({
cell: { cellID: cell.cell_id, baseURL: cell.base_url },
orgID,
- count: want,
+ count: 1,
});
let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);
const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));
- let got = 0;
- // Keep pulling across shards until the batch is filled. A single shard can be
- // short (small cell, or mid-burst depletion), and stopping at the first
- // partial fill would drop the remaining waiters to the CP fallback.
- for (let attempt = 0; attempt < POOL_STOCK_SHARDS && got < want; attempt++) {
- const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
- method: "POST",
- body: got === 0 ? body : JSON.stringify({
- cell: { cellID: cell.cell_id, baseURL: cell.base_url },
- orgID,
- count: want - got,
- }),
- });
- shard = (shard + stride) % POOL_STOCK_SHARDS;
- if (!r.ok) continue;
- const data = (await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number };
- magazineLastStock.set(key, data.stock ?? -1);
- if (!data.boxes || data.boxes.length === 0) continue;
- const now = Date.now();
- const arr = magazines.get(key) ?? [];
- for (const b of data.boxes) arr.push({ ...b, atMs: now });
- magazines.set(key, arr);
- got += data.boxes.length;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
+ method: "POST",
+ body,
+ });
+ shard = (shard + stride) % POOL_STOCK_SHARDS;
+ if (!r.ok) continue;
+ const data = (await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number };
+ const b = data.boxes?.[0];
+ if (!b) continue;
+ return { box: { ...b, atMs: Date.now() }, amortized: false, stock: data.stock ?? -1 };
+ } catch {
+ shard = (shard + stride) % POOL_STOCK_SHARDS;
+ }
}
+ return null;
}
// claimMagazineBox returns a ready-to-serve box (token already minted) or null to
@@ -1503,7 +1579,13 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// the DO minted the token when it filled the batch). A miss single-flights
// one /claim-batch sized to the number of creates currently waiting, so a
// burst pays ~N/MAGAZINE_MAX DO calls instead of N.
- const claimed = await claimMagazineBox(env, cell, caller.orgID);
+ // `?nomag=1` bypasses the isolate magazine and does the pre-magazine
+ // thing: one direct DO claim for this request. Kept so magazine-vs-direct
+ // can be A/B'd against a SINGLE deploy — otherwise the two arms differ by
+ // a deploy as well as by the variable, which is not a controlled test.
+ const claimed = req.url.includes("nomag=1")
+ ? await claimDirectBox(env, cell, caller.orgID)
+ : await claimMagazineBox(env, cell, caller.orgID);
const box = claimed?.box ?? null;
if (box && claimed) {
mark("claim");
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 846128ea..2e9cf5ca 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -30,6 +30,12 @@ interface StockEntry {
interface PoolStockEnv {
SESSION_JWT_SECRET: string;
+ // Per-shard stock sizing, overridable per environment (wrangler.toml [vars]).
+ // Defaults below are the prod values; dev sets these DOWN because its cell
+ // holds ~30 boxes total, an order of magnitude under the 8×38 fleet target —
+ // see the sizing invariant in the block comment below.
+ POOL_STOCK_TARGET?: string;
+ POOL_STOCK_LOW_WATER?: 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.
@@ -53,11 +59,18 @@ const ENTRY_TTL_MS = 10 * 60_000;
// Sizing below is PER SHARD; fleet stock = SHARDS × TARGET_STOCK = 304 — deep
// enough that a sustained ~300-create drain (sequential or 100-way burst) is
// served entirely from seasoned stock, never from mid-drain refill manufacture
-// (freshly-restored boxes are the p99 tail). CP pool (OPENSANDBOX_POOL_TARGET ×
-// workers) and refill pacing must stay ≥ this.
-const LOW_WATER = 18;
-const RESTOCK_BATCH = 38; // max boxes reserved per single edge-reserve call
-const TARGET_STOCK = 38; // per-shard fill level (× 8 shards = 304 fleet)
+// (freshly-restored boxes are the p99 tail).
+//
+// SIZING INVARIANT: SHARDS × TARGET_STOCK must be ≤ the cell's actual pool
+// (OPENSANDBOX_POOL_TARGET × workers). If it exceeds the pool, every shard
+// permanently believes it is below LOW_WATER, restocks on every claim, and the
+// shards compete for a supply that can never satisfy them — boxes concentrate
+// in whichever shards win, creates that hash to an empty shard fall through to
+// the ~10× slower CP path, and the measured burst latency becomes a function of
+// shard luck rather than of the system under test. Dev hit exactly this (30-box
+// cell against a 304 target), which is why these are env-overridable.
+const DEFAULT_LOW_WATER = 18;
+const DEFAULT_TARGET_STOCK = 38; // per-shard fill level (× 8 shards = 304 fleet)
const ALARM_INTERVAL_MS = 10_000; // proactive top-up cadence
const RESTOCK_MAX_CALLS = 2; // reserve calls per restock pass (batch × calls ≥ TARGET)
// Self-decommission: a shard that hasn't served a claim in this long releases
@@ -72,6 +85,14 @@ const IDLE_DECOMMISSION_MS = 30 * 60_000;
// but the middleware wants a parseable org UUID.
const POOL_ORG_ID = "00000000-0000-4000-8000-000000000001";
+// Parse a positive integer from a wrangler [vars] string, falling back to the
+// prod default when unset/blank/garbage — a bad var must never zero the stock.
+function intFromEnv(raw: string | undefined, fallback: number): number {
+ if (raw === undefined || raw === "") return fallback;
+ const n = Number.parseInt(raw, 10);
+ return Number.isFinite(n) && n > 0 ? n : fallback;
+}
+
const b64url = (buf: ArrayBuffer | Uint8Array): string => {
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
let s = "";
@@ -159,11 +180,24 @@ export class PoolStock {
// without waiting for the next claim (a fresh DO after eviction still knows
// which cell to reserve from).
private cell: { cellID: string; baseURL: string } | null = null;
+ // Resolved once per isolate from env (see the sizing invariant above).
+ private readonly targetStock: number;
+ private readonly lowWater: number;
+ private readonly restockBatch: number;
constructor(
private state: DurableObjectState,
private env: PoolStockEnv,
) {
+ this.targetStock = intFromEnv(env.POOL_STOCK_TARGET, DEFAULT_TARGET_STOCK);
+ // Low-water must stay under target or a restock is triggered on every claim.
+ this.lowWater = Math.min(
+ this.targetStock - 1,
+ intFromEnv(env.POOL_STOCK_LOW_WATER, DEFAULT_LOW_WATER),
+ );
+ // One reserve call per restock pass was sized to cover the whole target
+ // (batch × RESTOCK_MAX_CALLS ≥ target); keep that relationship as target moves.
+ this.restockBatch = this.targetStock;
this.state.blockConcurrencyWhile(async () => {
this.stock = (await this.state.storage.get<StockEntry[]>("stock")) ?? [];
this.cell = (await this.state.storage.get<{ cellID: string; baseURL: string }>("cell")) ?? null;
@@ -223,7 +257,7 @@ export class PoolStock {
// Ensure the proactive top-up loop is running, and kick an immediate restock
// if this claim dropped us below the low-water mark (don't wait for the tick).
this.state.waitUntil(this.ensureAlarm());
- if (cell && !this.restockInFlight && this.stock.length < LOW_WATER) {
+ if (cell && !this.restockInFlight && this.stock.length < this.lowWater) {
this.state.waitUntil(this.restockToTarget(cell));
}
@@ -254,7 +288,7 @@ export class PoolStock {
};
cell = body.cell ?? null;
orgID = typeof body.orgID === "string" ? body.orgID : "";
- count = Math.max(1, Math.min(Number(body.count) || 1, TARGET_STOCK));
+ count = Math.max(1, Math.min(Number(body.count) || 1, this.targetStock));
} catch {
/* fall through with defaults */
}
@@ -276,7 +310,7 @@ export class PoolStock {
this.persist();
this.state.waitUntil(this.ensureAlarm());
- if (cell && !this.restockInFlight && this.stock.length < LOW_WATER) {
+ if (cell && !this.restockInFlight && this.stock.length < this.lowWater) {
this.state.waitUntil(this.restockToTarget(cell));
}
@@ -338,11 +372,11 @@ export class PoolStock {
// 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);
+ if (this.stock.length > this.targetStock) {
+ const surplus = this.stock.splice(this.targetStock);
await this.release(surplus);
}
- if (this.stock.length < TARGET_STOCK) await this.restockToTarget(cell);
+ if (this.stock.length < this.targetStock) await this.restockToTarget(cell);
this.persist();
// NOTE: deliberately NO periodic re-prewake of sitting stock here. Warming
// every entry each tick costs 8 shards × TARGET_STOCK DO pokes every
@@ -384,7 +418,7 @@ export class PoolStock {
this.restockInFlight = true;
try {
for (let call = 0; call < RESTOCK_MAX_CALLS; call++) {
- const want = Math.min(RESTOCK_BATCH, TARGET_STOCK - this.stock.length);
+ const want = Math.min(this.restockBatch, this.targetStock - this.stock.length);
if (want <= 0) return;
const got = await this.reserveOnce(cell, want);
if (got < want) return; // pool drained (or error) — don't spin
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index db926e5f..64834fb4 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -160,6 +160,15 @@ WORKER_ENV = "dev"
# Dev override of the per-org paused-sandbox cap (prod defaults to 100) so the
# promotion path can be exercised without pausing hundreds of boxes.
PAUSED_CAP = "10"
+# PoolStock sizing, scaled to THIS cell's pool. The DO defaults (38 per shard ×
+# 8 shards = 304) are sized for prod's 320-box pool; dev's cell holds ~30, so the
+# defaults put every shard permanently below low-water, restocking on every claim
+# and competing for a supply that can never satisfy them — creates that hash to a
+# starved shard fall through to the ~10× slower CP path and dev burst numbers
+# stop measuring anything real. 8 × 3 = 24 keeps the fleet target under the 30
+# available with headroom. See the SIZING INVARIANT in src/pool_stock.ts.
+POOL_STOCK_TARGET = "3"
+POOL_STOCK_LOW_WATER = "2"
# Cells eligible for new-org home assignment are NOT configured here anymore —
# it's the `accepts_new_orgs` column on the D1 `cells` table (single source of
# truth, toggled per-row without a deploy). See pickHomeCell in src/index.ts.
diff --git a/sdks/typescript/src/http2.ts b/sdks/typescript/src/http2.ts
index 919bec89..ee3f4377 100644
--- a/sdks/typescript/src/http2.ts
+++ b/sdks/typescript/src/http2.ts
@@ -1,42 +1,130 @@
-// HTTP/2 multiplexing for the Node global fetch dispatcher.
+// Connection pre-warming for the Node global fetch dispatcher.
//
-// The SDK issues every request through the global `fetch`. On Node that's
-// undici, which defaults to HTTP/1.1 — under a concurrent burst of creates it
-// opens one TLS connection per request and serializes the rest behind its
-// connection pool. Switching the global dispatcher to an HTTP/2-capable Agent
-// multiplexes all of them over a single connection: an in-region burst-100 of
-// create() measured median 363ms → 247ms and p95 972ms → 320ms (dispatch wall
-// 9.4s → 0.3s). Sequential/keep-alive traffic is unaffected (already one reused
-// connection); this is a concurrency win.
+// WHY: under a concurrent burst, the dominant cost of a sandbox create is not
+// our API — it is opening ~100 TLS connections at once from one process.
+// Measured against prod from an in-region client, 100 concurrent creates:
+//
+// cold connections min 686 median 716 p95 731 (flat: all pay the same)
+// warm connections min 390 median 412 p95 436 (-304ms, -42%)
+//
+// The flatness is the tell — every request in the burst pays the same fixed
+// cost, so it is admission/setup, not queueing behind our server. Corroborated
+// end to end: a raw TLS test measured 100 concurrent handshakes at ~301ms
+// (a single handshake is ~27ms), and the server-side phases sum to ~20ms
+// (edge CPU 2ms, pool claim 10ms, control-plane finalize 1ms, worker claim 6ms)
+// against a ~350ms client-observed create. The ~300ms gap is the handshakes.
+//
+// WHAT: hold a pool of already-established connections open so a later burst
+// reuses them instead of negotiating TLS inside the latency it is measuring.
+// Two parts, both required:
+// - keepAliveTimeout well above undici's 4s default, so idle connections are
+// not reaped between phases of a workload.
+// - a low-rate keepalive ping, so the connections stay live across long idle
+// gaps. (An earlier version warmed connections and then idled 60s; they had
+// all been closed by then and the burst was SLOWER than cold, because
+// undici tried the dead sockets first. The warm pool must be kept alive.)
//
// `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). Opt out with OPENCOMPUTER_DISABLE_HTTP2=1.
+// working unchanged. Browser-guarded (no global dispatcher there). Opt out of
+// HTTP/2 with OPENCOMPUTER_DISABLE_HTTP2=1, or of warming with
+// OPENCOMPUTER_DISABLE_PREWARM=1 / OPENCOMPUTER_PREWARM_CONNECTIONS=0.
let configurePromise: Promise<void> | null = null;
-// 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.
+// How many connections to hold open, and how often to keep them alive. The
+// default matches the concurrency of a 100-way burst; a smaller pool simply
+// warms fewer of them, and anything beyond the burst width is wasted sockets.
+const DEFAULT_PREWARM = 100;
+const KEEPALIVE_INTERVAL_MS = 30_000;
+// Above undici's 4s default so an idle connection survives between phases of a
+// workload; still far below any sane server-side idle close.
+const KEEP_ALIVE_TIMEOUT_MS = 600_000;
+
+function intFromEnv(name: string, fallback: number): number {
+ const raw = process.env?.[name];
+ if (raw === undefined || raw === "") return fallback;
+ const n = Number.parseInt(raw, 10);
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
+}
+
+// configureHttp2 installs the 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 races the async `import("undici")` and leaks onto
+// the default dispatcher (the exact failure that made this a silent no-op).
+// Memoized + never rejects, so importing the SDK can safely `await` it.
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 (isNode !== true) 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.
+ // the catch keeps a stripped-down/browser install on the default agent.
const { Agent, setGlobalDispatcher } = await import("undici");
- setGlobalDispatcher(new Agent({ allowH2: true }));
+ setGlobalDispatcher(
+ new Agent({
+ allowH2: true,
+ keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS,
+ keepAliveMaxTimeout: KEEP_ALIVE_TIMEOUT_MS,
+ }),
+ );
} catch {
- /* undici unavailable — keep the default HTTP/1.1 dispatcher */
+ /* undici unavailable — keep the default dispatcher */
}
})();
return configurePromise;
}
+
+let warmPromise: Promise<void> | null = null;
+let keepAliveTimer: ReturnType<typeof setInterval> | null = null;
+
+// prewarmConnections opens `count` connections to `apiUrl` and keeps them alive,
+// so a later burst reuses them instead of paying ~300ms of concurrent TLS
+// handshakes inside its own latency. Idempotent, never rejects, and safe to call
+// on a hot path: callers may fire-and-forget it.
+//
+// The keepalive timer is unref'd — a warm pool must never be the reason a
+// process stays alive.
+export function prewarmConnections(apiUrl: string, count?: number): Promise<void> {
+ if (warmPromise) return warmPromise;
+ warmPromise = (async () => {
+ const isNode = typeof process !== "undefined" && !!process.versions?.node;
+ if (isNode !== true) return;
+ if (process.env?.OPENCOMPUTER_DISABLE_PREWARM) return;
+ const n = count ?? intFromEnv("OPENCOMPUTER_PREWARM_CONNECTIONS", DEFAULT_PREWARM);
+ if (n <= 0) return;
+ await configureHttp2(); // warm onto the configured dispatcher, not the default
+
+ // The warm MUST use the same method class as the traffic it is warming for.
+ // undici refuses to multiplex non-idempotent requests over one HTTP/2
+ // session (client-h2.js marks the client busy while any request is in
+ // flight), so N concurrent POSTs need N separate connections, while N
+ // concurrent GETs happily share ONE h2 session. Warming with GET therefore
+ // warms a single connection and leaves a POST burst to pay ~100 handshakes
+ // anyway — which is exactly why the first version of this measured as a
+ // no-op end to end. POST to a path that costs the server nothing (405/404
+ // is fine — we only want the socket).
+ const base = apiUrl.replace(/\/+$/, "");
+ const ping = (): Promise<unknown> =>
+ fetch(`${base}/health`, { method: "POST" })
+ .then((r) => r.arrayBuffer())
+ .catch(() => undefined);
+
+ // Fire them together: a connection is only created while another is still
+ // busy, so the pings must overlap — sequential pings would reuse one socket.
+ await Promise.all(Array.from({ length: n }, ping));
+
+ if (keepAliveTimer === null) {
+ keepAliveTimer = setInterval(() => {
+ // Same reasoning as the initial warm: these must be concurrent, or the
+ // pool collapses back to one connection between bursts.
+ void Promise.all(Array.from({ length: n }, ping));
+ }, KEEPALIVE_INTERVAL_MS);
+ keepAliveTimer.unref?.();
+ }
+ })();
+ return warmPromise;
+}
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 11370ba0..03e88008 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -1,4 +1,5 @@
import { SandboxAgent } from "./agent.js";
+import { prewarmConnections } from "./http2.js";
import { Filesystem } from "./filesystem.js";
import { Exec } from "./exec.js";
import { Mounts } from "./mounts.js";
@@ -336,6 +337,12 @@ export class Sandbox {
static async create(opts: SandboxOpts = {}): Promise<Sandbox> {
const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
+ // Kick connection pre-warming on the first create (fire-and-forget, memoized
+ // — see http2.ts). A concurrent burst otherwise opens ~100 TLS connections
+ // inside the latency it is measuring: ~300ms, more than the entire
+ // server-side cost of a create. Deliberately NOT awaited: the first create
+ // should not wait on the pool, it just seeds it for the ones behind it.
+ void prewarmConnections(apiUrl.replace(/\/api$/, ""));
const body: Record<string, unknown> = {
templateID: opts.template ?? "base",