Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Rack middleware for rate-limiting incoming HTTP requests.

License

NotificationsYou must be signed in to change notification settings

dryruby/rack-throttle

https://github.com/rack/rack-attack Accomplishes the same goal as rack-throttle,but has more active maintenance, usage, and maturity. Please think about using rack-attackover rack-throttle.

rack-throttle will still continue to exist to support legacy ruby applications (<2.3), butwill not be getting new features added as it exists strictly to support existing apps.

HTTP Request Rate Limiter for Rack Applications

This isRack middleware that provides logic for rate-limiting incomingHTTP requests to Rack applications. You can useRack::Throttle with anyRuby web framework based on Rack, including with Ruby on Rails and withSinatra.

Features

  • Throttles a Rack application by enforcing a minimum time interval betweensubsequent HTTP requests from a particular client, as well as by defininga maximum number of allowed HTTP requests per a given time period (per minute,hourly, or daily).
  • Compatible with any Rack application and any Rack-based framework.
  • Stores rate-limiting counters in any key/value store implementation thatresponds to#[]/#[]= (like Ruby's hashes) or to#get/#set (likememcached or Redis).
  • Compatible with thegdbm binding included in Ruby's standard library.
  • Compatible with thememcached,memcache-client,memcache andredis gems.
  • Compatible withHeroku'smemcached add-on(currently available as a free beta service).

Examples

Adding throttling to a Rails application

# config/application.rbrequire'rack/throttle'classApplication <Rails::Applicationconfig.middleware.useRack::Throttle::Intervalend

Adding throttling to a Sinatra application

#!/usr/bin/env ruby -rubygemsrequire'sinatra'require'rack/throttle'useRack::Throttle::Intervalget('/hello'){"Hello, world!\n"}

Adding throttling to a Rackup application

#!/usr/bin/env rackuprequire'rack/throttle'useRack::Throttle::Intervalrunlambda{ |env|[200,{'Content-Type'=>'text/plain'},"Hello, world!\n"]}

Enforcing a minimum 3-second interval between requests

useRack::Throttle::Interval,:min=>3.0

Allowing a maximum of 1 request per second

useRack::Throttle::Second,:max=>1

Allowing a maximum of 60 requests per minute

useRack::Throttle::Minute,:max=>60

Allowing a maximum of 100 requests per hour

useRack::Throttle::Hourly,:max=>100

Allowing a maximum of 1,000 requests per day

useRack::Throttle::Daily,:max=>1000

Combining various throttling constraints into one overall policy

useRack::Throttle::Daily,:max=>1000# requestsuseRack::Throttle::Hourly,:max=>100# requestsuseRack::Throttle::Minute,:max=>60# requestsuseRack::Throttle::Second,:max=>1# requestsuseRack::Throttle::Interval,:min=>3.0# seconds

Storing the rate-limiting counters in a GDBM database

require'gdbm'useRack::Throttle::Interval,:cache=>GDBM.new('tmp/throttle.db')

Storing the rate-limiting counters on a Memcached server

require'memcached'useRack::Throttle::Interval,:cache=>Memcached.new,:key_prefix=>:throttle

Storing the rate-limiting counters on a Redis server

require'redis'useRack::Throttle::Interval,:cache=>Redis.new,:key_prefix=>:throttle

Throttling Strategies

Rack::Throttle supports four built-in throttling strategies:

  • Rack::Throttle::Interval: Throttles the application by enforcing aminimum interval (by default, 1 second) between subsequent HTTP requests.
  • Rack::Throttle::Hourly: Throttles the application by defining amaximum number of allowed HTTP requests per hour (by default, 3,600requests per 60 minutes, which works out to an average of 1 request persecond).
  • Rack::Throttle::Daily: Throttles the application by defining amaximum number of allowed HTTP requests per day (by default, 86,400requests per 24 hours, which works out to an average of 1 request persecond).
  • Rack::Throttle::Minute: Throttles the application by defining amaximum number of allowed HTTP requests per minute (by default, 60requests per 1 minute, which works out to an average of 1 request persecond).
  • Rack::Throttle::Second: Throttles the application by defining amaximum number of allowed HTTP requests per second (by default, 1request per second).
  • Rack::Throttle::Rules: Throttles the application by definingdifferent rules of allowed HTTP request per time_window based on therequest method and the request paths, or use a default.

You can fully customize the implementation details of any of these strategiesby simply subclassing one of the aforementioned default implementations.And, of course, should your application-specific requirements besignificantly more complex than what we've provided for, you can also defineentirely new kinds of throttling strategies by subclassing theRack::Throttle::Limiter base class directly.

Example

Customize themax_per_second to be different depending on the request's method.

classRack::Throttle::RequestMethod <Rack::Throttle::Seconddefmax_per_second(request=nil)return(options[:max_per_second] ||options[:max] ||1)unlessrequestifrequest.request_method =="POST"4else10endendalias_method:max_per_window,:max_per_secondend

Passing the correct options forRules strategy.

rules=[{method:"POST",limit:5},{method:"GET",limit:10},{method:"GET",path:"/users/.*/profile",limit:3},{method:"GET",path:"/users/.*/reset_password",limit:1},{method:"GET",path:"/external/callback",whitelisted:true}]ip_whitelist=["1.2.3.4","5.6.7.8"]default=10useRack::Throttle::Rules,rules:rules,ip_whitelist:ip_whitelist,default:default

This configuration would allow a maximum of 3 profile requests per second (default), i1 reset password requests per second, 5 POST and 10 GET requests per second(always also based on the IPaddress). Additionally it would whitelist the external callbackand add a ip-whitelisting for the given ips.

Rules are checked in this order:

  • ip whitelist
  • rules withpaths,
  • rules withmethods only,
  • default.

It is possible to set the time window for this strategy to::second (default),:minute,:hour or:day, to change the check interval to these windows.

useRack::Throttle::Rules,rules:rules,time_window::minute

HTTP Client Identification

The rate-limiting counters stored and maintained byRack::Throttle arekeyed to unique HTTP clients.

By default, HTTP clients are uniquely identified by their IP address asreturned byRack::Request#ip. If you wish to instead use a more granular,application-specific identifier such as a session key or a user accountname, you need only subclass a throttling strategy implementation andoverride the#client_identifier method.

HTTP Response Codes and Headers

403 Forbidden (Rate Limit Exceeded)

When a client exceeds their rate limit,Rack::Throttle by default returnsa "403 Forbidden" response with an associated "Rate Limit Exceeded" messagein the response body.

An HTTP 403 response means that the server understood the request, but isrefusing to respond to it and an accompanying message will explain why.This indicates an error on the client's part in exceeding the rate limitsoutlined in the acceptable use policy for the site, service, or API.

503 Service Unavailable (Rate Limit Exceeded)

However, there exists a widespread practice of instead returning a "503Service Unavailable" response when a client exceeds the set rate limits.This is technically dubious because it indicates an error on the server'spart, which is certainly not the case with rate limiting - it was the clientthat committed the oops, not the server.

An HTTP 503 response would be correct in situations where the server wasgenuinely overloaded and couldn't handle more requests, but for ratelimiting an HTTP 403 response is more appropriate. Nonetheless, if you thinkotherwise,Rack::Throttle does allow you to override the returned HTTPstatus code by passing in a:code => 503 option when constructing aRack::Throttle::Limiter instance.

Dependencies

Installation

The recommended installation method is viaRubyGems.To install the latest official release of the gem, do:

% [sudo] gem install rack-throttle

Authors

Contributors

Contributing

  • Do your best to adhere to the existing coding conventions and idioms.
  • Don't use hard tabs, and don't leave trailing whitespace on any line.Before committing, rungit diff --check to make sure of this.
  • Do document every method you add usingYARD annotations. Read thetutorial or just look at the existing code for examples.
  • Don't touch the gemspec orVERSION files. If you need to change them,do so on your private branch only.
  • Do feel free to add yourself to theCREDITS file and thecorresponding list in the theREADME. Alphabetical order applies.
  • Don't touch theAUTHORS file. If your contributions are significantenough, be assured we will eventually add you in there.

License

This is free and unencumbered public domain software. For more information,seehttp://unlicense.org/ or the accompanyingUNLICENSE file.

About

Rack middleware for rate-limiting incoming HTTP requests.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors16

Languages


[8]ページ先頭

©2009-2026 Movatter.jp