Repository navigation
Description
Problem
The Topics list page takes seconds to open. One server action, getTopicsOverview, downloads the brand's entire 30-day result set to the client and aggregates it in JavaScript — 73 MB of JSON across 33 sequential HTTP round trips, to render 20 table rows.
The topic detail page already does this correctly: one action wrapping a Promise.all of six aggregate RPCs. The list page is the only surface still shipping raw rows.
Evidence
The scan, web/src/lib/actions/topic.ts#L374-L392:
for (let from = 0; from < TOPIC_RESULTS_MAX_ROWS; from += TOPIC_RESULTS_PAGE_SIZE) {
const { data, error } = await supabase
.from('prompt_results')
.select('prompt_id, created_at, visibility_score, mention_count, citation_count, mention_position, competitor_mentions')
...
.range(from, from + TOPIC_RESULTS_PAGE_SIZE - 1);
}Two independent costs, separated by a controlled A/B against the live database on the largest brand (32,607 rows in the window — 3.8× the next brand):
| requests | raw JSON | wall clock | |
|---|---|---|---|
| as written | 33 | 73.1 MB | 19,334 ms |
identical scan minus competitor_mentions |
33 | 5.1 MB | 7,032 ms |
- ~12.3 s is one over-fetched column.
competitor_mentionsaverages 10.9 entries per row and accounts for 68 of the 73 MB. The page renders one competitor name per topic. Every entry is detoasted, JSON-encoded, gzipped, shipped, gunzipped and parsed to compute that. - ~7.0 s is the 33 sequential round trips.
.awaitsits inside theforloop, and.range()becomesLIMIT/OFFSET, so page k re-walks k×1000 rows.EXPLAIN (ANALYZE, BUFFERS)at five offsets shows buffers growing linearly with offset (≈offset + 1,063); summed over 33 pages that is ~563,000 buffer touches (~4.3 GB) to read 32,607 rows once. A single-pass aggregate touches 28,028 buffers.
What this is not — measured and ruled out, so nobody chases it
- Not N+1. No query runs inside a per-row loop.
- Not a missing index.
idx_prompt_results_brand_createdserves the predicate; per-page execution is 3–61 ms. - Not RLS. Re-run under
authenticatedwith JWT claims: 55.5 ms vs 50.4 ms as service role. The policy is a hashed SubPlan evaluated once. - Not the statement timeout. Worst individual page is ~795 ms wall / 61 ms exec against an 8 s limit.
- Not client-side work.
JSON.parsemeasured at 265 ms; the aggregation loop is bounded well under that. Together under 3% of wall clock. - Not the suggestions card. It deliberately does not fetch until expanded.
Proposal
Move the aggregation into Postgres, matching the pattern the Insights surfaces already use (insights_aggregates, competitor_aggregates, share_of_voice_aggregates — all security_invoker, and the first two already accept a p_topic_id).
Add topics_overview_aggregates(p_brand_id uuid) returning one row per topic: answer counts, mention/citation answers, position sum and n for each window, mention and citation totals, distinct active and visible prompts, max(created_at), the 14-day daily buckets, and the competitor rollup. Then delete the paging loop and keep the existing computeAiVisibilityScore maths in JS over ~20 rows.
The equivalent aggregation was written and run against the live database (read-only, no migration applied):
full aggregate incl. daily sparkline + competitor rollup → 769 ms, 28,028 buffers, 17 kB output
same with NOT MATERIALIZED (planner inlines and parallelises) → 306 ms, 2 workers
73 MB → 17 kB, 33 requests → 1.
Two things to fix in the same change
TOPIC_RESULTS_MAX_ROWS = 50_000is a silent correctness cliff (topic.ts#L161). The largest brand is at 32,607 — 65% of the way there. Crossing it truncates the loop with no error, understating mentions, citations and share of voice. Same class of bug as Topics: leaderboard numbers disagree with Insights — unpaginated scan, no shopping exclusion, fixed window #464, which this constant was added to fix. Aggregating server-side removes the cliff rather than raising it.visibility_scoreis selected and never read. It appears exactly once in the file, in that select.
Measurement caveat
The end-to-end timings above were taken from a developer machine against the hosted project, where base round-trip latency is ~130 ms. In production the web app and the database are co-located, so the round-trip component (~7 s here) shrinks substantially; the payload component does not, being CPU-bound on detoast, JSON build, gzip and parse. A realistic production figure is 4–8 s rather than 19.6 s. The ranking of causes is unaffected — over-fetch first, request count second — and the proposed fix addresses both.
Acceptance criteria
- The Topics list page issues one aggregate call per brand instead of a paged scan, and transfers kilobytes rather than megabytes.
- The numbers rendered are identical to today's for the same brand and window, including the 14-day sparkline and the top competitor per topic.
- No client-side row cap remains, so a brand crossing any threshold cannot silently under-report.
- Topics with no results still render, with zeros rather than being dropped.
Activity
feat(web): one date range control across Visibility, Citations and Pr…
perf(topics): aggregate the overview in Postgres instead of downloadi…