Skip to content

Instantly share code, notes, and snippets.

@maksadbek
Created August 26, 2014 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maksadbek/a11bff71e7066ca6c3b4 to your computer and use it in GitHub Desktop.
Save maksadbek/a11bff71e7066ca6c3b4 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
...
before_filter :throttle
def throttle
client_ip = request.env["REMOTE_ADDR"]
key = "count:#{client_ip}"
count = REDIS.get(key)
unless count
REDIS.set(key, 0)
REDIS.expire(key, THROTTLE_TIME_WINDOW)
return true
end
if count.to_i >= THROTTLE_MAX_REQUESTS
render :status => 429, :json => {:message => "You have fired too many requests. Please wait for some time."}
return
end
REDIS.incr(key)
true
end
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment