Performance: eliminate N+1 queries and add missing indexes by Copilot · Pull Request #344 · mirego/killswitch

Closes:

Database Query Optimizations

N+1 query elimination:

  • BehaviorDispatcher.fetch_language: Changed pluck(:language) to map(&:language) on preloaded association
  • ProjectsController#fetch_project: Added .includes(:behaviors)
  • ApplicationsController#fetch_application: Added .includes(:projects)

Bulk update optimization:

  • BehaviorSorter.reorder_each_behavior: Replaced N individual update calls with single SQL CASE statement using Arel
# Before: N queries
behaviors.each { |b| b.update behavior_order: order }

# After: 1 query with CASE statement
case_node = Arel::Nodes::Case.new
map.each { |id, order| case_node = case_node.when(id_col.eq(id)).then(order) }
behaviors.update_all(behavior_order: case_node.else(order_col))

Database Indexes

Added indexes on foreign keys and lookup columns:

  • projects.key (unique) — API lookup
  • behaviors.project_id
  • applications.organization_id
  • projects.application_id

Tradeoffs

  • Added 4 migrations that must run on deploy
  • Arel CASE statement is less readable than loop but significantly faster at scale
Original prompt

Identify and suggest improvements to slow or inefficient code


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.