Module: RecurlyApi::RateLimiting

Included in:
Client
Defined in:
lib/recurly_api/rate_limiting.rb

Overview

Retry again in case rate limit exceeded

Constant Summary collapse

RATE_LIMIT_MAX_RETRIES =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#ratelimit_retriesObject

Returns the value of attribute ratelimit_retries.



16
17
18
# File 'lib/recurly_api/rate_limiting.rb', line 16

def ratelimit_retries
  @ratelimit_retries
end

Instance Method Details

#rate_limit_exceed_responseObject



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/recurly_api/rate_limiting.rb', line 40

def rate_limit_exceed_response
  resp_headers = recurly_response.headers
  rate_limit_info = { limit: resp_headers[:x_ratelimit_limit],
                      remaining: resp_headers[:x_ratelimit_remaining],
                      reset_time_seconds: resp_headers[:x_ratelimit_reset],
                      reset_time: DateTime.strptime(resp_headers[:x_ratelimit_reset], '%s') }
  { success: false, status_code: 429,
    error: 'Recurly API Rate limit exceeded',
    message: 'Too Many Requests, See rate-limiting for more info',
    rate_limit_info: rate_limit_info }
end

#rate_limit_exceeded?Boolean

Check if rate limit exceeded or not using resp status code OR x_ratelimit_remaining header

Returns:

  • (Boolean)


20
21
22
23
24
# File 'lib/recurly_api/rate_limiting.rb', line 20

def rate_limit_exceeded?
  ratelimit_remaining = recurly_response.headers[:x_ratelimit_remaining]
  logger.info("x_ratelimit_remaining---- : #{ratelimit_remaining}")
  recurly_response.code.eql?(429) || (ratelimit_remaining && ratelimit_remaining.to_i < 1) # 1998
end

#retry_on_rate_limit_exceedObject



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/recurly_api/rate_limiting.rb', line 26

def retry_on_rate_limit_exceed
  max_retries = ratelimit_retries # max count to retry if rate limit requests are exceeded.
  retry_count = 0
  delay = 1 # in seconds
  begin
    raise 'API Rate limit exceeded' if rate_limit_exceeded?
  rescue StandardError => _e
    logger.warn "API Rate limit exceeded retrying again. Retries left: #{max_retries - retry_count}"
    sleep delay += retry_count
    retry_count += 1
    retry if retry_count < max_retries
  end
end