Skip to content

Handle N+1 queries in SyncPolicyEventService

The following discussion from !172447 (merged) should be addressed:

  • @jessieay started a discussion: (+4 comments)

    Question: is this an N+1? I believe it is.

    I asked Claude for a recommendation for something more computationally efficient and this is what was recommended:

    def affected_rules(protected_branch_id)
      # Early return if no branch ID specified - no computation needed
      rules = security_policy.approval_policy_rules.undeleted
      return rules if protected_branch_id.nil?
    
      # Pre-fetch all branch IDs to avoid repeated service calls
      rule_to_branches = rules.each_with_object({}) do |rule, mapping|
        mapping[rule] = sync_project_approval_policy_rules_service.protected_branch_ids(rule)
      end
    
      # Filter rules using the cached branch IDs
      rules.select do |rule|
        rule_to_branches[rule].include?(protected_branch_id)
      end
    end
  • !172447 (comment 2284046031)

    Suggestion (non-blocking): now that this method is public, I wonder if it would be best moved somewhere outside of this service?

Edited by Sashi Kumar Kumaresan