Home

Awesome

GCRA for Ruby

Build Status Code Climate RubyDoc

gcra is a Ruby implementation of a generic cell rate algorithm (GCRA), ported from and data-format compatible with the Go implementation throttled. It's useful for rate limiting (e.g. for HTTP requests) and allows weights specified per request.

Getting Started

gcra currently uses Redis (>= 2.6.12 for EVALSHA, SCRIPT LOAD, SEX with NX and PX) as a data store, although it supports other store implementations.

Add to your Gemfile:

gem 'gcra'
gem 'redis'

Create Redis, RedisStore and RateLimiter instances:

require 'redis'
require 'gcra/rate_limiter'
require 'gcra/redis_store'

redis = Redis.new(host: 'localhost', port: 6379, timeout: 0.1)
key_prefix = 'rate-limit-app1:'
store = GCRA::RedisStore.new(
          redis,
          key_prefix,
          { reconnect_on_readonly: false },
        )

rate_period = 0.5  # Two requests per second
max_burst = 10     # Allow 10 additional requests as a burst
limiter = GCRA::RateLimiter.new(store, rate_period, max_burst)

Rate limit a request (call this before each request):

key = '123'  # e.g. an account identifier
quantity = 1  # the number of requests 'used up' by this request, useful e.g. for batch requests

exceeded, info = limiter.limit(key, quantity)
# => [false, #<struct GCRA::RateLimitInfo limit=11, remaining=10, reset_after=0.5, retry_after=nil>]

RateLimiter#limit only tells you whether to limit a request or not. You'll have to react to its response yourself and e.g. return an error message and stop processing a request if the limit was exceeded.

License

MIT