perf(api): eliminate unbounded in-memory queries and redundant DB fan-out across Analytics, Sales Chat, CRM, and Bio-Links
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
- Domain
- analytics, api, backend, databases, performance
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
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:
-
Analytics (
apps/api/src/analytics/analytics.service.ts,getAllDataL1166-1215 + 7 query methods):getAllDatafans out to 13 methods inPromise.all, redundantly executinggetOverview5x,getPipelineStagesAnalytics3x,getDailyTrends2x, andgetAccountIds15+x (~60-80 DB queries per page load).getPipelineStagesAnalytics,getTagDistributionAnalytics,getFollowUpEngineAnalytics,getIntentAnalytics,getOriginAttributionAnalytics, andgetSalesChatexecute unboundedfindManyqueries (several withouttimeRangefilters) and aggregate in Node.js memory.
-
Sales Chat (
apps/api/src/sales-chat/services/sales-chat-query.service.ts,getConversationsL127-335):- Tag, qualified/unqualified, and
followup_duefilters load all matchinginstagramUserProfile/pendingFollowUprows for the workspace into Node memory and pass largein/notInarrays to PostgreSQL. automationExecution.findMany(L310-335) omitsdistinct: ['instagramUserId'], loading all historical execution records for every conversation on the page.
- Tag, qualified/unqualified, and
-
CRM Email / Audience List (
apps/api/src/crm/services/crm-export.service.ts,getEmailListL42-95, L162-180, L250-258):- Every
GETrequest runs an unbounded "self-healing" sync over allinstagramUserProfilerows withemail != null || phone != null, issuing N+1findUnique+upsertqueries. allStatsCapturesloads all matchingcontactCapturerows into Node memory on every paginated request just to count emails and phones.channelFilter(email,phone,both) is applied in memory aftertake/skipandcount(), causing inaccuratetotal/hasMorevalues and short/empty pages.
- Every
-
Bio-Links (
apps/api/src/bio-links/bio-links.service.ts,getAnalyticsL733-903 &getBioPageLeadsL905-913):getAnalyticsloads everyBioAnalyticsEventrow for30d/90d/allinto Node memory and runsO(events * (links + buttons)).filter(...)loops. Viral pages (100k+ events) risk timeouts or OOM.getBioPageLeadsreturns all leads with no pagination (take/skip).
Expected Behavior
- All 4 endpoints return the exact same JSON response shapes (zero frontend breaking changes).
- Aggregations and counts are computed in PostgreSQL (
COUNT,GROUP BY,SUM) instead of loading unbounded tables into Node memory. AnalyticsService.getAllDataresolves shared sub-results once per request and optionally caches per-company responses safely in Redis (with graceful fallback when Redis is unavailable locally).getEmailListreturns accuratetotalandhasMorewhenchannelFilteris active, without running N+1 syncs on read requests.
Where to Look
apps/api/src/analytics/analytics.service.tsapps/api/src/sales-chat/services/sales-chat-query.service.tsapps/api/src/crm/services/crm-export.service.tsapps/api/src/bio-links/bio-links.service.ts
Solution / Implementation Guide (Zero-Regression Plan)
-
Analytics (
analytics.service.ts):- Compute
accountIds,overview,pipelineStages, anddailyTrendsonce ingetAllDataand pass them as optional precomputed parameters into dependent methods (keeping standalone method calls backward-compatible). - Replace unbounded
findMany+ JS loops withprisma.groupBy/count/ parameterized SQLGROUP BYqueries bounded bytimeRange. - Add a short-TTL Redis cache (
30-60s, keyed bycompanyId + timeRange) wrapped intry/catchso local dev without Redis still works cleanly.
- Compute
-
Sales Chat (
sales-chat-query.service.ts):- Add
distinct: ['instagramUserId'](ordered bystartedAt: 'desc') toautomationExecution.findMany. - Push tag, qualified, and
followup_duefilters into SQL/indexed Prismawhere/orderByclauses instead of loading full-company ID arrays into Node memory.
- Add
-
CRM Email List (
crm-export.service.ts):- Move the
instagramUserProfile -> contactCapturesync out ofGET /email-listinto write paths (or a one-time backfill script) so reads stay pureSELECTs. - Push
channelFilter(email,phone,both) into the PrismawhereClausebeforecount()andtake/skipso pagination andhasMoreare exact. - Replace
allStatsCapturesin-memory counting withprisma.contactCapture.count(...)/ SQLCOUNTaggregations.
- Move the
-
Bio-Links (
bio-links.service.ts):- Replace the full
bioAnalyticsEvent.findMany+ nested.filter(...)loops ingetAnalyticswith SQLGROUP BYaggregations (by day, type, device, referrer,linkId,platform), preserving the exact return object structure. - Add optional
limit/offsetpagination (defaulting to a safe cap like100) togetBioPageLeads.
- Replace the full
- Dominant language
- TypeScript
- Stars
- 2
- Forks
- 1
- Avg merge
- 6m
- Merged PRs (30d)
- 27
Getting set up
- Ships a Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from sumamakhan761/tryinstance
-
backend good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
sumamakhan761/tryinstance#65 ·
Maintainers usually reply within 1 day
-
backend good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
sumamakhan761/tryinstance#64 ·
Maintainers usually reply within 1 day
-
backend good first issue
Difficulty 1/5 1-3 hours Newbie friendliness 88/100
sumamakhan761/tryinstance#63 ·
Maintainers usually reply within 1 day
-
backend good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
sumamakhan761/tryinstance#62 ·
Maintainers usually reply within 1 day
-
backend good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
sumamakhan761/tryinstance#60 ·
Maintainers usually reply within 1 day
All issues in sumamakhan761/tryinstance
Similar issues
-
prio:low scope:hud
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
OliverRomhagen/vrigstad-joyride#953 ·
Maintainers usually reply within 1 day
-
review-followup
Difficulty 1/5 Under an hour Newbie friendliness 92/100
griffinwork40/agent-afk#5446 ·
Maintainers usually reply within 1 day
-
enhancement
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
kacper-szewczyk/Ticknest#346 ·
Maintainers usually reply within 1 day
-
echarts geo: a GeoJSON URL that returns 200 with a body that is not JSON is fetched on each refreshOpenbug plugin/echarts/geo
Difficulty 2/5 1-3 hours Newbie friendliness 86/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 79/100
Yeachan-Heo/gajae-code#8230 ·
Maintainers usually reply within 1 day