rust
46 lines · 6 steps
A timeout-guarded health check in Axum
An Axum handler probes Postgres with a bounded timeout and reports three distinct states as JSON.
Explained by
highlit
1use std::time::Duration;
2
3use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
4use serde::Serialize;
5use sqlx::PgPool;
6use tokio::time::timeout;
7
8#[derive(Serialize)]
9pub struct HealthResponse {
10 status: &'static str,
11 database: &'static str,
12}
13
14pub async fn health_check(State(pool): State<PgPool>) -> impl IntoResponse {
15 let probe = sqlx::query_scalar::<_, i32>("SELECT 1").fetch_one(&pool);
16
17 match timeout(Duration::from_secs(2), probe).await {
18 Ok(Ok(_)) => (
19 StatusCode::OK,
20 Json(HealthResponse {
21 status: "ok",
22 database: "up",
23 }),
24 ),
25 Ok(Err(err)) => {
26 tracing::error!(error = %err, "database health probe failed");
27 (
28 StatusCode::SERVICE_UNAVAILABLE,
29 Json(HealthResponse {
30 status: "degraded",
31 database: "down",
32 }),
33 )
34 }
35 Err(_) => {
36 tracing::warn!("database health probe timed out");
37 (
38 StatusCode::SERVICE_UNAVAILABLE,
39 Json(HealthResponse {
40 status: "degraded",
41 database: "timeout",
42 }),
43 )
44 }
45 }
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping an async I/O call in a timeout keeps a probe from hanging forever on a stuck dependency.
- 2Nested Result matching lets you distinguish a timeout from an error from success and respond differently to each.
- 3Returning a status code paired with JSON gives clients both a machine-readable signal and structured detail.
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
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 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
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-timeout-guarded-health-check-in-axum-explained-rust-e5ab/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.