0

I want to use rack-attack gem to throttle requests to an API. I would like to include RateLimit HTTP headers in all the responses, not only the throttled ones, so API consumers are aware how much quota they have left.

The gem's docs contain example how to include those kind of headers but only for responses that get throttled (exceed the allowed limit):

Rack::Attack.throttled_response = lambda do |env|
  match_data = env['rack.attack.match_data']
  now = match_data[:epoch_time]

  headers = {
    'RateLimit-Limit' => match_data[:limit].to_s,
    'RateLimit-Remaining' => '0',
    'RateLimit-Reset' => (now + (match_data[:period] - now % match_data[:period])).to_s
  }

  [ 429, headers, ["Throttled\n"]]
end

How can I add those headers to all responses?

So far I have been using (now deprecated) rack-throttle gem that did have such option.

mrt
  • 1,669
  • 3
  • 22
  • 32

0 Answers0