How to Retry Failed Requests in Ruby
A Ruby retry loop resends failed HTTP requests automatically.
It is useful for temporary problems such as rate limits (429), server overload (500-504), and connection failures. This guide shows how to implement retry in Ruby using Net::HTTP with exponential backoff.
What a Retry Loop Solves
Transient failures are common on the network. A server may be briefly overloaded, a rate limit may clear after a pause, or a connection may drop before a response arrives. A retry loop gives the request another chance while keeping the total number of attempts bounded.
The loop should not retry everything. Permanent errors such as a 404 or 401 will not improve by resending the same request. The script below retries only the status codes that usually indicate a temporary condition, and it also catches raised exceptions so a dropped connection does not end the run.
Create a Ruby Retry Loop
The complete script uses Net::HTTP to send a GET request, reads the response status, and decides whether to retry. It sets a maximum of five attempts, a list of retryable status codes, and a delay that doubles after each failed attempt.
The request includes an Authorization header with a bearer token placeholder. Replace that placeholder with your own credential. The script also builds a request URL from a base URL and query parameters, so you can point it at the endpoint you need to test.
Set APP_BASE_URL, SITE_BASE_URL and API_KEY. The documented GET /api/v1/ uses the url query field and Bearer header. This policy allows five attempts, retries the five listed statuses or raised exceptions, uses 10/30-second connection/read timeouts and waits 1, 2, 4 and 8 seconds between attempts.
require "net/http"
require "uri"
require "openssl"
MAX_ATTEMPTS = 5
RETRYABLE_STATUS_CODES = [429, 500, 502, 503, 504].freeze
def with_retries
last_response = nil
1.upto(MAX_ATTEMPTS) do |attempt|
begin
last_response = yield
status = last_response.code.to_i
return last_response if (200..299).cover?(status) || !RETRYABLE_STATUS_CODES.include?(status)
rescue StandardError => error
warn "Attempt #{attempt}: #{error.message}"
end
break if attempt == MAX_ATTEMPTS
delay = 2**(attempt - 1)
sleep(delay)
end
last_response
end
request_url = URI(ENV.fetch("APP_BASE_URL").sub(%r{/+\z}, "") + "/api/v1/")
raise ArgumentError, "Use an HTTPS API origin" unless request_url.scheme == "https"
request_url.query = URI.encode_www_form("url" => ENV.fetch("SITE_BASE_URL").sub(%r{/+\z}, ""))
result = with_retries do
request = Net::HTTP::Get.new(request_url)
request["Authorization"] = "Bearer #{ENV.fetch('API_KEY')}"
Net::HTTP.start(request_url.hostname, request_url.port,
use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_PEER,
open_timeout: 10, read_timeout: 30) { |connection| connection.request(request) }
end
puts "HTTP #{result.code}: #{result.body}" if resultHow the Ruby Retry Logic Works
The script has three moving parts that control its behavior.
First, the attempt cap. The script allows a maximum of five attempts:
MAX_ATTEMPTS = 5
Second, the retryable status list. The script executes retries for these temporary errors:
RETRYABLE_STATUS_CODES = [429, 500, 502, 503, 504].freeze
Third, the delay. The delay increases after each failed attempt:
delay = 2**(attempt - 1)
With at most five attempts, there are at most four waits: 1, 2, 4 and 8 seconds. The loop stops after the fifth attempt before calculating or sleeping for a fifth delay, so it does not wait 16 seconds after exhaustion.
Test the Failed Attempts
To see the retry behavior, change the request_url to a URL that returns a 503 error:
request_url = "https://httpbin.org/status/503"
Run the script and it will execute the retries across the 5 attempts. The output shows each attempt and its HTTP status, then reports that the maximum retry limit was reached. That confirms the loop is resending the request and stopping at the cap rather than looping forever.
Use with_retries and the standard-library imports from the preceding example. This public test returns HTTP 503. It deliberately sends no API-key or Authorization header to the third-party test endpoint.
test_response = with_retries do
Net::HTTP.get_response(URI("https://httpbin.org/status/503"))
end
puts test_response.code if test_responseRetry Decision Checklist
Before adding a retry, decide what counts as a temporary failure and what should stop the loop.
- Retry on 429, 500, 502, 503, and 504, because these often clear after a short wait.
- Retry on raised exceptions such as connection timeouts, so a dropped connection does not end the run.
- Do not retry on 4xx codes outside 429, because the same request will usually fail again.
- Stop after a fixed number of attempts to avoid endless resending.
- Increase the wait between attempts so a struggling server is not hammered.
- Log each attempt and its status so you can see where the loop stopped.
Loop Variables at a Glance
The script's behavior is controlled by a small set of values. Use this map to adjust the loop for your own endpoint.
- MAX_ATTEMPTS: the total number of tries, set to 5 in the example.
- RETRYABLE_STATUS_CODES: the status codes that trigger another attempt, set to 429, 500, 502, 503, and 504.
- attempt: the current try number, starting at 1.
- delay: the wait before the next try, calculated as 2 raised to the power of attempt minus 1.
- request_url: the endpoint being called, built from a base URL and query parameters.
- Authorization: the bearer token header sent with the request.
Status Failures vs Raised Exceptions
The loop handles two different kinds of failure. A status failure is a response that arrives with a code outside the 2xx range. The script reads that code and decides whether it is in the retryable list. A raised exception is a failure that prevents a response from arriving at all, such as a timeout or connection error. The rescue block catches those exceptions and lets the loop continue.
Keeping the two paths separate matters. A non-retryable status should stop the loop immediately, while an exception should usually be retried until the attempt cap is reached. The example script prints a message for each case so the two outcomes are easy to tell apart in the output.
Frequently asked questions
Which HTTP status codes should a Ruby retry loop resend?
The example retries 429, 500, 502, 503, and 504. These codes usually indicate a temporary condition such as a rate limit or server overload. Other 4xx codes generally will not improve by resending the same request, so the loop stops on them.
How many attempts does the example allow?
The script sets MAX_ATTEMPTS to 5. After the fifth attempt, it prints that the maximum retry limit was reached and stops.
How is the wait between attempts calculated?
The delay is 2 raised to the power of attempt minus 1, applied only when another attempt remains. Five attempts therefore allow four waits of 1, 2, 4 and 8 seconds; the final failure ends the loop without a 16-second wait.
How can I test the retry behavior?
Use the credential-free test block with https://httpbin.org/status/503. It exercises five attempts and four waits through with_retries without sending the API Authorization header to the third-party test endpoint. Inspect the final response code after exhaustion.