diff --git a/bench/.gitignore b/bench/.gitignore new file mode 100644 index 0000000..3eb949a --- /dev/null +++ b/bench/.gitignore @@ -0,0 +1,3 @@ +# Apps, packed builds, and raw function logs of the runs. +/.work/ +/results/**/*.logs.jsonl diff --git a/bench/README.md b/bench/README.md new file mode 100644 index 0000000..71d900f --- /dev/null +++ b/bench/README.md @@ -0,0 +1,157 @@ +# Benchmark + +What one request to a hosted site costs, for these targets: + +- **convex-hosting 0.14.0**, from npm: the HTTP action asks the component's `route` query which file + answers. +- **convex-hosting 0.15.0**, this repository's package, packed (target `convex-hosting-branch`): the + HTTP action answers from the site's files, which the deploy writes into the pushed code. +- **convex-hosting 0.15.0**, the same as published to npm (the 2026-11-11 runs install it from npm, + target `convex-hosting-0.15.0`). +- **Cloudflare Workers**, target `workers`: the same site as a Worker's static assets, with a Worker + script that renders the same page, on workers.dev. Its server side comes from `wrangler tail`, + which samples; a request runs the script once or not at all, so a case with any run costs one + billed request per request. +- **@convex-dev/static-hosting 0.2.1**, from npm, mounted at `/` + (`app.use(staticHosting, { httpPrefix: "/" })`), the mode its README calls the fastest: the + component's own HTTP action runs its `resolveAsset` query and reads the file from storage. + +Convex bills function calls: every query, mutation, action, and HTTP action, and every download of a +stored file ([usage limits](https://docs.convex.dev/production/usage-limits)). A flood against a +site spends them, so calls per request decide what a flood costs, and when the team's spending limit +turns every project off. + +## Method + +- **One Convex cloud project per target**, each with its own development deployment, created by + `run.ts`: `convex-hosting-bench-014`, `convex-hosting-bench` (this repository's package), and + `convex-hosting-bench-static`. Convex 1.46.0 in each app. +- **The same synthetic site** for all three, from `site.ts`: `index.html`, `404.html`, and 400 + scripts of about 2 KB with Vite-style hashed names, every file with its own bytes. +- **Cases.** `page`: `GET /` with `Sec-Fetch-Mode: navigate`, answered by `index.html`. `asset`: + `GET` of a hashed script. `rendered`: `GET /rendered` with `Sec-Fetch-Mode: navigate`, a path with + no file, answered by the app's code; the convex-hosting apps pass a worker that returns one small + page, so the case measures hosting and not a framework. static-hosting renders no page, so it has + no `rendered` case. +- **No cache answers.** Each request carries a unique query string, so the Cloudflare front of + `*.convex.site` passes every request to the HTTP action, as it does in a flood. A real site that + sends a long `Cache-Control` for its hashed files (the `/assets/*` rule in + [serving](../docs/serving.md)) has a repeat request answered by that front, with no function run. +- **Every response is checked**: the status and a marker in its body (`load.js`). A fast error is + not a result. +- **Open load**: k6's `constant-arrival-rate` executor sends a fixed number of requests per second + whatever the latency, and reports the requests it could not send (`dropped`). +- **Server side** from the deployment's own log stream (`npx convex logs --success --jsonl`), + started before the load and drained after it: every function execution of every request, grouped + by request id. `logCompleteness` is the HTTP actions logged over the requests k6 sent; every run + below logged all of them. A stored file's download does not appear in the logs, so + `billedCallsPerRequest` adds one for each answer whose body is a stored file. Convex counts a + query served from its cache as a call too. +- **The client** is one laptop in Chișinău, so client latency includes the round trip to the + deployments; the server-side numbers do not depend on it. + +Run it: + +```sh +brew install k6 # or https://grafana.com/docs/k6/latest/set-up/install-k6/ +node bench/run.ts convex-hosting-0.14.0 --run --files 400 --rate 25 --duration 60s +node bench/run.ts convex-hosting-branch --run --files 400 --rate 25 --duration 60s +node bench/run.ts static-hosting-0.2.1 --run --files 400 --rate 25 --duration 60s +node bench/report.ts +``` + +The first run of a target creates its project in the team in `BENCH_TEAM` (default `nicu`) and +deploys; `--no-deploy` reuses the deployed site. `bench/.work/` holds the apps and the packed build +of this repository's package; `bench/results//` holds one JSON file per case and k6's own +summary next to it. This repository keeps the 2026-11-11 summary only; the per-case results of every +run below are on the branch +[`nicu-hosting-bench`](https://github.com/samebase/convex-hosting/tree/nicu-hosting-bench/bench/results). + +## Results, 2026-11-11 + +The published packages and Cloudflare Workers, the same method: 400 files, two rounds at 25 +requests/s for 60 s per case, targets taking turns. Every response passed its checks; the Convex +logs held every request. All three Convex deployments are in `aws-us-east-1`, class `s256`. + +| Case | Workers: billed / $ per million | 0.15.0: billed / $ per million | 0.14.0: billed / $ per million | static-hosting 0.2.1: billed / $ per million | +| -------- | ------------------------------: | -----------------------------: | -----------------------------: | -------------------------------------------: | +| file | 0 / $0 | 2 / $4.00 | 3 / $6.00 | 3 / $6.00 | +| rendered | 1 / $0.30 | 1 / $2.00 | 2 / $4.00 | cannot render | + +Prices beyond each paid plan's included usage: Convex Professional, $2 per million function calls; +Workers Paid, $0.30 per million requests, static asset requests free. Not counted: Convex action +compute and egress, Workers CPU time. The Convex counts are measured, from logs that held every +request. The Workers counts follow from its routing and Cloudflare's pricing: `wrangler tail` +samples, so it showed that the script ran for the rendered page and never for a file, not how often. + +HTTP action median, the mean of the two rounds: a file 46.3 ms on 0.15.0, 66.3 ms on 0.14.0, 34.0 ms +on static-hosting; a rendered page 4.2 ms on 0.15.0, 26.5 ms on 0.14.0. Client latency from +Chișinău, where Cloudflare answered from Chișinău itself and Convex from US East: about 16 ms for +Workers and 140 to 380 ms for the Convex targets, which measures the distance more than the hosting. + +`node bench/graphic.ts 2026-11-11-comparison 2026-11-11-round-1 2026-11-11-round-2` draws +`results/2026-11-11-comparison.png`. + +## Results, 2026-11-04 + +400 files. Two rounds at 25 requests/s for 60 s per case (1,500 requests each), one at 100 +requests/s (6,000 each), targets taking turns. Every response passed its checks, k6 dropped no +request, and the logs held every request. `node bench/report.ts ` prints the full tables. +"0.15.0" in this section is a build from before the release, at commit `e4b3e7f`; see Provenance. + +**Calls per request.** The same in every round: + +| Case | 0.14.0: functions / billed | 0.15.0: functions / billed | static-hosting 0.2.1: functions / billed | +| -------- | -------------------------: | -------------------------: | ---------------------------------------: | +| page | 2 / 3 | **1 / 2** | 2 / 3 | +| asset | 2 / 3 | **1 / 2** | 2 / 3 | +| rendered | 2 / 2 | **1 / 1** | cannot render | + +**HTTP action time**, the median in ms of each round, from the deployment's logs: + +| Case | Rate | 0.14.0 | 0.15.0 | static-hosting 0.2.1 | +| -------- | ----- | ---------- | ---------- | -------------------- | +| page | 25/s | 83.7, 94.2 | 57.6, 52.6 | 41.2, 41.8 | +| page | 100/s | 85.8 | 50.4 | 40.9 | +| asset | 25/s | 80.2, 77.7 | 52.4, 51.8 | 41.2, 41.9 | +| rendered | 25/s | 38.5, 52.1 | 6.8, 6.5 | | +| rendered | 100/s | 37.1 | 6.3 | | + +What the numbers say: + +- **0.15.0 runs one function per request**; 0.14.0 and static-hosting run two. With the download of + a stored body, which Convex bills too, a file costs 2 calls in place of 3, and a rendered page 1 + in place of 2. A flood of one million file requests is 2 million billed calls, not 3 million. +- **A rendered page is about 6 to 8 times faster** in the action (6.5 ms against 37 to 52 ms), since + the action no longer waits for a query. +- **A file is about 30 ms faster than 0.14.0 and about 10 ms slower than static-hosting.** + static-hosting's action runs inside the component, so it reads the file from storage directly; an + app's action cannot read a component's storage, so 0.14.0 and 0.15.0 fetch the file's storage URL. + The price of static-hosting's way is the second function, and that its component can hand a + request to the app's code only as a buffered function call, so it renders no page. +- **Query cache.** static-hosting's `resolveAsset` takes only the path, so Convex answered all of + its calls from the query cache (`cachedResult: true` in the logs), which is cheap in time but is + still a call. 0.14.0's `route` takes the full URL, so a unique query string made every call run. +- **Client latency** includes the round trip from Chișinău; its tails moved between rounds by more + than the targets differ (0.15.0 page p95: 734 ms in round 1, 248 ms in round 2), so the tables + above use the deployment's own times. + +**Large sites.** 0.15.0 carries the site's files in the pushed code, so its cost grows with the +number of files. The release's numbers are in [design](../docs/design.md), under "The site's files": +4.2 ms per request at 10,000 files and 7.5 ms at 100,000, against 3.8 ms for an empty action. +Measured here, on the build from before the release: + +- a real 10,000-file site (a 0.89 MB `version.js`) served the same as 400 files: HTTP action median + 51.1 ms for the page, 51.3 ms for the asset, 6.7 ms for the rendered page, one function per + request, every check passed (`2026-11-04-files-10000`); +- deploying those 10,000 files took 1,519 s: about 360 `npx convex run` calls, each its own process + (`knownFiles` per 119 files, `generateUploadUrls` per 100, `recordFiles` per 60, and 5 pages of + storage URLs), and the files themselves, four at a time. Deploy time grows with the file count; + serving does not; +- 100,000 files is the most that the CLI accepts, Cloudflare's limit per Worker version. + +**Provenance.** The 0.15.0 deployment of the 2026-11-04 runs was built at commit `e4b3e7f`, a week +before the release; the `commit` field of those results is the checkout's HEAD when each case ran. +The release serves the same way, one HTTP action and no query, but reads the site's files +differently: that build decoded only the entries of the manifest that a lookup touched, and the +release decodes the whole manifest for each request. The 2026-11-11 runs measure the release. diff --git a/bench/graphic.ts b/bench/graphic.ts new file mode 100644 index 0000000..a704c8a --- /dev/null +++ b/bench/graphic.ts @@ -0,0 +1,219 @@ +// Draws the benchmark as one image for a post: what a million requests cost on each target, and, +// for the three Convex packages, the HTTP action's time. It reads the runs given, takes the mean of +// their per-round values, and writes bench/results/.html, .json, and .png (Chrome, headless). +// node bench/graphic.ts [ ...] +import { execFileSync } from "node:child_process"; +import { readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const BENCH = new URL(".", import.meta.url).pathname; +const [out, ...runs] = process.argv.slice(2); +if (out === undefined || runs.length === 0) { + throw new Error("Usage: node bench/graphic.ts [ ...]"); +} + +/** List prices beyond what each paid plan includes, checked 2026-11-11. */ +const PRICE = { + // Convex Professional: 25M function calls included, then $2 per million. + convexCall: 2 / 1e6, + // Cloudflare Workers Paid (Standard): 10M requests included, then $0.30 per million. Requests to + // static assets are free and unlimited. + workerRequest: 0.3 / 1e6, +}; + +const TARGETS = [ + { id: "workers", name: "Cloudflare Workers", note: "static assets" }, + { id: "convex-hosting-0.15.0", name: "convex-hosting 0.15.0", note: "" }, + { id: "convex-hosting-0.14.0", name: "convex-hosting 0.14.0", note: "" }, + { id: "static-hosting-0.2.1", name: "static-hosting 0.2.1", note: "" }, +] as const; +const ACCENT = "convex-hosting-0.15.0"; + +type Result = { + target: string; + case: string; + client: { requests: number; checksPassed: number; latencyMs: { median: number } }; + server: { + billedCallsPerRequest: number | null; + logCompleteness?: number | null; + httpActionMs?: { median: number | null; mean?: number | null }; + }; +}; + +const results: Result[] = runs.flatMap((run) => { + const dir = join(BENCH, "results", run); + return readdirSync(dir) + .filter((name) => name.endsWith(".json") && !name.endsWith(".k6.json")) + .map((name) => JSON.parse(readFileSync(join(dir, name), "utf8"))); +}); +for (const r of results) { + if (r.client.checksPassed !== 1) throw new Error(`${r.target} ${r.case}: a check failed.`); + if (r.server.logCompleteness != null && r.server.logCompleteness < 0.99) { + throw new Error( + `${r.target} ${r.case}: the logs hold ${r.server.logCompleteness} of requests.`, + ); + } +} + +const mean = (values: number[]) => values.reduce((a, b) => a + b, 0) / values.length; +function measure(target: string, caseName: string) { + const rounds = results.filter((r) => r.target === target && r.case === caseName); + if (rounds.length === 0) return null; + // 0.14.0 marks its version live at the first requests after a deploy, a few calls in a round. + const calls = rounds.map( + (r) => Math.round((r.server.billedCallsPerRequest ?? Number.NaN) * 100) / 100, + ); + if (new Set(calls.map(Math.round)).size !== 1) { + throw new Error(`${target} ${caseName}: calls differ: ${calls}`); + } + calls[0] = Math.round(calls[0]); + const price = target === "workers" ? PRICE.workerRequest : PRICE.convexCall; + const actionMs = rounds.map((r) => r.server.httpActionMs?.median ?? Number.NaN); + return { + rounds: rounds.length, + requests: rounds.reduce((sum, r) => sum + r.client.requests, 0), + billedPerRequest: calls[0], + dollarsPerMillion: calls[0] * price * 1e6, + httpActionMedianMs: target === "workers" ? null : mean(actionMs), + httpActionMedianMsByRound: target === "workers" ? null : actionMs, + clientMedianMs: mean(rounds.map((r) => r.client.latencyMs.median)), + }; +} + +const CASES = [ + { id: "asset", title: "A file of the build", detail: "a script; index.html costs the same" }, + { + id: "rendered", + title: "A page the app renders", + detail: "a path with no file, answered by code", + }, +]; +const data = Object.fromEntries( + CASES.map((c) => [c.id, Object.fromEntries(TARGETS.map((t) => [t.id, measure(t.id, c.id)]))]), +); +const page = Object.fromEntries(TARGETS.map((t) => [t.id, measure(t.id, "page")])); +writeFileSync( + join(BENCH, "results", `${out}.json`), + `${JSON.stringify({ runs, prices: PRICE, cases: { ...data, page } }, null, 2)}\n`, +); + +/** The length in px of a bar at the top of its band's scale. */ +const SCALE = 250; + +const money = (dollars: number) => (dollars === 0 ? "$0" : `$${dollars.toFixed(2)}`); +const escape = (text: string) => text.replace(/&/g, "&").replace(/, + max: number, +) { + const body = rows + .map((row) => { + const width = row.value === null ? 0 : Math.round((Math.max(row.value, 0) / max) * SCALE); + const bar = + row.value === null + ? `${escape(row.empty ?? "")}` + : `${escape(row.label)}`; + return `
${escape(row.name)}
${bar}
`; + }) + .join(""); + return `

${escape(title)}

${escape(detail)}

${body}
`; +} + +const costPanels = CASES.map((c) => { + const rows = TARGETS.map((t) => { + const m = data[c.id][t.id]; + if (m === null) + return { id: t.id, name: t.name, value: null, label: "", empty: "renders no page" }; + const free = t.id === "workers" && m.dollarsPerMillion === 0; + const unit = t.id === "workers" ? "request" : m.billedPerRequest === 1 ? "call" : "calls"; + const label = free + ? "$0 · static assets are free" + : `${money(m.dollarsPerMillion)} · ${m.billedPerRequest} ${unit}`; + return { id: t.id, name: t.name, value: m.dollarsPerMillion, label }; + }); + return panel(c.title, c.detail, rows, 6); +}).join(""); + +const timePanels = CASES.map((c) => { + const rows = TARGETS.filter((t) => t.id !== "workers").map((t) => { + const m = data[c.id][t.id]; + if (m === null) + return { id: t.id, name: t.name, value: null, label: "", empty: "renders no page" }; + return { + id: t.id, + name: t.name, + value: m.httpActionMedianMs, + label: `${m.httpActionMedianMs?.toFixed(1)} ms`, + }; + }); + return panel(c.title, "", rows, 70); +}).join(""); + +const html = ` +Hosting benchmark + + + + +

What one million requests cost

+

The same 400-file site on each, with every request reaching the server, as in a flood.

+

Dollars per million requests

at list price, beyond each plan's included usage
+
${costPanels}
+

Time in the HTTP action

median, from each deployment's logs; Convex only
+
${timePanels}
+
${escape(FOOTNOTE())}
+ +`; + +function FOOTNOTE() { + return ( + "Measured 2026-11-11: 25 requests/s for 60 s per case, two rounds, every response checked, calls counted from the platforms' logs. " + + "Convex Professional: $2 per million function calls beyond 25 million; a file's download from storage counts as a call. " + + "Workers Paid: $0.30 per million requests beyond 10 million. Not included: Convex action compute and egress, Workers CPU time. " + + "Convex deployments in US East; Workers answers from the nearest Cloudflare location. Method: github.com/samebase/convex-hosting/tree/nicu-hosting-bench/bench" + ); +} + +const htmlFile = join(BENCH, "results", `${out}.html`); +writeFileSync(htmlFile, html); +const png = join(BENCH, "results", `${out}.png`); +execFileSync("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [ + "--headless=new", + "--hide-scrollbars", + "--force-device-scale-factor=2", + "--window-size=1600,900", + "--virtual-time-budget=4000", + `--screenshot=${png}`, + `file://${htmlFile}`, +]); +console.log(png); diff --git a/bench/load.js b/bench/load.js new file mode 100644 index 0000000..bfcdd91 --- /dev/null +++ b/bench/load.js @@ -0,0 +1,43 @@ +// k6 load script for one case. Every request carries a unique query string, so no cache in front +// of the deployment answers it: each one reaches the HTTP action, as a flood would. Every response +// is checked for its status and for a marker in its body. +// +// k6 run -e BASE=https://.convex.site -e TARGET_PATH=/ -e STATUS=200 \ +// -e MARKER="Benchmark site" -e RATE=25 -e DURATION=60s -e OUT=summary.json load.js +import http from "k6/http"; +import { check } from "k6"; +import exec from "k6/execution"; + +const rate = Number(__ENV.RATE ?? 25); +export const options = { + scenarios: { + load: { + executor: "constant-arrival-rate", + rate, + timeUnit: "1s", + duration: __ENV.DURATION ?? "60s", + preAllocatedVUs: Math.max(20, rate * 2), + maxVUs: Math.max(200, rate * 10), + }, + }, + summaryTrendStats: ["avg", "min", "med", "p(90)", "p(95)", "p(99)", "max"], +}; + +const status = Number(__ENV.STATUS ?? 200); +const marker = __ENV.MARKER ?? ""; + +export default function () { + const url = `${__ENV.BASE}${__ENV.TARGET_PATH}?bench=${exec.scenario.iterationInTest}-${Date.now()}`; + const response = http.get(url, { + headers: { "Sec-Fetch-Mode": __ENV.FETCH_MODE ?? "no-cors" }, + redirects: 0, + }); + check(response, { + status: (r) => r.status === status, + body: (r) => typeof r.body === "string" && r.body.includes(marker), + }); +} + +export function handleSummary(data) { + return { [__ENV.OUT ?? "summary.json"]: JSON.stringify(data, null, 2) }; +} diff --git a/bench/report.ts b/bench/report.ts new file mode 100644 index 0000000..fb75c30 --- /dev/null +++ b/bench/report.ts @@ -0,0 +1,75 @@ +// Prints the results of one or more runs as Markdown tables: one row per target and case, with the +// function calls per request that the deployment's logs show, the calls Convex bills (the logged +// functions plus the download of a stored body), the HTTP action's own time, and the latency and +// throughput that k6 saw. +// node bench/report.ts [ ...] +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +type Result = { + target: string; + files: number; + rate: number; + duration: string; + case: string; + client: { + requests: number; + rate: number; + checksPassed: number; + dropped: number; + latencyMs: { median: number; p95: number; p99: number }; + }; + server: { + logCompleteness: number | null; + functionsPerRequest: number | null; + billedCallsPerRequest: number | null; + byFunction?: Record; + httpActionMs?: { median: number | null; p95: number | null }; + innerFunctionMs?: { median: number | null }; + /** A Cloudflare Workers target: the runs of its script that `wrangler tail` delivered. */ + sampledWorkerRuns?: number; + workerWallMs?: { median: number | null; p95: number | null }; + }; +}; + +const BENCH = new URL(".", import.meta.url).pathname; +const runs = process.argv.slice(2); +if (runs.length === 0) throw new Error("Usage: node bench/report.ts [ ...]"); + +const fixed = (value: number | null | undefined, digits = 0) => + value === null || value === undefined ? "n/a" : value.toFixed(digits); + +for (const run of runs) { + const dir = join(BENCH, "results", run); + const results: Result[] = readdirSync(dir) + .filter((name) => name.endsWith(".json") && !name.endsWith(".k6.json")) + .map((name) => JSON.parse(readFileSync(join(dir, name), "utf8"))); + const order = ["page", "asset", "rendered"]; + results.sort( + (a, b) => order.indexOf(a.case) - order.indexOf(b.case) || a.target.localeCompare(b.target), + ); + const first = results[0]; + console.log(`### ${run}: ${first.rate} requests/s for ${first.duration}, ${first.files} files\n`); + console.log( + "| Case | Target | Requests | Checks passed | Functions per request | Billed calls per request | HTTP action ms (median / p95) | Inner function ms (median) | Latency ms (median / p95 / p99) | Functions logged |", + ); + console.log("| --- | --- | --: | --: | --: | --: | --: | --: | --: | --- |"); + for (const r of results) { + const functions = + r.server.byFunction === undefined + ? `Worker runs sampled by wrangler tail: ${r.server.sampledWorkerRuns}` + : Object.entries(r.server.byFunction) + .map(([name, count]) => `${name}: ${count}`) + .join("
"); + const action = r.server.httpActionMs ?? r.server.workerWallMs; + console.log( + `| ${r.case} | ${r.target} | ${r.client.requests} | ${fixed(r.client.checksPassed * 100, 1)}% | ` + + `${fixed(r.server.functionsPerRequest, 2)} | ${fixed(r.server.billedCallsPerRequest, 2)} | ` + + `${fixed(action?.median, 1)} / ${fixed(action?.p95, 1)} | ` + + `${fixed(r.server.innerFunctionMs?.median, 1)} | ` + + `${fixed(r.client.latencyMs.median)} / ${fixed(r.client.latencyMs.p95)} / ${fixed(r.client.latencyMs.p99)} | ` + + `${functions} |`, + ); + } + console.log(""); +} diff --git a/bench/results/2026-11-11-comparison.json b/bench/results/2026-11-11-comparison.json new file mode 100644 index 0000000..756a5b0 --- /dev/null +++ b/bench/results/2026-11-11-comparison.json @@ -0,0 +1,115 @@ +{ + "runs": ["2026-11-11-round-1", "2026-11-11-round-2"], + "prices": { + "convexCall": 0.000002, + "workerRequest": 3e-7 + }, + "cases": { + "asset": { + "workers": { + "rounds": 2, + "requests": 3002, + "billedPerRequest": 0, + "dollarsPerMillion": 0, + "httpActionMedianMs": null, + "httpActionMedianMsByRound": null, + "clientMedianMs": 16.9905 + }, + "convex-hosting-0.15.0": { + "rounds": 2, + "requests": 3001, + "billedPerRequest": 2, + "dollarsPerMillion": 4, + "httpActionMedianMs": 46.2500515, + "httpActionMedianMsByRound": [46.197262, 46.302841], + "clientMedianMs": 357.6 + }, + "convex-hosting-0.14.0": { + "rounds": 2, + "requests": 3002, + "billedPerRequest": 3, + "dollarsPerMillion": 6, + "httpActionMedianMs": 66.28908799999999, + "httpActionMedianMsByRound": [66.688108, 65.890068], + "clientMedianMs": 380.97950000000003 + }, + "static-hosting-0.2.1": { + "rounds": 2, + "requests": 3000, + "billedPerRequest": 3, + "dollarsPerMillion": 6, + "httpActionMedianMs": 34.0004885, + "httpActionMedianMsByRound": [33.235066, 34.765910999999996], + "clientMedianMs": 350.879 + } + }, + "rendered": { + "workers": { + "rounds": 2, + "requests": 3001, + "billedPerRequest": 1, + "dollarsPerMillion": 0.3, + "httpActionMedianMs": null, + "httpActionMedianMsByRound": null, + "clientMedianMs": 12.932 + }, + "convex-hosting-0.15.0": { + "rounds": 2, + "requests": 3001, + "billedPerRequest": 1, + "dollarsPerMillion": 2, + "httpActionMedianMs": 4.2168995, + "httpActionMedianMsByRound": [4.186783, 4.247016], + "clientMedianMs": 140.34625 + }, + "convex-hosting-0.14.0": { + "rounds": 2, + "requests": 3001, + "billedPerRequest": 2, + "dollarsPerMillion": 4, + "httpActionMedianMs": 26.4774485, + "httpActionMedianMsByRound": [27.088506, 25.866391], + "clientMedianMs": 162.82375000000002 + }, + "static-hosting-0.2.1": null + }, + "page": { + "workers": { + "rounds": 2, + "requests": 3001, + "billedPerRequest": 0, + "dollarsPerMillion": 0, + "httpActionMedianMs": null, + "httpActionMedianMsByRound": null, + "clientMedianMs": 16.285249999999998 + }, + "convex-hosting-0.15.0": { + "rounds": 2, + "requests": 3002, + "billedPerRequest": 2, + "dollarsPerMillion": 4, + "httpActionMedianMs": 44.896046, + "httpActionMedianMsByRound": [43.69691400000001, 46.095178], + "clientMedianMs": 182.72199999999998 + }, + "convex-hosting-0.14.0": { + "rounds": 2, + "requests": 3002, + "billedPerRequest": 3, + "dollarsPerMillion": 6, + "httpActionMedianMs": 69.32060100000001, + "httpActionMedianMsByRound": [69.814107, 68.827095], + "clientMedianMs": 206.6915 + }, + "static-hosting-0.2.1": { + "rounds": 2, + "requests": 3000, + "billedPerRequest": 3, + "dollarsPerMillion": 6, + "httpActionMedianMs": 32.520264, + "httpActionMedianMsByRound": [32.670474, 32.370054], + "clientMedianMs": 170.94600000000003 + } + } + } +} diff --git a/bench/results/2026-11-11-comparison.png b/bench/results/2026-11-11-comparison.png new file mode 100644 index 0000000..0cc265f Binary files /dev/null and b/bench/results/2026-11-11-comparison.png differ diff --git a/bench/run.ts b/bench/run.ts new file mode 100644 index 0000000..cca1028 --- /dev/null +++ b/bench/run.ts @@ -0,0 +1,569 @@ +// Benchmarks one hosting target on its own Convex cloud project: it writes the target's app to +// bench/.work// with the package pinned to one exact version, deploys a synthetic site to +// the project's development deployment, then runs each case with k6 at a fixed arrival rate while +// it streams the deployment's function logs. One JSON file per case goes to bench/results//. +// +// node bench/run.ts --run [--files 400] [--rate 25] [--duration 60s] +// [--cases page,asset,rendered] [--no-deploy] +// +// Targets: convex-hosting-0.14.0 and convex-hosting-0.15.0 (npm), convex-hosting-branch (this +// checkout, packed), static-hosting-0.2.1 (npm, the component-owned mode its README calls the +// fastest), and workers: the same site as Cloudflare Workers static assets, with a Worker script +// that renders the same page, on workers.dev, whose server side comes from `wrangler tail`. +import { execFileSync, spawn } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { parseArgs } from "node:util"; +import { writeSite } from "./site.ts"; + +const BENCH = dirname(new URL(import.meta.url).pathname); +const REPO = resolve(BENCH, ".."); +const TEAM = process.env.BENCH_TEAM ?? "nicu"; +const CONVEX = "1.46.0"; + +/** A page that `worker` renders, for the case that no file answers. */ +const WORKER = `{ + fetch: async () => + new Response("Rendered

Rendered

", { + headers: { "Content-Type": "text/html; charset=utf-8" }, + }), +}`; + +const hostingConfig = `import { defineApp } from "convex/server"; +import hosting from "@samebase/convex-hosting/convex.config"; + +const app = defineApp(); +app.use(hosting); +export default app; +`; + +/** The app's `convex/http.ts` with one object, as `routeAll` takes it from 0.15.0 on. */ +const hostingHttpAssets = `import { httpRouter } from "convex/server"; +import { routeAll } from "@samebase/convex-hosting"; +import { components } from "./_generated/api.js"; +import { assets } from "../.convex-hosting/version.js"; + +const http = httpRouter(); +// A worker that renders one small page, so the rendered case measures hosting, not a framework. +routeAll({ http, component: components.hosting, assets, worker: ${WORKER} }); +export default http; +`; + +/** The same for 0.14.0, whose `routeAll` takes its arguments in order, with the version's id. */ +const hostingHttpVersionId = `import { httpRouter } from "convex/server"; +import { routeAll } from "@samebase/convex-hosting"; +import { components } from "./_generated/api.js"; +import { versionId } from "../.convex-hosting/version.js"; + +const http = httpRouter(); +// A worker that renders one small page, so the rendered case measures hosting, not a framework. +routeAll(http, components.hosting, versionId, ${WORKER}); +export default http; +`; + +type Target = { + /** Where it runs: a Convex project's development deployment, or Cloudflare Workers. */ + platform: "convex" | "workers"; + project: string; + dependencies: Record; + files: Record; + cases: CaseName[]; + deploy: (cwd: string) => void; +}; + +function packBranch(): string { + const dir = join(BENCH, ".work", "pack"); + mkdirSync(dir, { recursive: true }); + const output = execFileSync("pnpm", ["pack", "--pack-destination", dir], { + cwd: join(REPO, "packages", "convex-hosting"), + encoding: "utf8", + }); + const tarball = output.trim().split("\n").pop() ?? ""; + if (!tarball.endsWith(".tgz")) throw new Error(`pnpm pack printed no tarball:\n${output}`); + return tarball; +} + +const WRANGLER = "4.160.0"; + +const targets: Record Target> = { + "convex-hosting-0.15.0": () => ({ + platform: "convex", + project: "convex-hosting-bench", + dependencies: { "@samebase/convex-hosting": "0.15.0" }, + files: { "convex/convex.config.ts": hostingConfig, "convex/http.ts": hostingHttpAssets }, + cases: ["page", "asset", "rendered"], + deploy: (cwd) => sh(cwd, "npx", ["convex-hosting", "deploy", "--dev", "--dist", "site"]), + }), + workers: () => ({ + platform: "workers", + project: "convex-hosting-bench-workers", + dependencies: { wrangler: WRANGLER }, + files: { + "wrangler.jsonc": `${JSON.stringify( + { + name: "convex-hosting-bench-workers", + main: "worker.js", + compatibility_date: "2026-11-01", + workers_dev: true, + // Requests that match a file never run the Worker; the rest run it. + assets: { directory: "./site" }, + observability: { enabled: false }, + }, + null, + 2, + )}\n`, + // The same page as the Convex targets' worker. + "worker.js": `export default ${WORKER};\n`, + }, + cases: ["page", "asset", "rendered"], + deploy: (cwd) => { + const output = execFileSync("npx", ["wrangler", "deploy"], { cwd, encoding: "utf8" }); + process.stderr.write(output); + const url = /https:\/\/\S+\.workers\.dev/.exec(output)?.[0]; + if (url === undefined) throw new Error("wrangler deploy printed no workers.dev URL."); + writeFileSync(join(cwd, "site-url.txt"), `${url}\n`); + }, + }), + "convex-hosting-0.14.0": () => ({ + platform: "convex", + project: "convex-hosting-bench-014", + dependencies: { "@samebase/convex-hosting": "0.14.0" }, + files: { "convex/convex.config.ts": hostingConfig, "convex/http.ts": hostingHttpVersionId }, + cases: ["page", "asset", "rendered"], + deploy: (cwd) => sh(cwd, "npx", ["convex-hosting", "deploy", "--dev", "--dist", "site"]), + }), + "convex-hosting-branch": () => ({ + platform: "convex", + project: "convex-hosting-bench", + dependencies: { "@samebase/convex-hosting": `file:${packBranch()}` }, + files: { "convex/convex.config.ts": hostingConfig, "convex/http.ts": hostingHttpAssets }, + cases: ["page", "asset", "rendered"], + deploy: (cwd) => sh(cwd, "npx", ["convex-hosting", "deploy", "--dev", "--dist", "site"]), + }), + "static-hosting-0.2.1": () => ({ + platform: "convex", + project: "convex-hosting-bench-static", + dependencies: { "@convex-dev/static-hosting": "0.2.1" }, + files: { + "convex/convex.config.ts": `import { defineApp } from "convex/server"; +import staticHosting from "@convex-dev/static-hosting/convex.config"; + +// The component owns "/", the mode static-hosting's README calls the fastest. +const app = defineApp({ httpPrefix: "/api" }); +app.use(staticHosting, { httpPrefix: "/" }); +export default app; +`, + }, + // It renders no page: a path without a file answers its index.html or 404. + cases: ["page", "asset"], + deploy: (cwd) => { + sh(cwd, "npx", ["convex", "dev", "--once"]); + sh(cwd, "npx", ["@convex-dev/static-hosting", "upload", "--dist", "site", "--no-spa"]); + }, + }), +}; + +type CaseName = "page" | "asset" | "rendered"; +type Case = { + path: (paths: { asset: string }) => string; + marker: string; + fetchMode: string; + /** Whether the answer's body is a stored file, whose download Convex counts as a call. */ + download: boolean; +}; +const CASES: Record = { + page: { path: () => "/", marker: "Benchmark site", fetchMode: "navigate", download: true }, + asset: { + path: (paths) => paths.asset, + marker: "export const chunk", + fetchMode: "no-cors", + download: true, + }, + rendered: { path: () => "/rendered", marker: "Rendered", fetchMode: "navigate", download: false }, +}; + +function sh(cwd: string, command: string, args: string[]) { + execFileSync(command, args, { cwd, stdio: "inherit" }); +} + +/** The deployment and the site URL that the benchmark loads. */ +function siteOf(cwd: string, target: Target) { + if (target.platform === "workers") { + const site = readFileSync(join(cwd, "site-url.txt"), "utf8").trim(); + return { deployment: target.project, site }; + } + return convexEnv(cwd); +} + +function convexEnv(cwd: string) { + const env = readFileSync(join(cwd, ".env.local"), "utf8"); + const deployment = /^CONVEX_DEPLOYMENT=(?:dev:)?([a-z0-9-]+)/m.exec(env)?.[1]; + const site = /^CONVEX_SITE_URL=(\S+)/m.exec(env)?.[1]; + if (deployment === undefined) throw new Error(`${cwd}/.env.local has no CONVEX_DEPLOYMENT.`); + return { deployment, site: site ?? `https://${deployment}.convex.site` }; +} + +/** Writes the app and binds it to the target's project, creating the project on the first run. */ +function setUp(name: string, target: Target, files: number) { + const cwd = join(BENCH, ".work", name); + mkdirSync(join(cwd, "convex"), { recursive: true }); + const pkg = { + name: `bench-${name}`, + private: true, + type: "module", + dependencies: { convex: CONVEX, ...target.dependencies }, + }; + writeFileSync(join(cwd, "package.json"), `${JSON.stringify(pkg, null, 2)}\n`); + for (const [path, body] of Object.entries(target.files)) writeFileSync(join(cwd, path), body); + sh(cwd, "npm", ["install", "--no-audit", "--no-fund", "--loglevel=error"]); + if (target.platform === "convex" && !existsSync(join(cwd, ".env.local"))) { + const configure = (kind: string) => + execFileSync( + "npx", + [ + "convex", + "dev", + "--once", + "--configure", + kind, + "--team", + TEAM, + "--project", + target.project, + "--dev-deployment", + "cloud", + ], + { cwd, stdio: "inherit" }, + ); + // The first push fails while `.convex-hosting/version.js` does not exist yet; the project and + // `.env.local` are configured by then, which is what this step is for. + try { + configure("existing"); + } catch { + if (!existsSync(join(cwd, ".env.local"))) { + try { + configure("new"); + } catch { + if (!existsSync(join(cwd, ".env.local"))) + throw new Error(`Configuring ${target.project} failed.`); + } + } + } + } + const paths = writeSite(files, cwd); + return { cwd, paths }; +} + +const median = (values: number[]) => quantile(values, 0.5); +function quantile(values: number[], q: number) { + if (values.length === 0) return null; + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]; +} + +type LogEntry = { + kind: string; + udfType: string; + identifier: string; + componentPath: string | null; + requestId: string; + executionId: string; + timestamp: number; + executionTime: number; + success: { status?: string } | null; +}; + +/** Runs one case with k6 while the deployment's logs stream to a file, and measures both. */ +async function runCase( + cwd: string, + site: string, + caseName: CaseName, + paths: { asset: string }, + options: { rate: number; duration: string; out: string; target: Target }, +) { + const spec = CASES[caseName]; + const workers = options.target.platform === "workers"; + const logFile = `${options.out}.logs.jsonl`; + // Convex's log stream of the deployment, or Cloudflare's tail of the Worker, which reports each + // run of the Worker script and nothing for a request that a static asset answers. + const logs = workers + ? spawn("npx", ["wrangler", "tail", options.target.project, "--format", "json"], { + cwd, + stdio: ["ignore", "pipe", "ignore"], + }) + : spawn("npx", ["convex", "logs", "--success", "--jsonl"], { + cwd, + stdio: ["ignore", "pipe", "ignore"], + }); + const chunks: Buffer[] = []; + logs.stdout.on("data", (chunk: Buffer) => chunks.push(chunk)); + await new Promise((done) => setTimeout(done, 8000)); + const start = Date.now() / 1000; + const summaryFile = `${options.out}.k6.json`; + execFileSync( + "k6", + [ + "run", + "--quiet", + "-e", + `BASE=${site}`, + "-e", + `TARGET_PATH=${spec.path(paths)}`, + "-e", + "STATUS=200", + "-e", + `MARKER=${spec.marker}`, + "-e", + `FETCH_MODE=${spec.fetchMode}`, + "-e", + `RATE=${options.rate}`, + "-e", + `DURATION=${options.duration}`, + "-e", + `OUT=${summaryFile}`, + join(BENCH, "load.js"), + ], + { stdio: "inherit" }, + ); + const end = Date.now() / 1000; + // Logs arrive a few seconds after the executions. + await new Promise((done) => setTimeout(done, 15000)); + logs.kill(); + writeFileSync(logFile, Buffer.concat(chunks)); + if (workers) { + return { + case: caseName, + path: spec.path(paths), + client: clientOf(`${options.out}.k6.json`), + server: workerRuns(Buffer.concat(chunks).toString("utf8"), start, end, summaryFile), + }; + } + + const entries: LogEntry[] = Buffer.concat(chunks) + .toString("utf8") + .split("\n") + .flatMap((line) => { + try { + const entry = JSON.parse(line); + return entry?.kind === "Completion" ? [entry] : []; + } catch { + return []; + } + }) + .filter((entry) => entry.timestamp >= start - 1 && entry.timestamp <= end + 10); + const unique = [...new Map(entries.map((entry) => [entry.executionId, entry])).values()]; + const http = unique.filter((entry) => entry.udfType === "HttpAction"); + const requestIds = new Set(http.map((entry) => entry.requestId)); + const inner = unique.filter( + (entry) => entry.udfType !== "HttpAction" && requestIds.has(entry.requestId), + ); + const byFunction: Record = {}; + for (const entry of [...http, ...inner]) { + const key = `${entry.udfType} ${entry.componentPath ? `${entry.componentPath}/` : ""}${entry.identifier}`; + byFunction[key] = (byFunction[key] ?? 0) + 1; + } + const k6 = JSON.parse(readFileSync(summaryFile, "utf8")); + const metric = (name: string) => k6.metrics[name]?.values ?? {}; + const requests = metric("http_reqs").count ?? 0; + const checks = metric("checks"); + const executionsPerRequest = + http.length === 0 ? null : (http.length + inner.length) / http.length; + const passRate = checks.rate ?? 0; + return { + case: caseName, + path: spec.path(paths), + client: { + requests, + rate: metric("http_reqs").rate, + checksPassed: passRate, + failed: metric("http_req_failed").rate, + dropped: metric("dropped_iterations").count ?? 0, + latencyMs: { + median: metric("http_req_duration").med, + p90: metric("http_req_duration")["p(90)"], + p95: metric("http_req_duration")["p(95)"], + p99: metric("http_req_duration")["p(99)"], + max: metric("http_req_duration").max, + }, + }, + server: { + httpActionsLogged: http.length, + logCompleteness: requests === 0 ? null : http.length / requests, + functionsPerRequest: executionsPerRequest, + downloadsPerRequest: spec.download ? 1 : 0, + billedCallsPerRequest: + executionsPerRequest === null ? null : executionsPerRequest + (spec.download ? 1 : 0), + byFunction, + httpActionMs: { + median: median(http.map((entry) => entry.executionTime * 1000)), + // The mean, which action compute is billed on. + mean: + http.length === 0 + ? null + : http.reduce((sum, entry) => sum + entry.executionTime * 1000, 0) / http.length, + p95: quantile( + http.map((entry) => entry.executionTime * 1000), + 0.95, + ), + }, + innerFunctionMs: { + median: median(inner.map((entry) => entry.executionTime * 1000)), + p95: quantile( + inner.map((entry) => entry.executionTime * 1000), + 0.95, + ), + }, + }, + }; +} + +/** What k6 saw. */ +function clientOf(summaryFile: string) { + const k6 = JSON.parse(readFileSync(summaryFile, "utf8")); + const metric = (name: string) => k6.metrics[name]?.values ?? {}; + return { + requests: metric("http_reqs").count ?? 0, + rate: metric("http_reqs").rate, + checksPassed: metric("checks").rate ?? 0, + failed: metric("http_req_failed").rate, + dropped: metric("dropped_iterations").count ?? 0, + latencyMs: { + median: metric("http_req_duration").med, + p90: metric("http_req_duration")["p(90)"], + p95: metric("http_req_duration")["p(95)"], + p99: metric("http_req_duration")["p(99)"], + max: metric("http_req_duration").max, + }, + }; +} + +/** The JSON objects of `wrangler tail --format json`, which prints each event over many lines. */ +function tailEvents(text: string): Array> { + const events = []; + let depth = 0; + let begin = -1; + let inString = false; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (inString) { + if (c === "\\") i++; + else if (c === '"') inString = false; + } else if (c === '"') inString = true; + else if (c === "{") { + if (depth++ === 0) begin = i; + } else if (c === "}" && --depth === 0) { + try { + events.push(JSON.parse(text.slice(begin, i + 1))); + } catch {} + } + } + return events; +} + +/** + * The runs of the Worker script during the load. Cloudflare bills a run as a request and does not + * bill a request that a static asset answers. `wrangler tail` samples: it delivered 17 of 51 runs at + * 5 requests/s. A request runs the script once or not at all, so a case with any run costs one + * billed request per request, and a case with none costs nothing. + */ +function workerRuns(text: string, start: number, end: number, summaryFile: string) { + const requests = clientOf(summaryFile).requests; + const runs = tailEvents(text).filter( + (event) => + String(event.event?.request?.url ?? "").includes("?bench=") && + event.eventTimestamp / 1000 >= start - 1 && + event.eventTimestamp / 1000 <= end + 10, + ); + const wall = runs.map((event) => Number(event.wallTime)); + const cpu = runs.map((event) => Number(event.cpuTime)); + const mean = (values: number[]) => + values.length === 0 ? null : values.reduce((a, b) => a + b, 0) / values.length; + const perRequest = requests === 0 ? null : runs.length > 0 ? 1 : 0; + return { + sampledWorkerRuns: runs.length, + outcomes: Object.fromEntries( + [...new Set(runs.map((event) => String(event.outcome)))].map((outcome) => [ + outcome, + runs.filter((event) => event.outcome === outcome).length, + ]), + ), + functionsPerRequest: perRequest, + downloadsPerRequest: 0, + billedCallsPerRequest: perRequest, + workerWallMs: { median: median(wall), mean: mean(wall), p95: quantile(wall, 0.95) }, + workerCpuMs: { median: median(cpu), mean: mean(cpu), p95: quantile(cpu, 0.95) }, + }; +} + +async function main() { + const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + run: { type: "string" }, + files: { type: "string", default: "400" }, + rate: { type: "string", default: "25" }, + duration: { type: "string", default: "60s" }, + cases: { type: "string" }, + "no-deploy": { type: "boolean", default: false }, + }, + }); + const [name] = positionals; + const make = targets[name ?? ""]; + if (make === undefined || values.run === undefined) { + throw new Error( + `Usage: node bench/run.ts <${Object.keys(targets).join(" | ")}> --run [options]`, + ); + } + const target = make(); + const files = Number(values.files); + const { cwd, paths } = setUp(name, target, files); + let deploySeconds: number | null = null; + if (!values["no-deploy"]) { + const started = Date.now(); + target.deploy(cwd); + deploySeconds = (Date.now() - started) / 1000; + console.error(`Deployed ${files} files in ${deploySeconds.toFixed(0)} s.`); + } + const { deployment, site } = siteOf(cwd, target); + const cases = (values.cases?.split(",") ?? target.cases) as CaseName[]; + const outDir = join(BENCH, "results", values.run); + mkdirSync(outDir, { recursive: true }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { cwd: REPO, encoding: "utf8" }).trim(); + for (const caseName of cases) { + const out = join(outDir, `${name}-${files}-${caseName}`); + console.error( + `${name}, ${files} files, ${caseName}: ${values.rate}/s for ${values.duration} on ${site}`, + ); + const result = await runCase(cwd, site, caseName, paths, { + rate: Number(values.rate), + duration: values.duration, + out, + target, + }); + const record = { + target: name, + // The packed branch build lives in bench/.work/pack, whatever the checkout's path. + dependencies: Object.fromEntries( + Object.entries(target.dependencies).map(([name, spec]) => [ + name, + spec.replace(`file:${BENCH}/`, "file:bench/"), + ]), + ), + convex: CONVEX, + commit, + deployment, + files, + deploySeconds, + rate: Number(values.rate), + duration: values.duration, + date: new Date().toISOString(), + ...result, + }; + writeFileSync(`${out}.json`, `${JSON.stringify(record, null, 2)}\n`); + console.error( + JSON.stringify({ case: caseName, client: result.client, server: result.server }, null, 2), + ); + } +} + +await main(); diff --git a/bench/site.ts b/bench/site.ts new file mode 100644 index 0000000..7c0462f --- /dev/null +++ b/bench/site.ts @@ -0,0 +1,39 @@ +// Writes a synthetic built site to `/site`: an index page, a 404 page, and `count` scripts of +// about 2 KB, named the way Vite names chunks. Every file has its own bytes, so every file is stored +// once. The path of a script in the middle goes to `/paths.json`, outside the site. +// node site.ts +import { createHash } from "node:crypto"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +export function writeSite(count: number, dir: string) { + const site = join(dir, "site"); + rmSync(site, { recursive: true, force: true }); + mkdirSync(join(site, "assets"), { recursive: true }); + const names: string[] = []; + for (let i = 0; i < count; i++) { + const body = `export const chunk${i} = ${JSON.stringify("x".repeat(2000))}; // chunk ${i}\n`; + const hash = createHash("sha256").update(body).digest("base64url").slice(0, 8); + const name = `/assets/chunk-${i}-${hash}.js`; + writeFileSync(join(site, name), body); + names.push(name); + } + const page = (title: string) => + `${title}` + + `

${title}

\n`; + writeFileSync(join(site, "index.html"), page("Benchmark site")); + writeFileSync(join(site, "404.html"), page("Not found")); + const paths = { asset: names[Math.floor(count / 2)] }; + writeFileSync(join(dir, "paths.json"), `${JSON.stringify(paths)}\n`); + return paths; +} + +if (import.meta.main) { + const count = Number(process.argv[2]); + const dir = process.argv[3]; + if (!Number.isInteger(count) || count < 1 || dir === undefined) { + throw new Error("Usage: node site.ts "); + } + writeSite(count, dir); + console.log(`Wrote ${count} scripts, index.html and 404.html to ${join(dir, "site")}.`); +}