module TrafficJam
Constants
- SimpleLimit
GCRA (Generic Cell Rate Algorithm) is a leaky bucket type rate limiting algorithm. GCRA works by storing a key in Redis with a ms-precision expiry representing the time that the limit will be completely reset. Each increment operation converts the increment amount into the number of milliseconds to be added to the expiry.
When a request comes in, we take the existing expiry value, subtract a fixed amount representing the limit’s total burst capacity from it, and compare the result to the current time. This result represents the next time to allow a request. If it’s in the past, we allow the incoming request, and if it’s in the future, we don’t. After a successful request, a new expiry is calculated. (see brandur.org/rate-limiting)
This limit type does not support decrements or changing the max value without a complete reset. This means that if the period or max value for an action/value key changes, the used and remaining values cannot be preserved.
Example:
Limit
is 5 per 10 seconds.An increment by 1 first sets the key to expire in 2s. Another immediate increment by 4 sets the expiry to 10s. Subsequent increments fail until clock time catches up to expiry
Attributes
Public Class Methods
Configure library in a block.
@yield [TrafficJam::Configuration]
# File lib/traffic_jam.rb, line 25 def configure yield config end
Create limit with registed max/period.
@param action [Symbol] registered action name @param value [String] limit target value @return [TrafficJam::Limit]
# File lib/traffic_jam.rb, line 34 def limit(action, value) limits = config.limits(action.to_sym) TrafficJam::Limit.new(action, value, **limits) end
Reset all limits associated with the given action. If action is omitted or nil, this will reset all limits.
@note Not recommended for use in production. @param action [Symbol] action to reset limits for @return [nil]
# File lib/traffic_jam.rb, line 45 def reset_all(action: nil) prefix = if action.nil? "#{config.key_prefix}:*" else "#{config.key_prefix}:#{action}:*" end config.redis.keys(prefix).each do |key| config.redis.del(key) end nil end