Skip to content

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

Closed

Description

@gkhngyk

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_mentions averages 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. .await sits inside the for loop, and .range() becomes LIMIT/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_created serves the predicate; per-page execution is 3–61 ms.
  • Not RLS. Re-run under authenticated with 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.parse measured 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

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

  1. added
    bug
    topics
    on Aug 13, 2026
  2. added a commit that references this issue on Aug 15, 2026
    e83bb85
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugtopics

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions