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

オープン
#56 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
35/100
issue の種類
リファクタリング
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
postgresql, redis, typescript

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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.
主要言語
TypeScript
スター
2
フォーク
1
平均マージ
6分
マージ済み PR(30日)
27

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

sumamakhan761/tryinstance のほかの issue

sumamakhan761/tryinstance の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。