Fix expensive query on admin/users endpoint
In the admin/users
endpoint. We check whether the delete user
Button is rendered by checking whether there are groups where this user is a solo owner. This method has two issues
- It checks for all the users separately, causing N+1 issues
- It loads all the associated groups to the memory and checks the existence from ruby, this causes memory bloat
Low-hanging fruit to fix the issue is to offload the existence checks to the database so that entire groups need not be loaded to the ruby memory. Ref: https://www.speedshop.co/2019/01/10/three-activerecord-mistakes.html
For a user with 557 solo-owned groups
?> Benchmark.bmbm do |x|
?> x.report("exists?") { User.find(1614863).solo_owned_groups.exists? }
?> x.report("present?") { User.find(1614863).solo_owned_groups.present?}
[ gstg ] production> end
?>
Rehearsal --------------------------------------------
exists? 0.019400 0.003913 0.023313 ( 0.454207)
present? 0.029882 0.000000 0.029882 ( 0.214018)
----------------------------------- total: 0.053195sec
user system total real
exists? 0.012590 0.000277 0.012867 ( 0.075993)
present? 0.028800 0.002822 0.031622 ( 0.218427)
Edited by Aboobacker MK