faraday
How do I setup the retry middleware?
The retry middleware automatically retries failed requests based on configurable conditions. This is particularly useful for handling transient network errors and rate limiting.
Basic Setup
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'faraday'
gem 'faraday-retry'
end
conn = Faraday.new(url: 'https://api.example.com') do |f|
f.request :retry, max: 3
f.adapter Faraday.default_adapter
end
response = conn.get('/endpoint')
Configuration Options
The retry middleware accepts several options to customize behavior:
conn = Faraday.new(url: 'https://api.example.com') do |f|
f.request :retry,
max: 3, # Maximum number of retries
interval: 0.5, # Initial retry interval (seconds)
backoff_factor: 2, # Exponential backoff multiplier
max_interval: 10, # Maximum interval between retries
exceptions: [ # Which exceptions trigger retries
Faraday::TimeoutError,
Faraday::ConnectionFailed
],
methods: [:get, :post], # HTTP methods to retry
retry_statuses: [429, 503] # HTTP status codes to retry
f.adapter Faraday.default_adapter
end
Common Use Cases
API Rate Limiting:
conn = Faraday.new(url: 'https://api.example.com') do |f|
f.request :retry,
max: 5,
retry_statuses: [429],
retry_if: ->(env, exception) {
env[:status] == 429
}
f.adapter Faraday.default_adapter
end
Exponential Backoff:
conn = Faraday.new(url: 'https://api.example.com') do |f|
f.request :retry,
max: 4,
interval: 1,
backoff_factor: 2 # Retries at 1s, 2s, 4s, 8s
f.adapter Faraday.default_adapter
end
Important Notes
- The
faraday-retrygem must be installed separately as it’s not included in core Faraday (version 2.0+) - Retries only apply to idempotent methods by default (
GET,HEAD,DELETE,OPTIONS,TRACE) - Be cautious when retrying non-idempotent methods like
POSTorPUT - Consider setting reasonable timeouts to prevent hanging requests