rust
53 lines · 6 steps
Rate-limit errors as Axum responses
A custom error type implements IntoResponse so a throttled request returns 429 with a Retry-After header automatically.
Explained by
highlit
1use std::time::Duration;
2
3use axum::{
4 extract::State,
5 http::{header::RETRY_AFTER, StatusCode},
6 response::{IntoResponse, Response},
7 Json,
8};
9use serde_json::json;
10
11#[derive(Clone)]
12struct AppState {
13 limiter: RateLimiter,
14}
15
16enum QuotaError {
17 Exceeded { retry_after: Duration },
18}
19
20impl IntoResponse for QuotaError {
21 fn into_response(self) -> Response {
22 match self {
23 QuotaError::Exceeded { retry_after } => {
24 let secs = retry_after.as_secs().max(1);
25 (
26 StatusCode::TOO_MANY_REQUESTS,
27 [(RETRY_AFTER, secs.to_string())],
28 Json(json!({
29 "error": "rate_limit_exceeded",
30 "message": "Quota exceeded, slow down.",
31 "retry_after": secs,
32 })),
33 )
34 .into_response()
35 }
36 }
37 }
38}
39
40async fn create_message(
41 State(state): State<AppState>,
42 Json(payload): Json<NewMessage>,
43) -> Result<impl IntoResponse, QuotaError> {
44 match state.limiter.check(&payload.sender).await {
45 Verdict::Allowed => {}
46 Verdict::Throttled { reset_in } => {
47 return Err(QuotaError::Exceeded { retry_after: reset_in });
48 }
49 }
50
51 let message = Message::persist(payload).await;
52 Ok((StatusCode::CREATED, Json(message)))
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing IntoResponse lets a domain error type map itself to a full HTTP response.
- 2Returning Result<_, E> from a handler turns error branches into clean early returns.
- 3Setting Retry-After alongside a 429 gives clients an actionable signal for when to retry.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 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/rate-limit-errors-as-axum-responses-explained-rust-0db4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.