Skip to content

Container fetch pool idles connections out at 5 s, matching uvicorn's and Node's keep-alive, so a request sent at that moment is lost #8628

Open

Description

@max-sixty

containerFetch reaches a container port through a pooled HTTP client, kj::newHttpClient(timer, headerTable, address, {.entropySource = entropySource}) in src/workerd/api/container.c++. The pool keeps an idle connection for kj's default HttpClientSettings::idleTimeout, 5 s. Two common container servers close an idle keep-alive connection at the same 5 s: uvicorn (timeout_keep_alive) and Node's http.Server (keepAliveTimeout, 5000 in Node 26). A request the pool sends on a connection idle for about 5 s reaches a server that is closing it, and it fails with "Network connection lost", which the Containers SDK returns as a 500, "Container suddenly disconnected, try again". NetworkAddressHttpClient::getClient() checks canReuse(), which sees only a close that has already arrived, and nothing resends the request on a new connection.

A local repro in wrangler dev (wrangler 4.156.1): a Container Durable Object sends bursts of three concurrent containerFetch requests to uvicorn 0.54, with an idle gap between bursts.

Idle gap before the burst Lost, server keep-alive 5 s Lost, server keep-alive 75 s
1000–4995 ms 0 of 126 0 of 72
5000 ms 10 of 42 0 of 54
5005–6000 ms 0 of 150 0 of 96

In production, both requests our Worker lost this way in a week went out on a connection idle 4.86 s and 5.03 s.

Either change would remove the race:

  • an idle timeout for the container pool below common server keep-alives, such as 4 s;
  • resending a request on a new connection when a reused connection closes before any response byte arrives and before the request body has been read, as browsers and Go's net/http do.

Until then, a container server avoids it by keeping idle connections longer than 5 s; we set uvicorn's to 60 s (max-sixty/leaf#6370).

Repro files

worker.ts

// Reproduce a reused container connection that the container closed at its keep-alive
// timeout: open `width` concurrent requests so the runtime pools that many connections,
// leave them idle for `gap` ms, then send `width` concurrent requests again.
import { Container } from "@cloudflare/containers";

export class Repro extends Container {
  defaultPort = 8080;
  sleepAfter = "10m";

  async run(gaps: number[], trials: number, width: number): Promise<unknown> {
    const once = async () => {
      const response = await this.containerFetch("http://container/ping", 8080);
      const body = await response.text();
      return response.status === 200 ? "ok" : body.slice(0, 80);
    };
    const burst = () => Promise.all(Array.from({ length: width }, once));
    await burst();
    const results: Record<string, Record<string, number>> = {};
    for (const gap of gaps) {
      const counts: Record<string, number> = {};
      for (let i = 0; i < trials; i++) {
        await burst();
        await new Promise((resolve) => setTimeout(resolve, gap));
        for (const outcome of await burst()) counts[outcome] = (counts[outcome] ?? 0) + 1;
      }
      results[String(gap)] = counts;
    }
    return results;
  }
}

interface Env {
  REPRO: DurableObjectNamespace<Repro>;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const gaps = (url.searchParams.get("gaps") ?? "4000,4950,5000,5050,6000").split(",").map(Number);
    const trials = Number(url.searchParams.get("trials") ?? "5");
    const width = Number(url.searchParams.get("width") ?? "3");
    const stub = env.REPRO.get(env.REPRO.idFromName(url.searchParams.get("name") ?? "repro"));
    return Response.json(await stub.run(gaps, trials, width));
  },
};

server.py

"""A container HTTP server that answers every request, with a configurable keep-alive."""

import os

import uvicorn


async def app(scope, receive, send):
    if scope["type"] != "http":
        return
    while (await receive()).get("more_body"):
        pass
    await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": b"ok"})


uvicorn.run(
    app,
    host="0.0.0.0",
    port=8080,
    log_level="warning",
    timeout_keep_alive=int(os.environ.get("KEEP_ALIVE", "5")),
)

Dockerfile (built with KEEP_ALIVE=5 and 75)

FROM ghcr.io/astral-sh/uv:python3.14-bookworm-slim
RUN uv pip install --system uvicorn==0.54.0
COPY server.py /server.py
ARG KEEP_ALIVE=75
ENV KEEP_ALIVE=${KEEP_ALIVE}
EXPOSE 8080
CMD ["python", "/server.py"]

wrangler.toml

name = "keepalive-repro"
main = "worker.ts"
compatibility_date = "2026-09-01"

[dev]
port = 8799
inspector_port = 0

[[containers]]
class_name = "Repro"
image = "./Dockerfile"
max_instances = 2

[[durable_objects.bindings]]
name = "REPRO"
class_name = "Repro"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["Repro"]

Run wrangler dev, then request localhost:8799/?gaps=4995,5000,5005&trials=14; the response counts each outcome per gap.

This was written by Claude Code on behalf of max-sixty

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions