Repository navigation
Description
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:
-
The "has any data" check scans the whole table.
hasFiltersis true on the default view (datePreset !== 'all', and the default is24h), so thelimit: 1call fires — but it passes no date filter, so it scans the brand's entireprompt_resultshistory. AndgetPromptResults(web/src/lib/actions/tracking.ts) doesselect('*')with no SQL limit: it materializes every row (all heavy columns — full response text,citations/competitor_mentionsJSON) into the Node process, then slices in JS.limit: 1is misleading — the function still fetches everything just to computetotal = rows.length. This single unboundedselect('*')scan is the dominant first-load cost. -
getPromptResultsover-fetches in general. Even the windowed (24h) data call usesselect('*')and derivestotalfromrows.length, so it can't use a SQLLIMITand always pulls all heavy columns for the window.
Proposed change
Required
- Make the "has any data" check a count, not a scan. Replace the
getPromptResults(..., { limit: 1 })call with a cheapcount: 'exact', head: truequery (no rows, no columns). This removes the one unboundedselect('*')scan from the load path. - Fix
getPromptResultsfetch shape inweb/src/lib/actions/tracking.ts:- derive
totalfrom a separatecount: 'exact', head: truequery, - push the row cap into SQL via
.range()/.limit()instead of fetching everything and slicing in JS, - select only the columns the row list actually needs (the full response text isn't needed for the table — it's already lazy-loaded on expand).
This also speeds up perf(topics): speed up the topic detail page — collapse 6 serialized server actions into one #312, which calls the same function.
- derive
- Collapse the per-load server actions into one
getInsightsData(brand.id, filterOpts)action that runs the queries with a real server-sidePromise.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. totalmust stay accurate (from thecountquery), 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 newgetInsightsDataconsolidator.
How to test
- Open
/dashboard/insightson a brand with a large history → first paint is noticeably faster; the unbounded full-table scan is gone (check there's noselect('*')over the whole history in the load path). - Every number matches the current page (KPI strip, competitor, SoV, trend, and the expandable table's per-topic/prompt rollups) for the same filters.
- "Showing N of TOTAL" shows the correct TOTAL.
- Filters (date / model / region / topic) and the empty states behave exactly as before.
Notes
- No DB schema change.
- Related: perf(topics): speed up the topic detail page — collapse 6 serialized server actions into one #312 (same server-action serialization pattern; shares the
getPromptResultsfix).
Activity
perf(insights): drop the full-table scan on load + use SQL limit/count (
fix(prompts): consolidate the page's first load into one server action
fix(prompts): consolidate the page's first load into one server action (
feat(topics): persisted AI topic suggestions on the Topics page (#497)