#16066·chatwoot

perf: AssignableAgentsController#index 中的严重 N+1 查询循环 (每次请求 100 多次查询)

作者: md-riaz创建于 2026年9月29日更新于 2026年9月29日
  1. In app/controllers/api/v1/accounts/assignable_agents_controller.rb:
ruby
def index
  @include_ai_assignees = params[:include_ai_assignees].present?
  agent_ids = @inboxes.map do |inbox|
    authorize inbox, :show?
    inbox.members.pluck(:user_id)
  end
  agent_ids = agent_ids.inject(:&)
  all_agent_ids = (agent_ids.to_a + Current.account.administrators.pluck(:id)).uniq
  @assignable_agents = Current.account.users
                                .where(id: all_agent_ids)
  @agent_bots = @include_ai_assignees ? AgentBot.accessible_to(Current.account) : []
end
  1. In app/views/api/v1/accounts/assignable_agents/index.json.jbuilder:
ruby
json.payload do
  json.array! @assignable_agents do |agent|
    json.partial! 'api/v1/models/agent', formats: [:json], resource: agent
  end
end
  1. In app/views/api/v1/models/_agent.json.jbuilder: The view renders attributes like:
  • resource.availability_status (calls current_account_user)
  • resource.auto_offline (calls current_account_user)
  • resource.role (calls current_account_user)
  • resource.thumbnail (calls resource.avatar_url -> avatar_attachment -> ActiveStorage blob)
  • resource.custom_role_id (calls current_account_user&.custom_role_id)
  1. In app/models/concerns/user_attribute_helpers.rb:
ruby
def current_account_user
  # We want to avoid subsequent queries in case where the association is preloaded.
  # using where here will trigger n+1 queries.
  account_users.find { |ac_usr| ac_usr.account_id == Current.account.id } if Current.account
end

Note that the comment explicitly highlights that account_users must be preloaded. However, in AssignableAgentsController, neither account_users nor avatar_attachment: :blob are preloaded.

Observed Production Impact

In a production account with 47 agents:

  • Executing GET /api/v1/accounts/1/assignable_agents?inbox_ids[]=7&include_ai_assignees=true logs:
Completed 200 OK in 821ms (Views: 393.8ms | ActiveRecord: 237.7ms (108 queries, 3 cached))

Under concurrent dashboard loads, running 108 queries for a single dropdown list serializes behind Puma thread pools and causes response times to spike beyond 10-15 seconds.

内容来源: chatwoot/chatwoot