3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ActiveJob でジョブのメモリ使用量がしきい値を超えた場合に通知する

Last updated at Posted at 2022-02-25

やりたいこと

  • ActiveJob でジョブのメモリ使用量がしきい値以上だった場合に通知したい。
    • 僕の具体的なユースケース: Sidekiq で大量にメモリを使用して、かつ解放されない場合が結構ある。そこで、具体的にどのジョブが関係しているのかを調べたい。

方法

  • around_perform メソッドを使う。
    • 今回は Rollbar というエラーモニタリングサービスで警告を通知する。
    • Rollbar.warning の部分は、環境に応じて任意の通知方法に置き換えること。
app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
  around_perform do |job, block|
    MonitorMemoryUsage.call(job, &block)
  end
end
app/jobs/monitor_memory_usage.rb
module MonitorMemoryUsage
  extend ActionView::Helpers::NumberHelper

  class HighMemoryUsage < StandardError; end

  THRESHOLD = 100.megabytes

  def self.call(job)
    before_memsize = ObjectSpace.memsize_of_all
    results = yield
    after_memsize = ObjectSpace.memsize_of_all

    usage = after_memsize - before_memsize

    if usage > THRESHOLD
      message = "#{job.class.name}#{number_to_human_size(usage, locale: :en)} のメモリを消費しました。"
      Rollbar.warning(HighMemoryUsage.new(message), arguments: job.arguments)
    end

    results
  end
end

こんな感じ :eyes:

Rollbar warning
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?