Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Net::HTTP#max_retries= when you need Ruby’s standard-library retry behavior for documented idempotent transport failures. Use Faraday’s retry middleware when you also need selected HTTP-status retries, backoff, jitter, or Retry-After handling. In either case, bound the number of retries and do not automatically repeat a non-idempotent operation such as an order or charge unless you can prove that repeating it is safe.

What a retry can—and cannot—prove

A timeout, connection reset, or broken pipe tells you that the client did not receive a usable response. It does not prove that the server failed to apply the request. The server might have created a record or charged a card immediately before the connection disappeared. A retry therefore needs both a failure policy and an idempotency policy.

HTTP defines idempotence by intended effect: repeating an idempotent request has the same intended effect as making it once. Safe methods, PUT, and DELETE are idempotent under RFC 9110. A client SHOULD NOT automatically retry a non-idempotent method unless it knows the operation is actually idempotent or can detect that the original request was never applied. That warning matters especially for POST requests that create, reserve, or charge something.

Make a POST deliberately repeatable

  • Use the API’s idempotency-key or request-token mechanism, and send the same key on every attempt.
  • Have the server deduplicate the key and return the original result.
  • Alternatively, query the operation by a client-generated identifier before deciding whether to retry.
  • If neither is available, surface an unknown outcome to the caller instead of blindly repeating the side effect.

Option 1: Ruby Net::HTTP built-in retries

Net::HTTP exposes max_retries=. Ruby’s current documentation says its initial value is 1 and that it retries idempotent requests for listed transport and timeout failures, including Net::ReadTimeout, IOError, EOFError, connection reset or abort errors, broken pipes, OpenSSL::SSL::SSLError, and Timeout::Error. Ruby 3.2 documents the same initial value. See the current API and the Ruby 3.2 API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

This setting is not a blanket retry for every HTTP response. A 503, 429, or application-level error is still a response and requires your own policy.

Runnable GET example

require "net/http"
require "uri"

uri = URI("https://api.example.com/profile")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https")
http.open_timeout = 5
http.read_timeout = 20
http.max_retries = 2 # maximum retries; up to three total attempts

request = Net::HTTP::Get.new(uri)
request["Accept"] = "application/json"

begin
  response = http.request(request)
  unless response.is_a?(Net::HTTPSuccess)
    raise "HTTP #{response.code}: #{response.body}"
  end
  puts response.body
rescue Net::OpenTimeout, Net::ReadTimeout, IOError, EOFError => e
  warn "request failed after retries: #{e.class}: #{e.message}"
  raise
end

The value must be non-negative. A value of 2 means two repeats after the initial request, not two attempts total. Keep the value small and make the exhausted outcome explicit: return a failure object, raise an application error, or enqueue the work for later.

When Net::HTTP is the right fit

  • You already use the standard library and want no extra dependency.
  • You need retries for Ruby’s documented idempotent transport exceptions.
  • You do not need automatic status-code selection, jitter, or a custom backoff schedule.

Option 2: Faraday retry middleware

Faraday’s middleware provides a policy surface for exception retries and selected response statuses. The current faraday-retry source documents a default maximum of two retries, default retryable exception classes, and a default method list of GET, HEAD, OPTIONS, PUT, and DELETE. Verify option names against the version installed in your application because the main branch is a rolling source.

Install and configure it

gem install faraday faraday-retry
require "faraday"
require "faraday/retry"

conn = Faraday.new("https://api.example.com") do |f|
  f.request :retry,
    max: 2,
    interval: 0.1,
    backoff_factor: 2,
    max_interval: 2,
    interval_randomness: 0.2,
    retry_statuses: [429, 503]
  f.response :raise_error
  f.adapter Faraday.default_adapter
end

response = conn.get("/profile")
puts response.body

Those numbers are an example policy, not a universal recommendation. max: 2 allows up to three total attempts. The middleware can select methods, exception classes, statuses, initial interval, backoff factor, maximum interval, and randomization. It also parses Retry-After and applies the server’s requested wait within your configured limits. RFC 9110 says that Retry-After may be an HTTP date or a delay in seconds and indicates how long to wait before a follow-up request. See the Faraday middleware source and RFC 9110 sections 9.2.2 and 10.2.3.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Retry only statuses that are transient for your API

Do not assume that every 4xx or 5xx response should be retried. A 401 usually needs new credentials; a 400 needs corrected input. Select statuses such as 429 or 503 only when the remote API documents them as temporary. A server may use 500 for a permanent application defect, so include it only with a reason.

Choosing between the two clients

Concern Net::HTTP Faraday retry middleware
Dependency Ruby standard library Faraday plus faraday-retry
Built-in scope Documented idempotent transport failures Exceptions plus configured response statuses
Method control Ruby decides which requests are eligible Configurable method list
Backoff and jitter No policy knobs exposed by max_retries= Interval, backoff, maximum interval, and randomness
Retry-After Not a status-retry policy Parsed and combined with configured limits
Exhausted result Your code handles the final exception or response Your middleware stack raises or returns according to its configured response handling

Designing a safe retry policy

Bound attempts

Set a finite maximum. A retry loop without a cap can turn a temporary outage into permanently stuck workers and duplicate side effects. Document whether your number means retries or total attempts; both libraries describe a maximum number of retries.

Use capped exponential delay

A common shape is an initial delay that grows by a factor after each failure, capped at a maximum. Jitter adds a small random component so many clients do not reconnect simultaneously. Faraday’s middleware calculates this style of interval and also considers parsed Retry-After or rate-limit reset information. The exact values belong to the remote service’s limits and your latency budget.

Separate transport failures from HTTP responses

Transport exceptions mean the response is unknown. HTTP responses mean the server sent a status and body, so inspect them. Retry only statuses your API identifies as temporary, and preserve response headers needed for diagnostics.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Keep the operation observable

  • Log attempt number, method, host, status or exception class, and elapsed time.
  • Never log authorization headers, cookies, API keys, or sensitive request bodies.
  • Emit a metric for exhausted retries and for unknown outcomes.
  • Attach a correlation or idempotency key so support can trace one logical operation.

Handling non-idempotent requests

For a payment, signup, email send, or order creation, first check the API contract. If it supports an idempotency key, generate one before the first attempt and reuse it. Do not generate a new key inside the retry block. If the request timed out after transmission and the API has no deduplication or lookup endpoint, report that the outcome is unknown and require reconciliation rather than automatically sending a second request.

Common failures and fixes

“It retried, but a 503 was returned only once”

Net::HTTP#max_retries= covers documented transport failures, not arbitrary response statuses. Use Faraday with retry_statuses: [503], or write an explicit, bounded response loop.

“The retry happened too quickly”

Configure an interval and backoff in Faraday, honor Retry-After, and cap the resulting delay. Net::HTTP’s simple setting does not provide a configurable backoff policy.

“A POST created two records”

The operation was repeated without proof of idempotence. Add the provider’s idempotency key, use a deduplication token, or stop automatic retries for that endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

“The code retries forever”

Check nested application loops, job retries, and client retries together. Set a cap at each layer and define a single final failure path.

“Faraday raises immediately”

Confirm that faraday-retry is installed and that the retry middleware is placed in the connection stack before the adapter. Check that the method, exception class, and status appear in your configured policy.

“The final error contains secrets”

Sanitize exception and response logging. Record status, endpoint category, and correlation ID rather than complete URLs containing tokens or raw bodies.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Testing a retry implementation

  • Simulate a read timeout before a successful response and verify the bounded attempt count.
  • Return a configured transient status followed by success and confirm delay and Retry-After handling.
  • Return a permanent 400 or 401 and verify there is no retry.
  • Drop the connection after accepting a POST and verify that your idempotency or reconciliation path prevents duplication.
  • Exhaust attempts and assert that the caller receives a clear, sanitized failure.

Or skip the browser setup

If your Ruby service also needs website screenshots for diagnostics or reports, ScreenshotNeo provides a single HTTP call instead of maintaining browser automation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for options. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Start with the free ScreenshotNeo account.

Frequently Asked Questions

Does Net::HTTP retry 429 responses automatically?

No. Its documented setting concerns eligible idempotent transport failures; a 429 response needs an explicit response-status policy such as Faraday’s configured retry statuses.

What is the difference between retries and attempts?

An initial request is one attempt. A setting of two retries permits that initial attempt plus two repeats, for up to three attempts.

Should every timeout be retried?

Only when repeating the operation is safe or protected by an idempotency mechanism, and only within a bounded policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.