Repository navigation
perf(d1): cut ~54% of D1 rows read from analytics page loads - #3
Conversation
D1 bills rows scanned, not queries. Production D1 Insights over the last 30
days showed 8.66B rows read across the top ten queries, with two statements in
the analytics page-load batch accounting for ~4.7B of them:
- SELECT COUNT(*) FROM pageviews WHERE site_id = ? 2.2B rows (25% of reads)
19,383 rows scanned per row returned, to answer a yes/no question.
- the json_each event-properties cross join 2.52B rows (29.8% runtime)
~2,170 rows scanned per row returned, for a panel most views never open.
Both scale with a site's accumulated history, so the cost climbed daily even
when traffic did not. Multiplying them was the public dashboard's unconditional
`setTimeout(() => location.reload(), 60000)`, served Cache-Control: no-store —
one forgotten tab re-ran the full batch 1,440 times a day. Execution counts
clustered at ~114,000, i.e. ~114k renders in 30 days from a handful of tabs.
Changes:
- Public dashboard refreshes only when visible and older than 5 minutes; a
backgrounded tab never reloads, and returning to a stale one refreshes it
immediately so readers still see fresh data.
- selectAnalyticsEmptyState takes hasAnyDataEver: boolean, backed by
`SELECT 1 ... LIMIT 1`. On a 365k-row site: 8.75ms/365,000 rows -> 0.01ms/1 row.
- Event properties moved behind on-demand endpoints, ownership-checked for
/dashboard and public-flag-checked for /public. No cache: KV writes are the
one dimension already near its included limit, so trading D1 reads for KV
writes would move the cost rather than remove it.
Batch sizes go 17->16 (dashboard) and 16->15 (public); batchRes indices verified.
The remaining three custom_events batch queries (~2.48B rows, 29%) are
untouched, as is the same json_each shape in routes/api.ts, where callers expect
the data inline.
Test plan:
- npm run typecheck passes
- npm test: 113 tests, 109 pass, 0 fail (4 pre-existing skips)
- Unit seams written test-first and observed failing before implementation.
- The four page-load guards in test/analytics-page-load-queries.test.ts were
verified against a deliberately reintroduced regression: three flip to
failing with the old queries restored, and pass once reverted.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…dget Local verification caught two mistakes in the previous commit. 1. The event-properties click handler was inserted into the wrong template. public.ts renders two pages — the public dashboard (/public/:site_id) and the embed widget (/embed/:siteId) — and the script landed on the widget, which has no properties panel. The dashboard rendered the Load button with no listener behind it, so clicking it did nothing. Moved to the dashboard template; removed from the widget. The existing guards could not see this: they assert on which SQL a page load issues, and an inert button issues none. Added two assertions covering the handler's presence and the widget's contents, and verified both fail against the reintroduced bug. 2. The commit message and PR described the unconditional `setTimeout(() => location.reload(), 60000)` as belonging to the public dashboard. It was on the embed widget. The public dashboard has no auto-reload at all. The refresh gating is therefore correctly placed but its saving is smaller than claimed: the widget runs three cheap day-bounded queries per reload (site lookup, today's count, today's top 3 paths), not the analytics batch. None of them appear in the production top ten. Still worth gating — an embedded widget reloading every 60s forever on a third-party page is pure waste — but it does not explain the ~114,000 analytics renders, and the real driver of those remains unidentified. Fixes 2 and 3 are unaffected: both target queries measured directly in D1 Insights, and both are verified gone from the page-load path. Verified locally against wrangler dev with 120 seeded pageviews and 60 custom events: panel renders a placeholder, Load fetches and renders the real breakdown (plan=pro 28, plan=free 14, three sources at 14 — matching the seed), button removes itself, 0 console errors. The on-demand endpoints return 302 unauthenticated (/dashboard) and 404 for unknown sites (/public). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Correction after local verificationRan this against The 60s self-reload was on the embed widget, not the public dashboard
So the refresh gating is correctly placed and still worth having (an embedded widget reloading every 60s forever on someone else's page is pure waste), but it does not explain the ~114,000 analytics renders, and I no longer have an explanation for those. The "forgotten tab" story in the PR description was attached to the wrong route. What still holds: ~114k analytics batch renders over 30 days is solid, inferred from four different queries in that batch clustering at 111,931–114,326 executions. The A real bug: the Load button was inertThe click handler went into the embed widget's template instead of the dashboard's. The panel rendered correctly and no query fired — so the SQL guards all passed — but clicking Load did nothing. Fixed in 5cdcfe4, with two new assertions covering handler presence, verified against the reintroduced bug. This is a gap worth naming: asserting on which queries a page runs cannot distinguish "correctly deferred" from "broken and therefore silent". UnaffectedFixes 2 and 3 stand — both target queries measured directly in D1 Insights, and both are confirmed gone from the page-load path. The ~54% projection rests entirely on those two and does not depend on the refresh change. Verified locally
The "Manual smoke test in browser" box is now genuinely ticked. |
A bare "Load" button sitting in the panel header read as a failure state — the header no longer matched the other breakdown panels, and the body said "Not loaded", which looks like something went wrong rather than something deliberate. The trigger now occupies the body, where the table itself renders, so the panel reads as an intentional affordance: a full-width target labelled "Show breakdown by properties", with a muted second line explaining why it defers. The header is now identical to Top Pages, Referrer Sources and the rest. Since the trigger lives inside the body, replacing the body's innerHTML removes it — the explicit btn.remove() is gone. The error path relabels the button in place instead of blanking it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Leaves a single-line trigger. The nested spans went with it; the click handler already falls back to the button itself when there is no child element, so the loading and error labels still work unchanged. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Summary
D1 bills rows scanned, not queries. Production D1 Insights for the last 30 days shows 8.66B rows read across the top ten queries — about a third of the 25B included in the Workers Paid allowance, and climbing.
Two statements in the analytics page-load batch account for ~4.7B of that:
SELECT COUNT(*) FROM pageviews WHERE site_id = ?json_eachevent-properties cross joinThe first answers a yes/no question (has this site ever recorded a pageview?) by scanning every row the site has ever recorded. The second expands each event row by its property count to fill a panel most dashboard views never open.
Both scale with a site's accumulated history rather than its traffic, which is why reads ramped daily even on quiet days.
Multiplying them: the public dashboard ran
setTimeout(() => location.reload(), 60000)unconditionally, servedCache-Control: no-store. One forgotten tab re-ran the full 16-query batch 1,440 times a day. Execution counts across four different queries in that batch clustered at ~114,000 — roughly 114k renders in 30 days, ~2.6/minute sustained, from a handful of open tabs.Prior COGS analysis (
COGS-REPORT.md,docs/cogs-analysis.md) missed all of this because it counted a D1 "read" as one query, reporting the dashboard at "33 reads" per load.Changes
selectAnalyticsEmptyStatetakeshasAnyDataEver: boolean, backed bybuildSiteHasPageviewsQuery()→SELECT 1 ... LIMIT 1. Measured on a seeded 365k-row site: 8.75ms scanning 365,000 rows → 0.01ms scanning 1.GET /dashboard/sites/:id/event-properties(ownership-checked) andGET /public/:site_id/event-properties(public-flag-checked). The panel renders a placeholder with a Load button.Deliberately no KV cache on the event-properties query:
docs/cogs-analysis.mdidentifies KV writes as the one dimension already near its included limit, so caching would move the cost rather than remove it. Not running the query is strictly better than caching it.Batch sizes go 17→16 (dashboard) and 16→15 (public);
batchRes[n]indices verified in both.Test plan
npm run typecheckpassesnpm run testpasses — 113 tests, 109 pass, 0 fail (4 pre-existing skips for the standalone WordPress plugin repo)Notes on test rigour:
test/public-dashboard-refresh.test.tsexecutes the real inline script against stubbed browser globals rather than regex-matching it, covering all four states: hidden/stale, visible/fresh, visible/stale, and hidden→visible.test/analytics-page-load-queries.test.tspassed immediately, which proves nothing — so they were verified against a deliberately reintroduced regression. Three flip to failing with the old queries restored, and pass once reverted.Expected effect
The two query fixes remove ~4.7B rows/month directly (~54% of the 8.66B visible). The refresh fix scales down whatever fraction of those ~114k renders came from background tabs — which also reduces the four remaining
custom_eventsbatch queries, since those are billed per render.Not addressed here
custom_eventspage-load queries (996M + 991M + 494M ≈ 2.48B rows, 29%) — worth revisiting after this lands and the numbers settle.json_eachshape insrc/routes/api.ts:263. It wasn't in the top ten and API callers expect the data inline, so lazy-loading is the wrong fix there.scheduled.tsruns an unboundedCOUNT(DISTINCT substr(timestamp,1,10)) ... WHERE site_id = ?per site per day before itshasMinimumDataDaysearly exit, andrunTrafficAlertsfires on both cron triggers so it runs twice on Mondays. Neither appears in the top ten today, but both scale with site count. Separate PR.🤖 Generated with Claude Code