Skip to content

An open-source, faster Devin alternative

TypeScript

perf(edge): single-flight the api_keys lookup so a cold burst does not stampede D1

Brian Reardon6ee02dcf957b
diff --git a/cloudflare-workers/api-edge/src/auth_singleflight.test.ts b/cloudflare-workers/api-edge/src/auth_singleflight.test.ts
new file mode 100644
index 00000000..ccb8a50c
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/auth_singleflight.test.ts
@@ -0,0 +1,133 @@
+// A cold-cache burst must collapse onto ONE api_keys lookup.
+//
+// This is a latency contract, not a correctness one, which is exactly why it
+// needs a test: without single-flight everything still returns the right
+// answer, just slowly, so nothing fails and the regression is invisible until
+// someone runs a burst. Measured on prod at burst-100 against a freshly
+// deployed worker, the un-collapsed version put `auth` at 15,026ms median with
+// all 100 requests inside a 48ms band — one shared round trip to a D1 primary
+// that lives in WNAM while the burst runs in IAD.
+import { describe, expect, it, vi } from "vitest";
+import worker, { type Env } from "./index";
+
+const orgID = "22222222-2222-4222-8222-222222222222";
+const userID = "11111111-1111-4111-8111-111111111111";
+
+class CountingDB {
+ apiKeyLookups = 0;
+
+ prepare(sql: string) {
+ const db = this;
+ return {
+ bind() {
+ return this;
+ },
+ async first<T>(): Promise<T | null> {
+ if (sql.includes("FROM api_keys WHERE key_hash")) {
+ db.apiKeyLookups++;
+ // A real D1 read from IAD to a WNAM primary is ~300ms. Any await at
+ // all is enough to let the other requests in the burst reach the
+ // in-flight map, which is the behaviour under test.
+ await new Promise((r) => setTimeout(r, 5));
+ return { org_id: orgID, created_by: userID, expires_at: null } as T;
+ }
+ return null;
+ },
+ async all<T>(): Promise<{ results: T[] }> {
+ return { results: [] as T[] };
+ },
+ async run(): Promise<Record<string, never>> {
+ return {};
+ },
+ };
+ }
+
+ async batch<T>(stmts: { first(): Promise<T> }[]): Promise<{ results: T[] }[]> {
+ return Promise.all(stmts.map(async (s) => ({ results: [await s.first()] })));
+ }
+}
+
+function testEnv(db: CountingDB): Env {
+ return {
+ OPENCOMPUTER_DB: db,
+ SESSIONS_KV: {},
+ WORKER_ENV: "test",
+ CF_ADMIN_SECRET: "",
+ EVENT_SECRET: "",
+ } as unknown as Env;
+}
+
+const ctx = {
+ waitUntil: vi.fn(),
+ passThroughOnException: vi.fn(),
+} as unknown as ExecutionContext;
+
+describe("authenticate single-flight", () => {
+ it("collapses a concurrent cold-cache burst onto one api_keys lookup", async () => {
+ const db = new CountingDB();
+ const env = testEnv(db);
+ // Unique per run: authCache is module-global, so a key another test already
+ // authenticated would be served from cache and never reach D1 at all.
+ const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
+
+ await Promise.all(
+ Array.from({ length: 50 }, () =>
+ worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes", {
+ headers: { "X-API-Key": key },
+ }),
+ env,
+ ctx,
+ ),
+ ),
+ );
+
+ expect(db.apiKeyLookups).toBe(1);
+ });
+
+ it("does not collapse distinct keys onto one another", async () => {
+ const db = new CountingDB();
+ const env = testEnv(db);
+ const keys = Array.from(
+ { length: 3 },
+ () => `osb_${crypto.randomUUID().replace(/-/g, "")}`,
+ );
+
+ await Promise.all(
+ keys.flatMap((key) =>
+ Array.from({ length: 5 }, () =>
+ worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes", {
+ headers: { "X-API-Key": key },
+ }),
+ env,
+ ctx,
+ ),
+ ),
+ ),
+ );
+
+ expect(db.apiKeyLookups).toBe(keys.length);
+ });
+
+ it("releases the in-flight entry so a later miss still reaches D1", async () => {
+ const db = new CountingDB();
+ const env = testEnv(db);
+ const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
+ const call = (): Promise<Response> =>
+ worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes", {
+ headers: { "X-API-Key": key },
+ }),
+ env,
+ ctx,
+ );
+
+ await call();
+ expect(db.apiKeyLookups).toBe(1);
+ // Second call is served by the isolate cache, not by a second query — and
+ // critically it must not hang on a stale in-flight promise.
+ await call();
+ expect(db.apiKeyLookups).toBe(1);
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 6c4852bb..8376d6bd 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -388,6 +388,9 @@ interface AuthEntry {
lastBumpMs: number;
}
const authCache = new Map<string, AuthEntry>();
+// In-flight D1 auth lookups, keyed by key hash — see authenticate(). Collapses a
+// cold-cache burst onto one query instead of one per request.
+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
@@ -500,21 +503,46 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
return shared.caller;
}
- const row = await env.OPENCOMPUTER_DB.prepare(
- "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",
- )
- .bind(hash)
- .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();
- if (!row) return null; // never cache negatives — a freshly-created key must work at once
- if (row.expires_at && row.expires_at < nowSec) return null;
-
- const caller: Caller = { orgID: row.org_id, userID: row.created_by };
- if (authCache.size >= CACHE_MAX) authCache.clear();
- const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };
- authCache.set(hash, entry);
- await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_TTL_MS / 1000);
- bumpLastUsed(env, hash, entry, nowMs);
- return caller;
+ // Single-flight the D1 read. Both cache tiers are empty on a fresh isolate,
+ // and a burst arrives before either can fill, so without this N concurrent
+ // creates issue N identical queries against a primary that sits in WNAM while
+ // the burst runs in IAD.
+ //
+ // Measured on prod at burst-100 against a just-deployed worker: `auth` median
+ // 15,026ms, with all 100 requests inside a 48ms band — the tight band is the
+ // tell, since it means they were not queueing behind each other's work but
+ // waiting on one shared round trip that D1 serialized. Same isolate warm, the
+ // mark is 0ms. loadOrgPolicy already does this; auth was the last read on the
+ // create path that did not.
+ //
+ // Keyed on the hash, so distinct keys still proceed in parallel, and the
+ // entry is removed as soon as it settles — this collapses a stampede, it is
+ // not a cache tier of its own.
+ const inflight = authInflight.get(hash);
+ if (inflight) return inflight;
+ const pending = (async (): Promise<Caller | null> => {
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",
+ )
+ .bind(hash)
+ .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();
+ if (!row) return null; // never cache negatives — a freshly-created key must work at once
+ if (row.expires_at && row.expires_at < nowSec) return null;
+
+ const caller: Caller = { orgID: row.org_id, userID: row.created_by };
+ if (authCache.size >= CACHE_MAX) authCache.clear();
+ const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };
+ authCache.set(hash, entry);
+ await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_TTL_MS / 1000);
+ bumpLastUsed(env, hash, entry, nowMs);
+ return caller;
+ })();
+ authInflight.set(hash, pending);
+ try {
+ return await pending;
+ } finally {
+ authInflight.delete(hash);
+ }
}
// Cell rows are semi-static (base_url is fixed; capacity refreshes ~30s and