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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Order < ApplicationRecord include AASM belongs_to :warehouse
Modeling an order lifecycle with AASM in Rails
state machine
guards
callbacks
Intermediate
10 steps
ruby
require "timeout" require "net/http" class RemoteInventoryClient
Bounding a slow HTTP call with Timeout in Ruby
timeout
error-handling
http
Intermediate
6 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.