Upgrade to Pro — share decks privately, control downloads, hide ads and more …

7日分も開けないレポートが180日分返るまで - 計測と修正のサイクルで回すActiveRec...

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →
Avatar for hirocy hirocy
October 29, 2026

7日分も開けないレポートが180日分返るまで - 計測と修正のサイクルで回すActiveRecordパフォーマンス改善

Avatar for hirocy

hirocy

October 29, 2026

More Decks by hirocy

Other Decks in Programming

Transcript

  1. Q1. どこが悪い? SELECT delivery_report_hourlies.* ... WHERE campaign_id IN (?) --

    388 ms AI で発行元を探す campaigns_scope.includes(:delivery_report_hourlies, ...) 8
  2. A1. 全期間を preload していた SELECT delivery_report_hourlies.* ... WHERE campaign_id IN

    (?) -- report_at の条件が無い campaigns_scope.includes(:delivery_report_hourlies, ...) # includes は関連を丸ごと読む。N+1 対策で付けていた 1広告あたり 2,066行。使うのは当日の 15行だけ 9
  3. 修正1. 当日分だけ includes する # 当日分だけを読む関連 has_many :todays_delivery_report_hourlies, -> {

    where(report_at: Time.current.all_day) } # 期間に今日を含むときだけ includes(:todays_delivery_report_hourlies) 時間別が必要なのは当日分だけ 10
  4. Q2. どこが悪い? SELECT bills.* FROM bills WHERE bills.id = ?

    LIMIT ? -- ×122 AI で発行元を探す fixed_bills = campaign_bills.joins(bill: :bill_month) fixed_bills.map { |cb| cb.bill.bill_month.month } 11
  5. A2. joins は関連をロードしない fixed_bills = campaign_bills.joins(bill: :bill_month) # joins は

    JOIN するだけ。bill はロードされない fixed_bills.map { |cb| cb.bill.bill_month.month } # 辿るたびに1件ずつ SELECT(bills、bill_months 各122回) joins を書いていても、 N+1 になる 12