Optimize Budget model performance by preventing N+1 queries #2504

Closed
SyedaAnshrahGillani wants to merge 1 commits from optimize-budget-donut-chart-performance into main
SyedaAnshrahGillani commented 2025-07-23 19:12:14 +08:00 (Migrated from github.com)

Problem

The Budget model was suffering from N+1 query issues, leading to excessive database calls and performance degradation when rendering budget donut charts.

Before Optimization

  • to_donut_segments_json method was causing N+1 queries due to:
    • Loading each budget_category and its category separately
    • Repeated lookup calls for category expenses

Solution

  • Pre-computed category totals using an index_by for O(1) lookup.
  • Applied includes(:category) explicitly to ensure categories are preloaded, reducing query count.
  • Same optimization was applied to allocated_spending method.

After Optimization

  • Fixed to avoid repeated and expensive lookups per budget_category
  • Now only 2 queries total: preload + expense totals

Impact

This optimization is expected to significantly improve performance for users with many budget categories by reducing:

  • Response time for rendering budget sections
  • Database load on budget-related pages

Testing

Added comprehensive test coverage to validate no regression in behavior and verified query count reduction.

## Problem The Budget model was suffering from N+1 query issues, leading to excessive database calls and performance degradation when rendering budget donut charts. ### Before Optimization - **to_donut_segments_json** method was causing N+1 queries due to: - Loading each `budget_category` and its `category` separately - Repeated lookup calls for category expenses ## Solution - Pre-computed category totals using an `index_by` for O(1) lookup. - Applied `includes(:category)` explicitly to ensure categories are preloaded, reducing query count. - Same optimization was applied to `allocated_spending` method. ### After Optimization - Fixed to avoid repeated and expensive lookups per `budget_category` - Now only 2 queries total: preload + expense totals ## Impact This optimization is expected to significantly improve performance for users with many budget categories by reducing: - Response time for rendering budget sections - Database load on budget-related pages ## Testing Added comprehensive test coverage to validate no regression in behavior and verified query count reduction.

Pull request closed

Sign in to join this conversation.