Skip to content

perf(d1): cut ~54% of D1 rows read from analytics page loads - #3

Merged
scobb merged 4 commits into
mainfrom
perf/d1-read-reduction
Sep 4, 2026
Merged

scobb merged 4 commits into
mainfrom
perf/d1-read-reduction

Conversation

@scobb

@scobb scobb commented Sep 4, 2026

Copy link
Copy Markdown
Owner

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:

Query Rows read Read:return Share
SELECT COUNT(*) FROM pageviews WHERE site_id = ? 2.2B 19,383:1 25% of all reads
json_each event-properties cross join 2.52B 2,170:1 29.8% of total runtime

The 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, served Cache-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

  • Public dashboard refresh is visibility-gated — reloads only when visible and older than 5 minutes. A backgrounded tab never reloads; returning to a stale tab refreshes it immediately, so readers still see fresh data.
  • selectAnalyticsEmptyState takes hasAnyDataEver: boolean, backed by buildSiteHasPageviewsQuery() → SELECT 1 ... LIMIT 1. Measured on a seeded 365k-row site: 8.75ms scanning 365,000 rows → 0.01ms scanning 1.
  • Event properties moved behind on-demand endpoints — GET /dashboard/sites/:id/event-properties (ownership-checked) and GET /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.md identifies 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 typecheck passes
  • npm run test passes — 113 tests, 109 pass, 0 fail (4 pre-existing skips for the standalone WordPress plugin repo)
  • Manual smoke test in browser
  • Watch D1 Insights for a few days post-deploy to confirm where reads settle

Notes on test rigour:

  • Unit seams were written test-first and observed failing before implementation (6 failures, each for the expected reason).
  • test/public-dashboard-refresh.test.ts executes 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.
  • The four page-load guards in test/analytics-page-load-queries.test.ts passed 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_events batch queries, since those are billed per render.

Not addressed here

  • The other three custom_events page-load queries (996M + 991M + 494M ≈ 2.48B rows, 29%) — worth revisiting after this lands and the numbers settle.
  • The same json_each shape in src/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.ts runs an unbounded COUNT(DISTINCT substr(timestamp,1,10)) ... WHERE site_id = ? per site per day before its hasMinimumDataDays early exit, and runTrafficAlerts fires 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

Ralph (Keylight Digital) and others added 2 commits September 4, 2026 09:17
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>
@scobb

scobb commented Sep 4, 2026

Copy link
Copy Markdown
Owner Author

Correction after local verification

Ran this against wrangler dev with 120 seeded pageviews and 60 custom events. Two things in the original description were wrong, and one was a real bug.

The 60s self-reload was on the embed widget, not the public dashboard

/public/:site_id has no auto-reload at all. The setTimeout(() => location.reload(), 60000) was in /embed/:siteId, a separate template in the same file. The embed widget runs three cheap day-bounded queries per reload — a site lookup, today's pageview count, and today's top 3 paths — none of which appear in the production top ten.

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 strftime('%Y-%m-%d') events query at 82,469 is consistent with the rest once you account for the today range using strftime('%H') instead. I just can't yet say what drives that volume.

A real bug: the Load button was inert

The 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".

Unaffected

Fixes 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

Check Result
Public dashboard page load 200, placeholder only, no json_each, no all-time COUNT(*)
Load button (real browser) fetches and renders plan=pro 28, plan=free 14, three sources at 14 — matches seed
Button after load removes itself
Console 0 errors (1 pre-existing Tailwind CDN warning)
/dashboard/…/event-properties unauthenticated 302
/public/unknown/event-properties 404
Embed widget gated refresh present, unconditional reload gone
Suite 115 tests, 111 pass, 0 fail, typecheck clean

The "Manual smoke test in browser" box is now genuinely ticked.

Ralph (Keylight Digital) and others added 2 commits September 4, 2026 11:11
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>
@scobb
scobb merged commit 3fcadd1 into main Sep 4, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant