rust
41 lines · 7 steps
Turning Axum timeouts into 504 JSON
An Axum route caps a slow report handler with a Tower timeout layer and rewrites the timeout into a clean gateway-timeout response.
Explained by
highlit
1use std::time::Duration;
2
3use axum::{
4 body::Body,
5 http::{Request, Response, StatusCode},
6 response::IntoResponse,
7 routing::get,
8 Json, Router,
9};
10use serde_json::json;
11use tower::ServiceBuilder;
12use tower_http::timeout::TimeoutLayer;
13
14pub fn report_routes() -> Router {
15 Router::new()
16 .route("/reports/heavy", get(generate_heavy_report))
17 .layer(
18 ServiceBuilder::new()
19 .layer(TimeoutLayer::new(Duration::from_secs(5)))
20 .map_response(map_timeout_to_504),
21 )
22}
23
24fn map_timeout_to_504(response: Response<Body>) -> Response<Body> {
25 if response.status() == StatusCode::REQUEST_TIMEOUT {
26 return (
27 StatusCode::GATEWAY_TIMEOUT,
28 Json(json!({
29 "error": "report_generation_timed_out",
30 "message": "The report took too long to generate. Try narrowing the date range."
31 })),
32 )
33 .into_response();
34 }
35 response
36}
37
38async fn generate_heavy_report(_req: Request<Body>) -> impl IntoResponse {
39 let rows = crate::reporting::aggregate_yearly_totals().await;
40 Json(json!({ "rows": rows }))
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Tower layers wrap handlers uniformly, so cross-cutting concerns like timeouts live outside the business logic.
- 2Mapping a raw framework status into a domain-specific JSON error gives clients a clearer, actionable response.
- 3Composing behavior with ServiceBuilder keeps ordering explicit: apply the timeout, then reshape whatever it produces.
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
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 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
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/turning-axum-timeouts-into-504-json-explained-rust-fd1b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.