We found this while testing this website’s own server. A client opened a connection, sent half a request and then nothing. Seventy seconds later the connection was still open, and so was every other one like it. That is the shape of a slowloris attack: no traffic to speak of, just many connections that never finish, until the server runs out of file descriptors or memory.
The server already had a 20-second request timeout. It did not help, and the reason applies to most Axum services.
Why the Timeouts You Have Do Not Fire
hyper, the HTTP library under Axum, has a header read timeout of 30 seconds by default. It only works when the connection has a timer to measure time with. axum::serve (checked in axum 0.8.9) builds its connections without one, so the default never takes effect.
tower_http::timeout::TimeoutLayer does not cover the gap either. It wraps your service, and hyper calls your service only once the request headers are complete. A client that never finishes its headers never reaches it. The same holds for a keep-alive connection that sits idle after its first request.
Behind a proxy that buffers whole requests, such as Cloudflare or nginx, the proxy absorbs this. A published container port, a direct IP address or a forgotten firewall rule skips the proxy.
Check Your Server in a Minute
This script opens one connection, sends an unfinished request and waits up to 90 seconds for the server to close it:
import socket, time
s = socket.create_connection(("127.0.0.1", 3000))
s.settimeout(90)
s.sendall(b"GET / HTTP/1.1\r\nHost: localhost\r\n")
start = time.time()
try:
s.recv(1)
print(f"closed after {time.time() - start:.0f} s")
except socket.timeout:
print("still open after 90 s: no header timeout")
The Fix: Serve Connections Yourself
The fix is to accept connections yourself and give hyper a timer. It is about thirty lines, and the Axum Router stays as it is:
[dependencies]
hyper = { version = "1", features = ["server", "http1"] }
hyper-util = { version = "0.1", features = ["tokio"] }
tower = { version = "0.5", features = ["util"] }
use std::{net::SocketAddr, time::Duration};
use axum::{Router, extract::ConnectInfo};
use hyper::{body::Incoming, server::conn::http1, service::service_fn};
use hyper_util::rt::{TokioIo, TokioTimer};
use tokio::net::TcpListener;
use tower::ServiceExt;
pub async fn serve(listener: TcpListener, app: Router) {
loop {
let (stream, peer) = match listener.accept().await {
Ok(conn) => conn,
Err(_) => {
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
};
let app = app.clone();
let service = service_fn(move |mut req: hyper::Request<Incoming>| {
req.extensions_mut().insert(ConnectInfo::<SocketAddr>(peer));
app.clone().oneshot(req)
});
tokio::spawn(async move {
let _ = http1::Builder::new()
.timer(TokioTimer::new())
.header_read_timeout(Duration::from_secs(30))
.serve_connection(TokioIo::new(stream), service)
.await;
});
}
}
What each part does:
timerandheader_read_timeout. A connection that has not sent complete headers within 30 seconds is closed. In our tests this also closed idle keep-alive connections after 30 seconds, because waiting for the next request is waiting for headers.ConnectInfo. Handlers that read the client address keep working, because the loop inserts it for each request just asinto_make_service_with_connect_infowould.- The pause after an accept error. If the process runs out of file descriptors,
acceptfails at once. Without the pause the loop would spin at full CPU.
This serves HTTP/1.1, which is what a reverse proxy or tunnel normally speaks to the origin. For graceful shutdown, wrap each connection with hyper_util::server::graceful::GracefulShutdown (feature server-graceful) and stop accepting when your shutdown signal arrives.
If you put a proxy in front, give it a shorter idle timeout than the server’s 30 seconds, so it never reuses a connection the server is about to close.
Keep It Fixed
Run the script again. It should print closed after 30 s. Then turn it into a test, so a future refactor cannot remove the timer without a failing build. Make the timeout a parameter of serve and start it on a random port with a short value:
let listener = TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
tokio::spawn(serve(listener, app, Duration::from_millis(500)));
Connect, send nothing, and assert that the read returns end-of-file within a few seconds.
Check this again when you upgrade Axum. If a later version gives serve a timer, the custom loop can go, but only after the script above says so.