Skip to content

Commit 06c64a0

Browse files
feat: implement retry after throttle
1 parent 9af0d69 commit 06c64a0

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

config/initializers/rack_attack.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,21 @@ class Attack
8888
req.env['rack.jwt.payload']['user_id'] if req.env['rack.jwt.payload']
8989
end
9090

91+
# Add Retry-After header to throttled responses so clients can self-throttle
92+
Rack::Attack.throttled_responder = lambda do |req|
93+
match_data = req.env['rack.attack.match_data']
94+
period = match_data[:period].to_i
95+
epoch_time = match_data[:epoch_time].to_i
96+
retry_after = period - (epoch_time % period)
97+
98+
headers = {
99+
'Content-Type' => 'application/json',
100+
'Retry-After' => retry_after.to_s
101+
}
102+
body = { error: { code: 'RATE_LIMITED', message: 'Too many requests. Please retry later.' } }.to_json
103+
[429, headers, [body]]
104+
end
105+
91106
# Log blocked and throttled requests
92107
ActiveSupport::Notifications.subscribe('rack.attack') do |_name, _start, _finish, _request_id, payload|
93108
req = payload[:request]

0 commit comments

Comments
 (0)