From ead1ab31b4e1af10df30dbcc97c9be59dbbd9f26 Mon Sep 17 00:00:00 2001 From: Pau Perez Date: Thu, 25 Mar 2021 09:40:08 +0100 Subject: [PATCH] Fix multiple N+1 on /admin/customers.json This (should) considerably improve traces like https://app.datadoghq.com/apm/trace/917632173599137280?spanID=3163385094622710144&env=production&sort=time&colorBy=service&spanViewType=metadata&graphType=flamegraph&shouldShowLegend=true by fixing the following 3 N+1s ``` user: root GET /admin/customers.json?enterprise_id=4 USE eager loading detected Customer => [:enterprise] Add to your query: .includes([:enterprise]) Call stack /usr/src/app/app/serializers/api/admin/customer_with_calculated_balance_serializer.rb:24:in `balance_value' /usr/src/app/app/serializers/api/admin/customer_with_calculated_balance_serializer.rb:9:in `balance' /usr/src/app/app/controllers/admin/customers_controller.rb:20:in `block (2 levels) in index' /usr/src/app/app/controllers/admin/customers_controller.rb:17:in `index' user: root GET /admin/customers.json?enterprise_id=4 USE eager loading detected Spree::Address => [:state] Add to your query: .includes([:state]) Call stack /usr/src/app/app/serializers/api/address_serializer.rb:14:in `state_name' /usr/src/app/app/controllers/admin/customers_controller.rb:20:in `block (2 levels) in index' /usr/src/app/app/controllers/admin/customers_controller.rb:17:in `index' user: root GET /admin/customers.json?enterprise_id=4 USE eager loading detected Spree::Address => [:country] Add to your query: .includes([:country]) Call stack /usr/src/app/app/serializers/api/address_serializer.rb:10:in `country_name' /usr/src/app/app/controllers/admin/customers_controller.rb:20:in `block (2 levels) in index' /usr/src/app/app/controllers/admin/customers_controller.rb:17:in `index' ``` This popped up after improving the balances calculation. Now, that it's fast, it's clear that are more performance problems on that endpoint. We'll see if there are any left after this. --- app/controllers/admin/customers_controller.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/controllers/admin/customers_controller.rb b/app/controllers/admin/customers_controller.rb index 4a2f4242e9..9057735bcb 100644 --- a/app/controllers/admin/customers_controller.rb +++ b/app/controllers/admin/customers_controller.rb @@ -74,7 +74,12 @@ module Admin def collection if json_request? && params[:enterprise_id].present? customers_relation. - includes(:bill_address, :ship_address, user: :credit_cards) + includes( + :enterprise, + { bill_address: [:state, :country] }, + { ship_address: [:state, :country] }, + user: :credit_cards + ) else Customer.where('1=0') end