Skip to content

perf(topics): aggregate the overview in Postgres instead of downloading it - #726

Merged
gkhngyk merged 1 commit into
mainfrom
fix/721-topics-overview-aggregate
Aug 14, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
fix/721-topics-overview-aggregate

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Summary

The Topics page fetched the brand's entire 30-day result set to render twenty table rows — 33 sequential requests, 73 MB of JSON, 19.3 s end to end on the largest brand.

topics_overview_aggregates does in Postgres what the client was doing in JavaScript. Only the AI Visibility Score stays on the client, over ~20 rows, so this page and the Insights headline keep computing it from one implementation.

before after
requests 33 1
payload 73.1 MB 33 kB
time 19,334 ms 736 ms (function), ~1.0 s over HTTP

Correctness first

The old client-side aggregation and the new function were run side by side against the live database before the page was switched over. They agree exactly on all seventeen topics, across every field: answers, mention answers, citation answers, position sum and n, total mentions, total citations, competitor mentions, active prompts, visible prompts and last run.

Two details that would have broken it silently and are handled explicitly:

  • Sparkline buckets are keyed in UTC (AT TIME ZONE 'UTC'), because the client builds the same keys from Date.toISOString(). Reading them in the session timezone would shift every bucket by the offset and quietly redraw the trend.
  • Window boundaries resolve inside the function, from the database's clock, rather than being passed in from the caller's.

The 4.5 s detour, and why the competitor rollup re-scans

The first working version was still 4.5 s with 7,500 temp blocks. rows is referenced several times, so Postgres materialises it — and carrying competitor_mentions through that materialisation spills 32k detoasted jsonb values to disk. It was the same over-fetch as before, just moved inside the database.

Reading that column only where it is needed, in its own scan, brought the function to 736 ms. The CTE comment says so, since the shape looks redundant otherwise.

The 50,000-row cliff is gone

TOPIC_RESULTS_MAX_ROWS stopped the scan at 50,000 rows with no error. The largest brand was at 32,607 — 65% of the way there — and crossing it would have understated every figure on the page. Same class of defect as #464, which the constant was added to fix. Aggregating server-side removes the cliff rather than raising it.

visibility_score was also being selected and never read; it is gone with the scan.

Related issue

Closes #721

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Open Topics on a brand with a lot of history — it should render in about a second rather than stalling.
  2. Compare the table against what it showed before: visibility rate, change, mentions, citations, share of voice, top competitor, active/visible prompts, last run and the sparkline shape must all be unchanged.
  3. A topic with prompts but no answers in the window still appears, with zeros — dropping it would make the roster disagree with itself.
  4. Brands with little data are unaffected.

yarn typecheck, yarn lint (6 pre-existing warnings, 0 errors), yarn format:check and yarn build pass locally.

The types file is regenerated to include the new function — without it supabase.rpc('topics_overview_aggregates', …) does not type-check.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • supabase/schema.sql regenerated via bash supabase/build-schema.sh
  • Changes are focused — one concern per PR

…ng it

The page fetched the brand's entire 30-day result set to render twenty table
rows. On the largest brand that was 33 sequential requests and 73 MB of JSON,
measured end to end at 19.3 s.

Two costs, separated by a controlled A/B: ~12.3 s was one over-fetched column
— competitor_mentions, averaging eleven entries per row, downloaded to derive
a single top competitor per topic — and ~7.0 s was the round trips, since
.range() becomes LIMIT/OFFSET and page k re-walks k×1000 rows. Buffers grew
linearly with offset: ~563k touches to read 32,607 rows once, against 28k for
a single pass.

topics_overview_aggregates does in Postgres what the client was doing in
JavaScript. Only the AI Visibility Score stays here, over ~20 rows, so this
page and the Insights headline keep computing it from one implementation.

The competitor rollup deliberately re-scans prompt_results rather than
reusing the shared CTE. `rows` is referenced several times, so Postgres
materialises it, and carrying the jsonb through that materialisation spilled
32k detoasted values to temp files — 4.5 s and 7,500 temp blocks. Reading the
column only where it is needed brought the function to 736 ms.

Also removes the 50,000-row ceiling. The largest brand was at 32,607 and
crossing it would have truncated the scan with no error, understating every
figure on the page — the same class of defect as #464, which the constant was
added to fix. Aggregating server-side removes the cliff instead of raising it.

Verified against the live database before switching the page over: the old
client-side aggregation and the new function were run side by side on the
largest brand and agree exactly on all seventeen topics across answers,
mention and citation answers, position sum and n, total mentions and
citations, competitor mentions, active and visible prompts, and last run.

Closes #721
@gkhngyk
gkhngyk merged commit e83bb85 into main Aug 14, 2026
5 checks passed
@gkhngyk
gkhngyk deleted the fix/721-topics-overview-aggregate branch August 14, 2026 19:29
@gkhngyk gkhngyk mentioned this pull request Aug 24, 2026
7 of 12 tasks
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.

Topics: the overview downloads 73 MB over 33 sequential requests to render 20 rows

1 participant