Ruby Faraday Proxy Setup
Faraday is Ruby's most popular HTTP client middleware framework. Its pluggable adapter architecture and middleware stack make it ideal for proxy workflows — you can add retry logic, request logging, response parsing, and error handling as composable middleware layers. The proxy configuration applies globally to the connection, routing all requests through Hex Proxies automatically.
Complete Configuration with Middleware
require 'faraday'proxy_url = "http://#{ENV['PROXY_USER']}:#{ENV['PROXY_PASS']}@gate.hexproxies.com:8080"
conn = Faraday.new(url: 'https://example.com') do |f| f.proxy proxy_url
# Retry middleware for proxy failures f.request :retry, max: 3, interval: 2, interval_randomness: 0.5, backoff_factor: 2, retry_statuses: [403, 429, 503]
# Request headers f.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)' f.headers['Accept-Language'] = 'en-US,en;q=0.9'
# Timeouts f.options.timeout = 30 f.options.open_timeout = 15
# Response parsing f.response :json, content_type: /\bjson$/ f.response :logger if ENV['DEBUG']
f.adapter Faraday.default_adapter end
response = conn.get('/api/data') puts "[#{response.status}] #{response.body}" ```
Geo-Targeted Connections
Create connections with country-specific proxy credentials:
def proxied_connection(country: nil)
user = ENV['PROXY_USER']Faraday.new do |f| f.proxy "http://#{user}:#{ENV['PROXY_PASS']}@gate.hexproxies.com:8080" f.request :retry, max: 3, retry_statuses: [403, 429, 503] f.options.timeout = 30 f.options.open_timeout = 15 end end
us_conn = proxied_connection(country: 'us') uk_conn = proxied_connection(country: 'gb')
us_response = us_conn.get('https://example.com/pricing') uk_response = uk_conn.get('https://example.com/pricing') ```
Custom Middleware for Proxy Metrics
class ProxyMetrics < Faraday::Middleware
def call(env)
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
response = @app.call(env)
elapsed = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000).round
puts "[#{response.status}] #{env.url} - #{elapsed}ms via proxy"
response
endconn = Faraday.new do |f| f.proxy proxy_url f.use ProxyMetrics f.adapter Faraday.default_adapter end ```
Common Pitfalls
Faraday middleware order matters. The retry middleware must be added before the adapter — middleware runs in the order it is declared. If you add retry after the adapter, it will not catch connection failures. Another issue: Faraday connections are not thread-safe for concurrent modification. Create separate connections per thread or use connection pooling.
Choosing the Right Adapter
Faraday supports multiple HTTP adapters. The default Net::HTTP adapter works for basic proxy needs. For higher throughput, switch to the Typhoeus adapter which uses libcurl for connection pooling and parallel requests through the proxy.