Skip to content

fix(#1013): Eliminate N+1 count queries in KpiService - #1107

Open
laxjovial wants to merge 1 commit into
rinafcode:mainfrom
laxjovial:fix/issue-1013
Open

fix(#1013): Eliminate N+1 count queries in KpiService#1107
laxjovial wants to merge 1 commit into
rinafcode:mainfrom
laxjovial:fix/issue-1013

Conversation

@laxjovial

Copy link
Copy Markdown
Contributor

📝 Description
This pull request resolves Issue #1013 by eliminating severe N+1 query bottlenecks within the KpiService, which previously executed sequential database queries based on the number of courses and cohorts.

🛠️ Changes Made
Enrollment Conversion Optimization: Replaced the per-course enrollmentRepository.count() loop with a single grouped query (SELECT courseId, COUNT(*) FROM enrollment GROUP BY courseId). The results are loaded into memory and mapped to the course list, reducing thousands of sequential queries to exactly two queries.
User Retention Optimization: Rewrote calculateUserRetention to use a direct SQL COUNT aggregation rather than eagerly loading all user rows per cohort month via userRepository.find().
Performance Observability: Enclosed both KPI job executions with a duration tracker, exporting a kpi_job_duration_ms metric using MetricsService. This ensures any future regressions in query performance or job duration are highly visible.
Tests Added: Added kpi.service.spec.ts to assert that the calculateEnrollmentConversionRate issues a constant number of queries (strictly bounded to exactly one aggregate query builder call) regardless of the number of courses dynamically returned.
🧪 Acceptance Criteria Addressed
The conversion rate job issues a constant number of queries regardless of course count.
Retention calculation uses aggregation and does not load individual user rows.
Job duration is exported as a metric for monitoring.
Tests added to assert constant query count.
🔗 Related Issues
Resolves #1013

@drips-wave

drips-wave Bot commented Jul 28, 2026

Copy link
Copy Markdown

@laxjovial Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@RUKAYAT-CODER

Copy link
Copy Markdown
Contributor

Well done on the job done so far!
Kindly resolve conflict and fix workflow to pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Eliminate the per-course N+1 count query in KpiService.calculateEnrollmentConversionRate

2 participants