Skip to content

perf(insights): drop the full-table scan on load + use SQL limit/count instead of fetching all rows #313

Closed

Description

@gkhngyk

Problem

/dashboard/insights is slow on first load. The whole page is gated behind a single isLoading flag, so nothing paints until every request the page fires has resolved — and one of them scans the brand's entire history.

This shares the server-action serialization root cause with #312 (topic detail), and the getPromptResults fix below benefits both pages.

Root cause (from the code)

loadData() fires several server actions through one Promise.all. Next.js processes server actions sequentially (each is a separate queued POST), so latency is roughly their sum, not the slowest. On the default 24h view the calls are:

const promises = [
  getInsightsSummary(brand.id, filterOpts),
  getPromptResults(brand.id, { limit: PROMPT_RESULTS_ROW_LIMIT /* 1500 */, ...filterOpts }),
  getCompetitorComparison(brand.id, filterOpts),
  getShareOfVoiceData(brand.id, filterOpts),
  hasFilters
    ? getPromptResults(brand.id, { limit: 1 }).then(({ total }) => ({ total }))  // ← no date filter
    : Promise.resolve(null),
];

plus a separate getTopics(brand.id) in another effect.

Two concrete costs:

  1. The "has any data" check scans the whole table. hasFilters is true on the default view (datePreset !== 'all', and the default is 24h), so the limit: 1 call fires — but it passes no date filter, so it scans the brand's entire prompt_results history. And getPromptResults (web/src/lib/actions/tracking.ts) does select('*') with no SQL limit: it materializes every row (all heavy columns — full response text, citations / competitor_mentions JSON) into the Node process, then slices in JS. limit: 1 is misleading — the function still fetches everything just to compute total = rows.length. This single unbounded select('*') scan is the dominant first-load cost.

  2. getPromptResults over-fetches in general. Even the windowed (24h) data call uses select('*') and derives total from rows.length, so it can't use a SQL LIMIT and always pulls all heavy columns for the window.

Proposed change

Required

  1. Make the "has any data" check a count, not a scan. Replace the getPromptResults(..., { limit: 1 }) call with a cheap count: 'exact', head: true query (no rows, no columns). This removes the one unbounded select('*') scan from the load path.
  2. Fix getPromptResults fetch shape in web/src/lib/actions/tracking.ts:
  3. Collapse the per-load server actions into one getInsightsData(brand.id, filterOpts) action that runs the queries with a real server-side Promise.all (genuinely parallel, one round trip), removing the serialization penalty.

No behavior change

This is a performance refactor — the displayed rows, the grouped insights table, and every shown number must stay identical:

  • The row list is already capped at PROMPT_RESULTS_ROW_LIMIT (1500) via the current JS slice; pushing the same cap into SQL returns the same rows (newest first), so the table and its per-group rollups are unchanged.
  • total must stay accurate (from the count query), so "Showing 1500 of N" still shows the true N.
  • The KPI strip, competitor table, SoV, and trend already come from their own full-window server actions and are untouched.

Files to touch

  • web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx — swap the data-existence check to a count; call one consolidated action.
  • web/src/lib/actions/tracking.ts — getPromptResults (count-based total, SQL limit, narrower select) and a new getInsightsData consolidator.

How to test

  1. Open /dashboard/insights on a brand with a large history → first paint is noticeably faster; the unbounded full-table scan is gone (check there's no select('*') over the whole history in the load path).
  2. Every number matches the current page (KPI strip, competitor, SoV, trend, and the expandable table's per-topic/prompt rollups) for the same filters.
  3. "Showing N of TOTAL" shows the correct TOTAL.
  4. Filters (date / model / region / topic) and the empty states behave exactly as before.

Notes

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

    enhancementhelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions