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 std::sync::{Arc, Mutex, MutexGuard}; use std::time::Instant; pub struct TimedGuard<'a, T> {
A self-timing mutex guard in Rust
raii
mutex
deref
Advanced
7 steps
javascript
import { parsePhoneNumberFromString } from 'libphonenumber-js'; export class PhoneValidationError extends Error { constructor(message, code) {
Normalizing phone numbers with typed errors
validation
error-handling
custom-errors
Intermediate
6 steps
typescript
import { Injectable, computed, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs';
Optimistic updates with Angular signals
signals
optimistic-updates
state-management
Intermediate
9 steps
python
import os from datetime import datetime, timezone import jwt
JWT bearer auth as a FastAPI dependency
authentication
jwt
dependency-injection
Intermediate
7 steps
rust
use std::error::Error; use std::path::Path; use serde::Deserialize;
Custom CSV deserialization with serde in Rust
serde
csv
deserialization
Intermediate
7 steps
go
package config import ( "fmt"
Loading typed config from environment variables in Go
configuration
environment-variables
type-parsing
Beginner
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/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.