server, lifecycle: drop idle upstream connections before uvicorn does (#27192)

* server, lifecycle: drop idle upstream connections before uvicorn does

The server kept idle connections to uvicorn pooled for a minute, but
uvicorn closes them after gunicorn's keepalive of 2 seconds. A request
that reused a connection uvicorn was closing got reset after it was
sent, and the client received a 503 "authentik starting".

Drop idle connections a second before uvicorn's keep-alive runs out.
Raising gunicorn's keepalive above the pool timeout would also work,
but uvicorn before 0.53 keeps a connection open after a request with
`Connection: Close` and silently drops the next request on it, so on
2026.8 a longer keepalive would leave that connection in the pool for
a minute instead of 2 seconds.

* server, lifecycle: raise uvicorn keep-alive to 5 seconds
This commit is contained in:
Dominic Roy authored and GitHub committed 2026-10-29 16:49:58 +00:00
1 parent 358eaba364
commit 62d919f36e
2 files changed
+116 -5

No files matched your search

+4
View File
@@ -64,6 +64,10 @@ timeout = 30
graceful_timeout = 30
dirty_graceful_timeout = 30
# Uvicorn closes idle upstream connections after this many seconds. The server's upstream
# client must drop them first, see GUNICORN_KEEPALIVE in src/server/mod.rs
keepalive = 5
logconfig_dict = get_logger_config()
workers = CONFIG.get_int("web.workers", 2)
+112 -5
View File
@@ -69,6 +69,23 @@ pub(super) static GUNICORN_READY: AtomicBool = AtomicBool::new(false);
pub(crate) type ServerClient = Client<UnixSocketConnector<PathBuf>, Body>;
/// How long uvicorn keeps an idle connection open. Match `keepalive` in
/// lifecycle/gunicorn.conf.py.
const GUNICORN_KEEPALIVE: Duration = Duration::from_secs(5);
/// Reusing a connection uvicorn is closing resets the request after it was
/// sent, and the client gets a 503. Drop idle connections a second before
/// uvicorn does, leaving room for a stalled event loop on either side.
const UPSTREAM_POOL_IDLE_TIMEOUT: Duration =
GUNICORN_KEEPALIVE.saturating_sub(Duration::from_secs(1));
fn upstream_client(socket_path: PathBuf) -> ServerClient {
Client::builder(TokioExecutor::new())
.pool_idle_timeout(UPSTREAM_POOL_IDLE_TIMEOUT)
.set_host(false)
.build(UnixSocketConnector::new(socket_path))
}
pub(crate) fn socket_path() -> PathBuf {
temp_dir().join("authentik.sock")
}
@@ -119,10 +136,6 @@ impl Server {
.stderr(Stdio::inherit())
.spawn()?;
let client = Client::builder(TokioExecutor::new())
.pool_idle_timeout(Duration::from_mins(1))
.set_host(false)
.build(UnixSocketConnector::new(socket_path.clone()));
// Keeps no idle connections, so a retry always gets a new one.
let retry_client = Client::builder(TokioExecutor::new())
.pool_max_idle_per_host(0)
@@ -131,7 +144,7 @@ impl Server {
Ok(Self {
gunicorn: Mutex::new(gunicorn),
client,
client: upstream_client(socket_path.clone()),
retry_client,
socket_path,
workers: ArcSwapOption::empty(),
@@ -411,3 +424,97 @@ pub(crate) async fn start(_cli: Cli, tasks: &mut Tasks) -> Result<Arc<Server>> {
Ok(server)
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicUsize;
use http_body_util::BodyExt as _;
use tempfile::TempDir;
use tokio::{
io::{AsyncReadExt as _, AsyncWriteExt as _},
net::UnixListener,
time::sleep,
};
use super::*;
/// Stands in for uvicorn: answers every request on a connection and keeps
/// it open. Returns how many connections it accepted.
fn spawn_upstream(socket_path: &std::path::Path) -> Arc<AtomicUsize> {
let listener = UnixListener::bind(socket_path).expect("failed to bind upstream socket");
let accepted = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&accepted);
tokio::spawn(async move {
loop {
let (mut stream, _) = listener.accept().await.expect("failed to accept");
counter.fetch_add(1, Ordering::SeqCst);
tokio::spawn(async move {
let mut request = Vec::new();
let mut buf = [0_u8; 1024];
loop {
let read = stream.read(&mut buf).await.expect("failed to read");
if read == 0 {
return;
}
request.extend_from_slice(&buf[..read]);
if request.ends_with(b"\r\n\r\n") {
request.clear();
stream
.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n")
.await
.expect("failed to write response");
}
}
});
}
});
accepted
}
async fn get(client: &ServerClient) {
let request = Request::builder()
.uri("http://localhost:8000/")
.body(Body::empty())
.expect("failed to build request");
let response = client.request(request).await.expect("request failed");
response
.into_body()
.collect()
.await
.expect("failed to read body");
}
/// Uvicorn may already be closing a connection that has been idle for
/// almost its whole keep-alive, so the client must not pick it up again.
#[tokio::test]
async fn upstream_client_does_not_reuse_connections_uvicorn_is_closing() {
let dir = TempDir::new().expect("failed to create temp dir");
let socket_path = dir.path().join("authentik.sock");
let accepted = spawn_upstream(&socket_path);
let client = upstream_client(socket_path);
get(&client).await;
sleep(GUNICORN_KEEPALIVE.saturating_sub(Duration::from_millis(200))).await;
get(&client).await;
assert_eq!(accepted.load(Ordering::SeqCst), 2);
}
/// Back-to-back requests still share a connection. This also shows the
/// upstream above tells reuse apart from new connections.
#[tokio::test]
async fn upstream_client_reuses_fresh_connections() {
let dir = TempDir::new().expect("failed to create temp dir");
let socket_path = dir.path().join("authentik.sock");
let accepted = spawn_upstream(&socket_path);
let client = upstream_client(socket_path);
get(&client).await;
get(&client).await;
assert_eq!(accepted.load(Ordering::SeqCst), 1);
}
}