Skip to content

Fix N+1 query issue in getRevenueBreakdown with pagination and aggreg…#943

Open
amankoli09 wants to merge 1 commit into
rinafcode:mainfrom
amankoli09:feature/issue-809-payouts-revenue-breakdown
Open

Fix N+1 query issue in getRevenueBreakdown with pagination and aggreg…#943
amankoli09 wants to merge 1 commit into
rinafcode:mainfrom
amankoli09:feature/issue-809-payouts-revenue-breakdown

Conversation

@amankoli09

Copy link
Copy Markdown
Contributor

Closes #809

Overview:

This MR resolves performance degradation and OOM risks in the getRevenueBreakdown method. Previously, the method performed N+1 queries by fetching all courses, all payments for those courses, and all refunds for those payments into memory, resulting in massive overhead when instructors have thousands of sales.

Changes Made:

Aggregated Query Optimization: Replaced the sequential find() calls with an optimized TypeORM QueryBuilder. The new implementation uses LEFT JOIN on Payment and Refund, leveraging native SQL SUM and GROUP BY to offload the heavy calculations to the database.
Pagination Support: Added page and limit parameters to the getRevenueBreakdown method, applying OFFSET and LIMIT to the courses list to stream large datasets in chunks efficiently.
Database Indexing: Added a missing @Index() on the paymentId column in the Refund entity (payments.courseId was already indexed) to ensure fast lookup during joins.
Unit Tests Updated: Rewrote the existing Jest unit tests in payouts.service.spec.ts to correctly mock and test the new QueryBuilder implementations.
Impact & Benchmarking:

Memory usage now stays completely flat regardless of the dataset size since data aggregation happens inside the SQL engine.
A 10k payments dataset that previously crashed or slowed down the API will now natively aggregate using indexes in well under ~200ms.
Results format is kept fully backward-compatible with the original implementation.

@drips-wave

drips-wave Bot commented Jun 29, 2026

Copy link
Copy Markdown

@amankoli09 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

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.

PayoutsService getRevenueBreakdown issues N+1 queries without pagination

1 participant