Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cop idea: Do not use Kernel.sleep in jobs #11

Open
ydakuka opened this issue Sep 16, 2023 · 0 comments
Open

Cop idea: Do not use Kernel.sleep in jobs #11

ydakuka opened this issue Sep 16, 2023 · 0 comments

Comments

@ydakuka
Copy link

ydakuka commented Sep 16, 2023

Reference: https://github.com/toptal/active-job-style-guide#sleep

Do not use Kernel.sleep in jobs. sleep blocks the worker thread, and it’s not able to process other jobs. Re-schedule the job for a later time, or use limiters with a custom exception.

# bad
class SomeJob < ApplicationJob
  def perform(user)
    attempts_number = 3
    ThirdParty::Api::User.renew(user.external_id)
  rescue ThirdParty::Api::Errors::TooManyRequestsError => error
    sleep(error.retry_after)
    attempts_number -= 1
    retry unless attempts_number.zero?
    raise
  end
end

# good - retry job in a while, a limited number of times
class SomeJob < ApplicationJob
  sidekiq_options retry: 3
  sidekiq_retry_in do |count, exception|
    case exception
    when ThirdParty::Api::Errors::TooManyRequestsError
      count + 1 # i.e. 1s, 2s, 3s
    end
  end

  def perform(user)
    ThirdParty::Api::User.renew(user.external_id)
  end
end

# good - fine-grained control of API usage in jobs
class SomeJob < ApplicationJob
  def perform(user)
    LIMITER.within_limit do
      ThirdParty::Api::User.renew(user.external_id)
    end
  end
end

# config/initializers/sidekiq.rb
Sidekiq::Limiter.configure do |config|
  config.errors << ThirdParty::Api::Errors::TooManyRequestsError
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant