Class: ShopifyClient::Throttling::RedisStrategy

Inherits:
Strategy
  • Object
show all
Defined in:
lib/shopify-client/throttling/redis_strategy.rb

Overview

Use Redis to maintain API call limit throttling across threads/processes.

No delay for requests up to half of the call limit.

Instance Method Summary collapse

Methods inherited from Strategy

#build_interval_key, #on_request, #timestamp

Instance Method Details

#after_sleep(env, interval_key) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 29

def after_sleep(env, interval_key)
  header = env[:response_headers]['X-Shopify-Shop-Api-Call-Limit']

  return if header.nil?

  num_requests, max_requests = header.split('/')

  Redis.current.mapped_hmset(interval_key,
    num_requests: num_requests,
    max_requests: max_requests,
    header_timestamp: header_timestamp,
  )
end

#interval(interval_key) ⇒ Object

See Also:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 10

def interval(interval_key)
  num_requests, max_requests, header_timestamp = Redis.current.hmget(interval_key,
    :num_requests,
    :max_requests,
    :header_timestamp,
  ).map(&:to_i)

  num_requests = leak(num_requests, header_timestamp)

  max_unthrottled_requests = max_requests / 2

  if num_requests > num_unthrottled_requests
    Rational((num_requests - num_unthrottled_requests) * leak_rate, 1000)
  else
    0
  end
end

#leak(num_requests, header_timestamp) ⇒ Integer

Find the actual number of requests by subtracting requests leaked by the leaky bucket algorithm since the last header timestamp.

Parameters:

  • num_requests (Integer)
  • header_timestamp (Integer)

Returns:

  • (Integer)


50
51
52
53
54
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 50

def leak(num_requests, header_timestamp)
  n = Rational(timestamp - header_timestamp, leak_rate).floor

  n > num_requests ? 0 : num_requests - n
end

#leak_rateObject

Leak rate of the leaky bucket algorithm in milliseconds.



57
58
59
# File 'lib/shopify-client/throttling/redis_strategy.rb', line 57

def leak_rate
  500
end