rust
50 lines · 7 steps
A maintenance-mode gate in Axum
An Axum middleware that flips the whole API into a 503 response while a shared flag is switched on.
Explained by
highlit
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use axum::body::Body;
5use axum::extract::State;
6use axum::http::{header, Request, StatusCode};
7use axum::middleware::Next;
8use axum::response::{IntoResponse, Json, Response};
9use serde_json::json;
10
11#[derive(Clone)]
12pub struct MaintenanceState {
13 enabled: Arc<AtomicBool>,
14 retry_after_secs: u64,
15}
16
17impl MaintenanceState {
18 pub fn new(retry_after_secs: u64) -> Self {
19 Self {
20 enabled: Arc::new(AtomicBool::new(false)),
21 retry_after_secs,
22 }
23 }
24
25 pub fn set(&self, on: bool) {
26 self.enabled.store(on, Ordering::Relaxed);
27 }
28}
29
30pub async fn maintenance_guard(
31 State(state): State<MaintenanceState>,
32 request: Request<Body>,
33 next: Next,
34) -> Response {
35 if state.enabled.load(Ordering::Relaxed) {
36 let body = Json(json!({
37 "error": "service_unavailable",
38 "message": "The service is temporarily down for maintenance.",
39 }));
40
41 return (
42 StatusCode::SERVICE_UNAVAILABLE,
43 [(header::RETRY_AFTER, state.retry_after_secs.to_string())],
44 body,
45 )
46 .into_response();
47 }
48
49 next.run(request).await
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An Arc<AtomicBool> lets many request handlers read a toggle concurrently while an admin path flips it, with no locks.
- 2Axum middleware can short-circuit the request by returning a Response instead of calling next.run.
- 3Pairing a 503 with a Retry-After header tells clients to back off politely instead of hammering the server.
Related explainers
rust
use axum::body::Bytes; use axum::http::{header, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use serde::Serialize;
Custom Axum responses with per-user ETags
etag
trait-implementation
generics
Intermediate
7 steps
rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use std::sync::Arc;
Batch inserts with per-item status in Axum
batch-processing
error-handling
serde
Intermediate
8 steps
javascript
const express = require('express'); const app = express();
Enforcing HTTPS with Express middleware
middleware
https
security
Intermediate
6 steps
rust
use std::time::Duration; #[derive(Debug, PartialEq)] pub enum ParseDurationError {
Parsing duration strings safely in Rust
parsing
error-handling
checked-arithmetic
Intermediate
8 steps
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
rust
use std::time::Duration; #[derive(Debug, Clone, Copy)] pub struct LatencyStats {
Computing latency percentiles in Rust
percentiles
interpolation
closures
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/a-maintenance-mode-gate-in-axum-explained-rust-dde3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.