0
0
Ruby on Railsframework~30 mins

Rate limiting in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Implementing Rate Limiting in a Rails Controller
📖 Scenario: You are building a simple Rails API that serves user data. To protect your API from too many requests in a short time, you want to add rate limiting.This means limiting how many times a user can call the API within a certain time frame.
🎯 Goal: Build a Rails controller with a rate limiting mechanism that allows only 5 requests per minute per user.Use a simple in-memory store (a Ruby hash) to track request counts.
📋 What You'll Learn
Create a controller with an action that returns a JSON message
Add a configuration variable for the maximum allowed requests per minute
Implement rate limiting logic that counts requests per user IP
Return a 429 status code with a message when the limit is exceeded
💡 Why This Matters
🌍 Real World
APIs often need rate limiting to prevent abuse and ensure fair usage among users.
💼 Career
Understanding rate limiting is important for backend developers building scalable and secure web services.
Progress0 / 4 steps
1
Create a Rails controller with an action
Create a Rails controller named ApiController with an action user_data that renders JSON with { message: 'User data accessed' }.
Ruby on Rails
Need a hint?

Use render json: { message: 'User data accessed' } inside the user_data method.

2
Add a configuration variable for rate limit
Add a constant MAX_REQUESTS_PER_MINUTE set to 5 inside the ApiController class.
Ruby on Rails
Need a hint?

Define MAX_REQUESTS_PER_MINUTE = 5 inside the controller class but outside any method.

3
Implement rate limiting logic
Inside the user_data action, create a class variable @@request_counts as a hash to track requests by request.remote_ip. Increment the count for the current IP. If the count exceeds MAX_REQUESTS_PER_MINUTE, render JSON with { error: 'Rate limit exceeded' } and status 429. Otherwise, render the success message.
Ruby on Rails
Need a hint?

Use request.remote_ip to get the user's IP and track counts in @@request_counts.

4
Reset request counts every minute
Add a method reset_request_counts that clears @@request_counts. Use before_action to call reset_request_counts every minute by checking if a class variable @@last_reset is more than 60 seconds ago. Initialize @@last_reset to the current time.
Ruby on Rails
Need a hint?

Use before_action to call reset_request_counts before each request.

Reset counts if more than 60 seconds passed since last reset.