Repository navigation
Closed
Labels
Description
Problem
/dashboard/insights is slow to load. The cause is the data layer, not the UI:
- The insights server actions in
web/src/lib/actions/tracking.tspull full rows (from('prompt_results').select('*')) and aggregate in JS —getInsightsSummary,getShareOfVoiceData, andgetCompetitorComparisoneach loop over the fetched rows (reduce/for…of) instead of letting Postgres compute the totals. As a brand accumulates results (thousands of rows), this transfers a lot of data and computes in Node on every load. - The page (
insights/page.tsx) fires 4–5 of these actions in parallel on every mount, each doing multiple Supabase round-trips (prompt_results + prompts + topics). - No caching anywhere on this path.
prompt_resultshas single-column indexes (brand_id,created_at,prompt_id) but no composite(brand_id, created_at)— the exact shape the brand + date-range filters need.
Goal
Make the insights page fast without hiding fresh data: on-demand Run All / Refresh results / Test Single Prompt must still reflect immediately (these update prompt_results synchronously). So a blind long-TTL cache is a non-goal — freshness on write is a hard requirement.
Proposed approach (phased)
1. Aggregate in the DB instead of JS (biggest win, cache-independent)
- Replace
select('*')+ JS reduce with SQL aggregation — Postgres RPC functions or views that return the summary / share-of-voice / competitor metrics already computed. Select only needed columns. - Add a composite index
(brand_id, created_at DESC)onprompt_results(and any others the new queries need).
2. (Optional, larger) Precomputed daily summaries
- Scheduled tracking runs ~daily. Have the tracking worker write a per-brand/day summary row (e.g.
daily_insights) on each run, so reads become trivial lookups that are always fresh (refreshed exactly when data changes — no TTL/staleness tradeoff).
3. Caching with invalidation (complement)
- Cache the read paths (Next 16
use cache+cacheTag, orunstable_cache) and invalidate (updateTag) when tracking/refresh writes new results, so cached reads are fast but on-demand updates appear immediately.
Start with (1) — it likely removes most of the latency on its own. (2)/(3) build on it.
Acceptance criteria
- Insights page load time meaningfully reduced (measure before/after on a brand with many results)
- Reported numbers are unchanged vs the current implementation (no metric regressions)
- On-demand Run All / Refresh / Test Single Prompt still reflect immediately (no stale-until-TTL)
- Appropriate indexes added where missing
Out of scope
UI changes, visibility-scoring changes, and any long-TTL cache that delays on-demand updates.
Activity
perf(insights): aggregate insights data in Postgres instead of pullin…