#1032·pingora

[bug] Health checks have no total deadline: an endless response body stalls the load balancer

Author: YZL0v3ZZCreated Sep 30, 2026Updated Sep 30, 2026

Describe the bug

HttpHealthCheck::check() reads the backend response to its end before it returns, and the only deadline it sets is a per-read read_timeout. A backend that answers 200 OK and then keeps sending body bytes at an interval shorter than that deadline makes every individual read complete inside it, so the check never returns. The failure needs no malice: a streaming health endpoint, or a backend that terminates its response lazily, produces the same state.

Nothing else in the path bounds the check. A health-check pass awaits every target on one lane in sequential mode, which is the default (parallel_health_check: false), and in parallel mode it still joins every spawned check (pingora-load-balancing/src/lib.rs:510-525). The load balancer's background services await the pass in a race_shutdown with shutdown (pingora-load-balancing/src/background.rs:74-90, :233-239, :430-441), so the wait ends only when the process receives a shutdown signal.

Consequently one backend freezes the control plane of the whole group. Health transitions stop for every backend, so unhealthy backends stay in rotation and healthy backends cannot be re-admitted; LoadBalancerGroup runs service discovery in the same loop, so membership and selector updates also stop; HealthCheckService signals readiness to dependent services only after the first pass completes (background.rs:433-439), so those services never start. The proxy itself continues to serve traffic, which makes the failure silent.

Root cause

1. The default HTTP health check looks bounded

The constructor documents a one-second connect timeout and a one-second read timeout, and sets both on the peer template it clones for every target.

rust
// pingora-load-balancing/src/health_check.rs:206-220
        let mut req = RequestHeader::build("GET", b"/", None).unwrap();
        req.append_header("Host", host).unwrap();
        let sni = if tls { host.into() } else { String::new() };
        let mut peer_template = HttpPeer::new("0.0.0.0:1", tls, sni);
        peer_template.options.connection_timeout = Some(Duration::from_secs(1));
        peer_template.options.read_timeout = Some(Duration::from_secs(1));
        HttpHealthCheck {
            consecutive_success: 1,
            consecutive_failure: 1,
            peer_template,
            connector: HttpConnector::new(None),
            reuse_connection: false,
            req,
            validator: None,
            port_override: None,

2. The check connects, writes the request, and reads the response header

rust
// pingora-load-balancing/src/health_check.rs:292-306
        let session = self.connector.get_http_session(&peer).await?;

        let mut session = session.0;

        session.set_write_timeout(peer.options.write_timeout);

        let req = Box::new(self.req.clone());
        session.write_request_header(req).await?;
        session.finish_request_body().await?;

        custom_session!(session.finish_custom().await?);

        session.set_read_timeout(peer.options.read_timeout);

        session.read_response_header().await?;

The connect phase is bounded by connection_timeout, and the response header read is bounded by the per-read read_timeout, so a backend that sends a header and then goes silent is reported as unhealthy. The problem is the body that keeps arriving.

3. The drain loop has no total deadline, and it is not limited to reusable connections

rust
// pingora-load-balancing/src/health_check.rs:319-324
        while session.read_response_body().await?.is_some() {
            // drain the body if any
        }

        // TODO(slava): do it concurrently wtih body drain?
        custom_session!(session.drain_custom_messages().await?);

The connection is only kept when reuse_connection is true, and that field defaults to false, so the drain runs for a connection that will be dropped anyway. A bounded drain is needed in both cases; the point here is that nothing bounds it.

rust
// pingora-load-balancing/src/health_check.rs:326-331
        if self.reuse_connection {
            let idle_timeout = peer.idle_timeout();
            self.connector
                .release_http_session(session, &peer, idle_timeout)
                .await;
        }

The loop ends when read_response_body yields None, which for HTTP/1 means the framing-defined end of the body (pingora-core/src/protocols/http/v1/client.rs:476-478), and for HTTP/2 means END_STREAM. Only the backend can produce that condition.

4. The read deadline is per read, not per response

The session field documents this explicitly.

rust
// pingora-core/src/protocols/http/v1/client.rs:44-48
    // timeouts:
    /// The read timeout, which will be applied to both reading the header and the body.
    /// The timeout is reset on every read. This is not a timeout on the overall duration of the
    /// response.
    pub read_timeout: Option<Duration>,

The implementation matches: each body read gets its own timer around one read future.

rust
// pingora-core/src/protocols/http/v1/client.rs:479-490
    pub async fn read_body_ref(&mut self) -> Result<Option<&[u8]>> {
        let result = match self.read_timeout {
            Some(t) => match timeout(t, self.do_read_body()).await {
                Ok(res) => res,
                Err(_) => Error::e_explain(ReadTimedout, format!("reading body, timeout: {t:?}")),
            },
            None => self.do_read_body().await,
        };

        result.map(|maybe_body| {
            maybe_body.map(|body_ref| {
                let slice = self.body_reader.get_body(&body_ref);

The HTTP/2 client session applies the same rule, so a deployment that probes an HTTP/2 backend inherits the same unbounded wait.

rust
// pingora-core/src/protocols/http/v2/client.rs:60-63
    /// The read timeout, which will be applied to both reading the header and the body.
    /// The timeout is reset on every read. This is not a timeout on the overall duration of the
    /// response.
    pub read_timeout: Option<Duration>,

5. No other deadline covers the response phase

total_connection_timeout wraps connection establishment only, and the HTTP health check does not set it.

rust
// pingora-core/src/connectors/mod.rs:398-412
    // Create the future that does the connections, but don't evaluate it until
    // we decide if we need a timeout or not
    let connect_future =
        do_connect_inner(peer, bind_to, alpn_override, tls_ctx, offload_wait_duration);

    match peer.total_connection_timeout() {
        Some(t) => match pingora_timeout::timeout(t, connect_future).await {
            Ok(res) => res,
            Err(_) => Error::e_explain(
                ConnectTimedout,
                format!("connecting to server {peer}, total-connection timeout {t:?}"),
            ),
        },
        None => connect_future.await,
    }

Inside that future, connection_timeout bounds the TCP connect (pingora-core/src/connectors/l4.rs:158-176) and the TLS handshake (pingora-core/src/connectors/tls/boringssl_openssl/mod.rs:250-258, pingora-core/src/connectors/tls/rustls/mod.rs:284-293, pingora-core/src/connectors/tls/s2n/mod.rs:161-170), and write_timeout defaults to None. The health check has no field for a per-probe deadline, and the HealthCheck trait only documents cancellation on shutdown, not a time bound.

rust
// pingora-load-balancing/src/health_check.rs:45-52
pub trait HealthCheck {
    /// Check the given backend.
    ///
    /// `Ok(())`` if the check passes, otherwise the check fails.
    ///
    /// A health-check pass drops this future to cancel the check on shutdown,
    /// so an implementation must not rely on running to completion once polled.
    async fn check(&self, target: &Backend) -> Result<()>;

6. The pass awaits every check, so one stuck check owns the pass

rust
// pingora-load-balancing/src/lib.rs:464-481
        async fn check_and_report(
            backend: &Backend,
            check: &Arc<dyn HealthCheck + Send + Sync>,
            health: &Health,
        ) {
            let errored = check.check(backend).await.err();
            let healthy = errored.is_none();
            let flipped = health.observe_health(healthy, check.health_threshold(healthy));
            if flipped {
                check.health_status_change(backend, healthy).await;
                let summary = check.backend_summary(backend);
                if let Some(error) = errored {
                    warn!("{summary} becomes unhealthy, {error}");
                } else {
                    info!("{summary} becomes healthy");
                }
            }
        }

check.check(backend).await has no deadline, and the health observation is recorded only after the check returns. Parallel mode spawns one task per target (lib.rs:496-508) but then waits for all of them, so the pass still does not complete; sequential mode waits for one target at a time, so targets after the stalled one are not checked in that pass either.

rust
// pingora-load-balancing/src/lib.rs:510-525
            // Drained one at a time rather than with `JoinSet::join_all`, which
            // resumes a task panic in this caller. One backend's check panicking
            // should not abort the checks for every other backend.
            while let Some(joined) = jobs.join_next().await {
                if let Err(error) = joined {
                    // That backend keeps its previous health for this pass.
                    warn!("health check task failed: {error}");
                }
            }
        } else {
            for backend in state.targets.iter() {
                if let Some(health) = state.health.get(&self.health_key(backend)) {
                    check_and_report(backend, &health_check, health).await;
                }
            }
        }

The runner isolates a panicking check from the other targets, as the comment states. A check that never returns is not isolated by the same mechanism, because it holds the lane instead of failing.

7. The service loop only races shutdown, so the stall is permanent

rust
// pingora-load-balancing/src/background.rs:74-90
async fn race_shutdown<F: Future>(shutdown: &mut ShutdownWatch, work: F) -> Raced<F::Output> {
    tokio::pin!(work);
    loop {
        tokio::select! {
            biased;
            change = shutdown_changed(&mut *shutdown) => match change {
                WatchChange::ShuttingDown => return Raced::ShuttingDown,
                WatchChange::Spurious => continue,
                // Nothing can signal shutdown any more, so stop racing
                // altogether and let the work finish.
                WatchChange::Closed => break,
            },
            output = &mut work => return Raced::Completed(output),
        }
    }
    Raced::Completed(work.await)
}

Raced::ShuttingDown is the only path that drops the pass. LoadBalancer::run uses this wrapper around the pass, after which it reschedules the next pass.

rust
// pingora-load-balancing/src/background.rs:233-239
            if schedule.health_check_is_due(now) {
                let health_check = self.backends.run_health_check(self.parallel_health_check);
                match race_shutdown(&mut shutdown, health_check).await {
                    Raced::ShuttingDown => return,
                    Raced::Completed(()) => schedule.health_check_finished_at(now),
                }
            }

HealthCheckService::run additionally gates readiness on the first completed pass, so the stall also withholds readiness from dependents.

rust
// pingora-load-balancing/src/background.rs:430-441
            let health_check = self.registry.run_health_check(self.parallel_health_check);
            match race_shutdown(&mut shutdown, health_check).await {
                Raced::ShuttingDown => return,
                Raced::Completed(()) => {
                    if let Some(ready) = ready_opt.take() {
                        // The initial health pass completed, so services depending on
                        // this registry can start receiving traffic.
                        ServiceReadyNotifier::notify_ready(ready);
                    }
                    schedule.health_check_finished_at(Instant::now());
                }
            }

The service task is awaited by the server runtime with no liveness check on it, so a pass that never completes keeps the task alive until the process shuts down.

Pingora info

Pingora version: 0.9.0, main at 4487f7b2ab50f159e4a2cf4f6a6b813f61bb6e19 Rust version: nightly-2026-03-21 (toolchain used for the reproduction) Operating system version: Linux on x86_64. The reproducer drives the production health check over loopback TCP, so it is platform-independent.

Steps to reproduce

Save the file below as pingora-load-balancing/tests/pingora_healthcheck_endless_body.rs and run:

cargo +nightly-2026-03-21 test -p pingora-load-balancing --test pingora_healthcheck_endless_body -- --nocapture

The mock backend serves 200 OK with Transfer-Encoding: chunked and writes one chunk every 50 ms without ever sending the terminating chunk. Each chunk arrives far inside the one-second per-read deadline, so the per-read timeout never fires. The third test is the control: the same path against a backend that ends its body, which returns normally.

pingora-load-balancing/tests/pingora_healthcheck_endless_body.rs (runnable test file)
rust
//! An HTTP health check has no total deadline, so a backend that never ends its
//! 200 response body parks `check()` forever and stalls the health-check pass.
//!
//! Integration: `pingora-load-balancing/tests/pingora_healthcheck_endless_body.rs`
//! Run: cargo +nightly-2026-03-21 test -p pingora-load-balancing --test pingora_healthcheck_endless_body -- --nocapture
//! On `main` at 4487f7b the two `*_must_not_*` tests fail after the 5s bound; the control passes.

use std::collections::BTreeSet;
use std::net::SocketAddr;
use std::time::Duration;

use pingora_load_balancing::discovery::Static;
use pingora_load_balancing::health_check::{HealthCheck, HttpHealthCheck};
use pingora_load_balancing::{Backend, Backends};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::time::timeout;

/// Test-side bound. On the affected version the check never returns, so the outer timeout
/// always fires first; a bounded implementation returns well inside it.
const BOUND: Duration = Duration::from_secs(5);

/// Mock backend. `endless` => answer `200 OK` with a chunked body that never ends;
/// otherwise answer a complete 2-byte body (control).
///
/// The chunk interval is far below the health check's 1s `read_timeout`, so the per-read
/// timeout can never fire: the per-read budget is not a total budget.
async fn spawn_origin(endless: bool) -> SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        loop {
            let Ok((mut io, _)) = listener.accept().await else {
                break;
            };
            tokio::spawn(async move {
                serve(&mut io, endless).await;
            });
        }
    });
    addr
}

async fn serve(io: &mut TcpStream, endless: bool) {
    // Consume the request head (GET / HTTP/1.1 + Host).
    let mut buf = [0u8; 1024];
    let _ = io.read(&mut buf).await;

    if endless {
        io.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
            .await
            .unwrap();
        loop {
            if io.write_all(b"5\r\nhello\r\n").await.is_err() {
                return;
            }
            let _ = io.flush().await;
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    } else {
        io.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
            .await
            .unwrap();
        let _ = io.flush().await;
    }
}

/// Core bug: `HttpHealthCheck::check()` drags the response body until the peer ends it.
/// A backend that keeps it open forever pins the check forever.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn health_check_must_not_drain_an_endless_body_forever() {
    let addr = spawn_origin(true).await;
    let check = HttpHealthCheck::new("example.com", false);
    let backend = Backend::new(&addr.to_string()).unwrap();

    let outcome = timeout(BOUND, check.check(&backend)).await;
    assert!(
        outcome.is_ok(),
        "VULNERABILITY REPRODUCED: HttpHealthCheck::check() was still pending after \
         {BOUND:?}. The drain loop at pingora-load-balancing/src/health_check.rs:319-321 \
         has no total deadline: read_timeout (1s) is reset on every read \
         (v1/client.rs:479-490), so a backend that never ends its 200 body parks the \
         check forever."
    );
}

/// Impact: the pass is one serial lane (`lib.rs:519-524`), and the LB background service
/// awaits the whole pass with no deadline (`background.rs:234/334/430`). One endless body
/// therefore stops health checking (and discovery updates) for every backend.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn one_endless_body_backend_must_not_stall_the_whole_health_check_pass() {
    let stalled = spawn_origin(true).await;
    let good = spawn_origin(false).await;

    let backends_set = BTreeSet::from([
        Backend::new(&stalled.to_string()).unwrap(),
        Backend::new(&good.to_string()).unwrap(),
    ]);
    let mut backends = Backends::new(Static::new(backends_set));
    backends.set_health_check(Box::new(HttpHealthCheck::new("example.com", false)));
    backends.update(|_| {}).await.unwrap();

    let pass = timeout(BOUND, backends.run_health_check(false)).await;
    assert!(
        pass.is_ok(),
        "VULNERABILITY REPRODUCED: the whole health-check pass was still pending after \
         {BOUND:?} because one backend streams an endless body. `run_health_check` \
         (lib.rs:459-533) awaits every check without a per-check deadline, so the \
         LoadBalancer/HealthCheckService loop (background.rs:234/334/430) never regains \
         control: no backend is checked again, discovery updates stop, and readiness is \
         never signalled."
    );
}

/// Control: an identical backend with a terminating body makes the same code path return
/// quickly, so the stall above is caused by the missing total deadline, not by the harness.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn health_check_passes_for_a_terminating_body() {
    let addr = spawn_origin(false).await;
    let check = HttpHealthCheck::new("example.com", false);
    let backend = Backend::new(&addr.to_string()).unwrap();

    let outcome = timeout(BOUND, check.check(&backend)).await;
    match outcome {
        Ok(Ok(())) => {}
        other => panic!(
            "control failed: the health check did not complete successfully in {BOUND:?}: {other:?}"
        ),
    }
}

Expected results

The whole probe is bounded. A backend that never ends its response body is reported as a failed check, the pass completes, later passes run, and the background service keeps applying health transitions, discovery updates, and readiness. Deployments can bound a probe without dropping the response phase, for example with a per-check deadline or a bounded drain.

Observed results

Two of the three tests failed after the 5-second bound on main at 4487f7b; the control passed.

Test output (sanitized: user, host, and paths normalized; the panic line numbers refer to the runner's copy of the reproducer, whose provenance header is 32 lines longer than the listing above)
<user>@<hos