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

Open
#56 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Refactor
Clarity
Clearly specified
Activity status
Active
Tech stack
postgresql, redis, typescript

Research direction

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.

Written by the indexing model from the issue text.

Description

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.
Dominant language
TypeScript
Stars
2
Forks
1
Avg merge
6m
Merged PRs (30d)
27

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from sumamakhan761/tryinstance

All issues in sumamakhan761/tryinstance

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.