ruby 31 lines · 6 steps

Bounding a slow HTTP call with Timeout in Ruby

A remote inventory client caps its upstream request and falls back to a stale cache when the deadline is blown.

Explained by highlit
1require "timeout"
2require "net/http"
3 
4class RemoteInventoryClient
5 class SlowUpstreamError < StandardError; end
6 
7 DEFAULT_TIMEOUT = 3.0
8 
9 def initialize(base_uri, timeout: DEFAULT_TIMEOUT)
10 @base_uri = URI(base_uri)
11 @timeout = timeout
12 end
13 
14 def stock_level(sku)
15 Timeout.timeout(@timeout, SlowUpstreamError, "inventory lookup exceeded #{@timeout}s") do
16 response = fetch("/skus/#{sku}/stock")
17 JSON.parse(response.body).fetch("available")
18 end
19 rescue SlowUpstreamError => e
20 Rails.logger.warn("[inventory] #{e.message} sku=#{sku}")
21 StaleStockCache.fetch(sku)
22 end
23 
24 private
25 
26 def fetch(path)
27 Net::HTTP.start(@base_uri.host, @base_uri.port, use_ssl: @base_uri.scheme == "https") do |http|
28 http.request(Net::HTTP::Get.new(path))
29 end
30 end
31end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping risky I/O in Timeout.timeout with a custom exception makes deadline failures easy to catch and handle distinctly.
  2. 2Pairing a hard timeout with a stale-cache fallback keeps a service responsive even when an upstream degrades.
  3. 3Configurable timeouts with a sensible default let callers tune latency budgets without touching call sites.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Bounding a slow HTTP call with Timeout in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code