perf(api): eliminate unbounded in-memory queries and redundant DB fan-out across Analytics, Sales Chat, CRM, and Bio-Links
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 35/100
- Tipo de issue
- Refactorización
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- postgresql, redis, typescript
- Área
- analytics, api, backend, databases, performance
Línea de trabajo
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.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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
- Lenguaje dominante
- TypeScript
- Estrellas
- 2
- Forks
- 1
- Merge medio
- 6 min
- PR fusionados (30 d)
- 27
Preparar el entorno
- Incluye un Dockerfile o un archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de sumamakhan761/tryinstance
-
backend good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
sumamakhan761/tryinstance#65 ·
Los mantenedores suelen responder en 1 día
-
backend good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
sumamakhan761/tryinstance#64 ·
Los mantenedores suelen responder en 1 día
-
backend good first issue
Dificultad 1/5 1-3 horas Aptitud para principiantes 88/100
sumamakhan761/tryinstance#63 ·
Los mantenedores suelen responder en 1 día
-
backend good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
sumamakhan761/tryinstance#62 ·
Los mantenedores suelen responder en 1 día
-
backend good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
sumamakhan761/tryinstance#60 ·
Los mantenedores suelen responder en 1 día
Todos los issues de sumamakhan761/tryinstance
Issues similares
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 67/100
makecindy/cindy#15342 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
enhancement
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
kwitsch/claude-code-plugin-tooling#219 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
Los mantenedores suelen responder en 1 día
-
no-repo-link tool-submission
Dificultad 1/5 Menos de una hora Aptitud para principiantes 74/100
BraveOPotato/NoSignups#2618 ·
-
enhancement good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100