How to Handle Timeout Error in Ruby on Rails?

Cryptex Technologies
2 min readSep 14, 2021


By: Najma Malik Category: Ruby on Rails Technologies: 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’
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…’

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.

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 is a sample usage, how we can try it three times before failing:

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

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 = => ‘….’, :connect_timeout => 5,

:timeout => 5)

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

Originally published at



Cryptex Technologies

Cryptex specializes in developing open source web applications and software solutions across all domains and verticals using Ruby on Rails (ROR) technology