perf(api): eliminate unbounded in-memory queries and redundant DB fan-out across Analytics, Sales Chat, CRM, and Bio-Links

Aperta
#56 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Refactoring
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
postgresql, redis, typescript

Direzione di ricerca

Start by reading the four named service files and tracing the query and response shapes for each endpoint. Run the existing API tests for analytics, sales chat, CRM exports, and bio-links to establish current behavior. Work through the listed query and pagination changes while preserving response shapes; done means bounded database work, accurate filtered pagination, and unchanged endpoint responses.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

backend
Problem Description

Four core read endpoints perform unbounded findMany queries, in-memory aggregations, or redundant query fan-out that work at <100 users but cause high latency, DB connection exhaustion, or Node OOM errors at 1,000–10,000+ users:

  1. Analytics (apps/api/src/analytics/analytics.service.ts, getAllData L1166-1215 + 7 query methods):

    • getAllData fans out to 13 methods in Promise.all, redundantly executing getOverview 5x, getPipelineStagesAnalytics 3x, getDailyTrends 2x, and getAccountIds 15+x (~60-80 DB queries per page load).
    • getPipelineStagesAnalytics, getTagDistributionAnalytics, getFollowUpEngineAnalytics, getIntentAnalytics, getOriginAttributionAnalytics, and getSalesChat execute unbounded findMany queries (several without timeRange filters) and aggregate in Node.js memory.
  2. Sales Chat (apps/api/src/sales-chat/services/sales-chat-query.service.ts, getConversations L127-335):

    • Tag, qualified/unqualified, and followup_due filters load all matching instagramUserProfile / pendingFollowUp rows for the workspace into Node memory and pass large in/notIn arrays to PostgreSQL.
    • automationExecution.findMany (L310-335) omits distinct: ['instagramUserId'], loading all historical execution records for every conversation on the page.
  3. CRM Email / Audience List (apps/api/src/crm/services/crm-export.service.ts, getEmailList L42-95, L162-180, L250-258):

    • Every GET request runs an unbounded "self-healing" sync over all instagramUserProfile rows with email != null || phone != null, issuing N+1 findUnique + upsert queries.
    • allStatsCaptures loads all matching contactCapture rows into Node memory on every paginated request just to count emails and phones.
    • channelFilter (email, phone, both) is applied in memory after take/skip and count(), causing inaccurate total/hasMore values and short/empty pages.
  4. Bio-Links (apps/api/src/bio-links/bio-links.service.ts, getAnalytics L733-903 & getBioPageLeads L905-913):

    • getAnalytics loads every BioAnalyticsEvent row for 30d/90d/all into Node memory and runs O(events * (links + buttons)) .filter(...) loops. Viral pages (100k+ events) risk timeouts or OOM.
    • getBioPageLeads returns all leads with no pagination (take/skip).

Expected Behavior
  1. All 4 endpoints return the exact same JSON response shapes (zero frontend breaking changes).
  2. Aggregations and counts are computed in PostgreSQL (COUNT, GROUP BY, SUM) instead of loading unbounded tables into Node memory.
  3. AnalyticsService.getAllData resolves shared sub-results once per request and optionally caches per-company responses safely in Redis (with graceful fallback when Redis is unavailable locally).
  4. getEmailList returns accurate total and hasMore when channelFilter is active, without running N+1 syncs on read requests.

Where to Look
  • apps/api/src/analytics/analytics.service.ts
  • apps/api/src/sales-chat/services/sales-chat-query.service.ts
  • apps/api/src/crm/services/crm-export.service.ts
  • apps/api/src/bio-links/bio-links.service.ts

Solution / Implementation Guide (Zero-Regression Plan)
  1. Analytics (analytics.service.ts):

    • Compute accountIds, overview, pipelineStages, and dailyTrends once in getAllData and pass them as optional precomputed parameters into dependent methods (keeping standalone method calls backward-compatible).
    • Replace unbounded findMany + JS loops with prisma.groupBy / count / parameterized SQL GROUP BY queries bounded by timeRange.
    • Add a short-TTL Redis cache (30-60s, keyed by companyId + timeRange) wrapped in try/catch so local dev without Redis still works cleanly.
  2. Sales Chat (sales-chat-query.service.ts):

    • Add distinct: ['instagramUserId'] (ordered by startedAt: 'desc') to automationExecution.findMany.
    • Push tag, qualified, and followup_due filters into SQL/indexed Prisma where / orderBy clauses instead of loading full-company ID arrays into Node memory.
  3. CRM Email List (crm-export.service.ts):

    • Move the instagramUserProfile -> contactCapture sync out of GET /email-list into write paths (or a one-time backfill script) so reads stay pure SELECTs.
    • Push channelFilter (email, phone, both) into the Prisma whereClause before count() and take/skip so pagination and hasMore are exact.
    • Replace allStatsCaptures in-memory counting with prisma.contactCapture.count(...) / SQL COUNT aggregations.
  4. Bio-Links (bio-links.service.ts):

    • Replace the full bioAnalyticsEvent.findMany + nested .filter(...) loops in getAnalytics with SQL GROUP BY aggregations (by day, type, device, referrer, linkId, platform), preserving the exact return object structure.
    • Add optional limit / offset pagination (defaulting to a safe cap like 100) to getBioPageLeads.
Lingua principale
TypeScript
Stelle
2
Fork
1
Merge medio
6m
PR unite (30g)
27

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di sumamakhan761/tryinstance

Tutte le issue di sumamakhan761/tryinstance

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.