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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.