Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, ActiveJobs and AWS SQS: what happen to my jobs when a worker instance is killed?

We are using Rails 5.0.2 and ActiveJobs in AWS Beanstalk with SQS as a backend with the gem active_elastic_job.

We have a job defined like this:

class MyJob < ActiveJob::Base
  rescue_from(StandardError) do |exception|
    self.class.set(:wait => 1.minutes).perform_later
  end

  def perform
    MyLongTask.run
  end
end

We experienced that when one instance in the worker environment is killed (due auto-scaling or something) the rescue_from is not executed and the Job is not sent back to the Queue.

How can we capture the moment the instance is been called to be killed so we can gracefully react and wrapping up before my process is really killed? (if possible)

Update

I am trying this

class MyJob < ActiveJob::Base
  def perform
    begin
      sleep(100)
    rescue SignalException => e
      # send signal to some log place
      raise e
    end
  end
end

But the log is never sent not when I terminate the instance neither when I kill the puma process with $ restart puma

like image 299
fguillen Avatar asked Dec 05 '18 10:12

fguillen


People also ask

Does SQS automatically delete messages?

Amazon SQS doesn't automatically delete a message after retrieving it for you, in case you don't successfully receive the message (for example, if the consumers fail or you lose connectivity).

How long can you keep your Amazon SQS messages in Amazon SQS queues?

You can configure the Amazon SQS message retention period to a value from 1 minute to 14 days. The default is 4 days. Once the message retention quota is reached, your messages are automatically deleted.

What happens when lambda fails to process SQS message?

Short description. If your Lambda function is throttled, returns an error, or doesn't respond when reading an Amazon SQS message batch, then the messages return to your queue. After the visibility timeout occurs, your Lambda function receives the message batch again.

What happens after SQS visibility timeout?

During this time, the consumer processes and deletes the message. However, if the consumer fails before deleting the message and your system doesn't call the DeleteMessage action for that message before the visibility timeout expires, the message becomes visible to other consumers and the message is received again.


1 Answers

By catching the SIGTERM signal, you can perform any cleanup you'd like before the process is terminated (your environment might send a SIGKILL later which cannot be caught).

Signal.trap(:SIGTERM) {
  # perform cleanup here
  exit
}
like image 163
Umang Raghuvanshi Avatar answered Sep 23 '22 20:09

Umang Raghuvanshi