How to Handle Timeout Error in Ruby on Rails?

How to Handle Timeout Error in Ruby on Rails?

14 Sep 2021
0 Comments
How to Handle Timeout Error in Ruby on Rails?

Timeout Error is an exception error thrown when any block of code takes too long to execute, so it terminates its execution by throwing the same error.


This is a common issue we may have faced many times while integrating third-party APIs. This is because whenever we send API requests to any third party, we have to wait for their responses.


In order to handle such Timeout errors, we’ll need to catch the exception error and then handle it properly.
 

Here a sample example with require ‘timeout’:

require 'timeout'
begin
  status = Timeout::timeout(5) {
    # code block that should be terminated if it takes more than 5 seconds...
  }
rescue Timeout::Error
  puts 'Taking long to execute, exiting...'
end


We’ll have to write our code block inside the timeout block, and can adjust with whatever number of seconds we want our code to wait before terminating its execution.
In the above case, if the code block completes its execution before 5 seconds, then it will return the result of the block. And if not, then it will terminate the execution and raise an exception of timeout.

 

Retries:
If we are working with any third-party APIs and facing timeout error and want to repeat any block of code till it gets executed successfully, then we can use a gem called ‘retries’.

 

We can get the gem with gem install retries or simply adding gem "retries" to the Gemfile if using bundler.
 

Here a sample usage, how we can try it three times before failing:

require 'retries'
with_retries(:max_tries => 3) { # do_the_thing }

 

Redis:
Redis is also the best solution to handle timeouts. It increases the performance scalability of the application. Check out here for its installation steps and use cases.

 

Here is a simple example of  timeout handling with Redis:

$redis = Redis.new(:url => '....', :connect_timeout => 5, :timeout => 5)

 

Hope the above solutions help you to solve such timeout issues.
Thanks for reading.




Leave a comment: