ruby 24 lines · 2 tabs

Request timeout handling with Rack::Timeout

Alex Kumar Jan 2026
2 tabs
Rails.application.config.middleware.insert_before(
  Rack::Runtime,
  Rack::Timeout,
  service_timeout: 15  # 15 seconds
)

# Log timeout errors
Rack::Timeout.register_state_change_observer(:logger) do |env, info|
  if info[:state] == :timed_out
    Rails.logger.error("Request timeout: #{env['REQUEST_METHOD']} #{env['PATH_INFO']} exceeded 15s")
  end
end
2 files · ruby Explain with highlit

Long-running requests tie up worker threads and degrade overall application responsiveness. Rack::Timeout enforces request timeouts at the Rack layer, killing requests that exceed configured limits. I set conservative timeouts (15-30 seconds) and handle Rack::Timeout::RequestTimeoutException to return proper 503 Service Unavailable responses. Timeouts protect against slow database queries, hung external API calls, or resource exhaustion. The challenge is distinguishing between legitimately slow operations and bugs—I use monitoring to track timeout rates and investigate patterns. For known slow operations like report generation, I move them to background jobs rather than fighting with timeout configuration.


Related snips

Share this code

Here's the card — post it anywhere.

Request timeout handling with Rack::Timeout — share card
Link copied