Last active
August 10, 2023 02:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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