ruby
45 lines · 9 steps
Layered API rate limiting in Rails
A messages API keys authentication and stacks two rate limits per API key before serving or enqueuing work.
Explained by
highlit
1class Api::MessagesController < ApiController
2 before_action :authenticate_api_key!
3
4 rate_limit to: 100,
5 within: 1.minute,
6 by: -> { current_api_key.id },
7 with: -> { render_rate_limit_exceeded },
8 store: Rails.cache
9
10 rate_limit to: 5,
11 within: 1.second,
12 by: -> { current_api_key.id },
13 only: :create,
14 with: -> { render_rate_limit_exceeded }
15
16 def index
17 messages = current_api_key.account.messages.order(created_at: :desc).limit(50)
18 render json: messages
19 end
20
21 def create
22 message = current_api_key.account.messages.new(message_params)
23
24 if message.save
25 DeliverMessageJob.perform_later(message)
26 render json: message, status: :created
27 else
28 render json: { errors: message.errors }, status: :unprocessable_entity
29 end
30 end
31
32 private
33
34 def message_params
35 params.require(:message).permit(:to, :body)
36 end
37
38 def render_rate_limit_exceeded
39 response.headers["Retry-After"] = "60"
40 render json: {
41 error: "rate_limit_exceeded",
42 message: "Too many requests for this API key. Slow down."
43 }, status: :too_many_requests
44 end
45end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Stacking multiple rate_limit declarations lets one endpoint enforce both a sustained ceiling and a tighter burst limit.
- 2Keying throttles by an authenticated identity like an API key isolates each caller's quota from everyone else's.
- 3Returning a Retry-After header with a 429 tells well-behaved clients exactly how long to back off.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/layered-api-rate-limiting-in-rails-explained-ruby-1ad1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.