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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Stacking multiple rate_limit declarations lets one endpoint enforce both a sustained ceiling and a tighter burst limit.
  2. 2Keying throttles by an authenticated identity like an API key isolates each caller's quota from everyone else's.
  3. 3Returning a Retry-After header with a 429 tells well-behaved clients exactly how long to back off.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Layered API rate limiting in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code