Skip to content

Instantly share code, notes, and snippets.

@dkam
Last active August 10, 2023 02:06
Show Gist options
  • Save dkam/b2fa3d644f28323e425be19bd1cdd7a1 to your computer and use it in GitHub Desktop.
Save dkam/b2fa3d644f28323e425be19bd1cdd7a1 to your computer and use it in GitHub Desktop.
A Rails before_action to request bots retry-after X seconds when normalised load is high
def bot_shedding(wait: 600, threshold: 1)
require "sys/cpu"
require "etc"
# normalize the 1-minute load average based on processor count
return unless Sys::CPU.load_avg[0] / Etc.nprocessors > threshold
return unless DeviceDetector.new(request.user_agent).bot?
logger.info("Shedding bots: Returning 503 / Retry-After: #{wait} for #{request.remote_ip} / #{request.user_agent}")
response.headers["Retry-After"] = wait.to_s # Ask clients to retry after X seconds
render plain: "service unavailable: Retry in #{wait}", status: :service_unavailable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment