Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Nov 22, 2025

Category.find was called inside loops while building lanes and nodes, creating N+1 queries when the category data was already available from the steps collection.

Changes

  • Build category lookup hash upfront: Fetch all categories once with Category.where(id: category_ids).index_by(&:id) instead of individual Category.find calls
  • Replace inline lookups: Use categories_by_id[step.category_id] in both lanes and nodes construction
  • Add nil handling: Filter nil category_id values before query and add guards in loops with .compact
# Before: N queries
lanes = steps.map { |step| category = Category.find(step.category_id); ... }
nodes = steps.map { |step| category_name = Category.find(step.category_id).name; ... }

# After: 1 query
category_ids = steps.map(&:category_id).compact.uniq
categories_by_id = Category.where(id: category_ids).index_by(&:id)
lanes = steps.map { |step| category = categories_by_id[step.category_id]; next unless category; ... }
nodes = steps.map { |step| category = categories_by_id[step.category_id]; next unless category; ... }

Reduces queries from O(n) to O(1) where n = number of workflow steps.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI self-assigned this Nov 22, 2025
Copilot AI and others added 3 commits November 22, 2025 16:03
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Copilot AI changed the title [WIP] Address feedback from review on performance improvements Fix N+1 query in workflow visualization controller Nov 22, 2025
Copilot AI requested a review from merefield November 22, 2025 16:06
Copilot finished work on behalf of merefield November 22, 2025 16:07
@merefield merefield changed the base branch from eliminate_n_plus_1 to main November 22, 2025 16:13
@merefield merefield marked this pull request as ready for review November 22, 2025 16:46
@merefield merefield merged commit 737df50 into main Nov 22, 2025
4 checks passed
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.

2 participants