0
0
Ruby on Railsframework~10 mins

Rate limiting in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to set a rate limit of 5 requests per minute using Rack::Attack.

Ruby on Rails
Rack::Attack.throttle('req/ip', limit: 5, period: 60) do |req|
  req.[1]
end
Drag options to blanks, or click blank then click option'
Auser_agent
Bpath
Chost
Dip
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'path' instead of 'ip' will limit requests per URL, not per user.
Using 'user_agent' is not reliable for identifying unique users.
2fill in blank
medium

Complete the code to block requests from a specific IP address '192.168.1.1'.

Ruby on Rails
Rack::Attack.blocklist('block 192.168.1.1') do |req|
  req.[1] == '192.168.1.1'
end
Drag options to blanks, or click blank then click option'
Apath
Buser_agent
Cip
Dhost
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'user_agent' will not block by IP.
Using 'path' or 'host' will not correctly identify the IP.
3fill in blank
hard

Fix the error in the throttle block to correctly count requests per user ID.

Ruby on Rails
Rack::Attack.throttle('req/user', limit: 10, period: 60) do |req|
  req.env['warden'].user.[1]
end
Drag options to blanks, or click blank then click option'
Aname
Bid
Cemail
Dsession
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'name' or 'email' may not be unique or always present.
Using 'session' is not a user attribute.
4fill in blank
hard

Fill both blanks to create a custom response for throttled requests with status 429 and a JSON message.

Ruby on Rails
Rack::Attack.throttled_response = lambda do |env|
  [[1], { 'Content-Type' => 'application/json' }, [{ error: [2] }.to_json]]
end
Drag options to blanks, or click blank then click option'
A429
B"Too many requests"
C"Request limit exceeded"
D403
Attempts:
3 left
💡 Hint
Common Mistakes
Using 403 instead of 429 is incorrect for rate limiting.
Not using a string message in JSON causes errors.
5fill in blank
hard

Fill all three blanks to define a throttle that limits POST requests to '/login' to 5 per minute per IP.

Ruby on Rails
Rack::Attack.throttle('logins/ip', limit: [1], period: [2]) do |req|
  req.[3] if req.path == '/login' && req.post?
end
Drag options to blanks, or click blank then click option'
A5
B60
Cip
Duser_agent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'user_agent' instead of 'ip' will not limit per user IP.
Setting the wrong period or limit changes the throttle behavior.