Skip to content

[Bug]: APIRequestContext reuses idle sockets past the server's Keep-Alive timeout and fails with read ECONNRESET #44007

Closed

Description

Version

1.65.0. It also reproduces on 1.64.1, and main has the same agent code.

Steps to reproduce

An APIRequestContext request sent about 6 s after the previous response fails with read ECONNRESET when the server is a Node.js HTTP server with default keep-alive settings and its event loop is busy around that moment. This is the bug reported in #42698, which was closed with a request to retest on a newer version. It still reproduces on 1.65.0, on every run, with no proxy, framework, or browser.

  1. Run npm init -y && npm i playwright-core@1.65.0.
  2. Save server.mjs and client.mjs from below.
  3. Run node server.mjs in one terminal.
  4. Run node client.mjs in another.

server.mjs uses Node's default HTTP server settings. It adds one 400 ms event-loop stall, timed to cover the server's idle deadline, to stand in for a busy server such as next dev compiling a route.

// server.mjs
import http from "node:http";

let requests = 0;
const server = http.createServer((req, res) => {
	console.log(`handler ran for request ${++requests}`);
	res.on("finish", () => {
		req.socket.lastResponseAt = Date.now();
		// Simulate a busy server (for example, `next dev` compiling a route) right
		// before the 6 s idle deadline. The stall runs in the check phase, so the
		// event loop reaches its next timers phase after the deadline and before
		// the poll phase reads the client's next request.
		setTimeout(
			() =>
				setImmediate(() => {
					const until = Date.now() + 400;
					while (Date.now() < until) {}
				}),
			5800,
		);
	});
	res.end("ok");
});
server.on("connection", (socket) => {
	socket.on("close", () =>
		console.log(`connection closed ${Date.now() - socket.lastResponseAt} ms after its last response`),
	);
});
server.listen(3123, "127.0.0.1", () => console.log("listening on http://127.0.0.1:3123"));

client.mjs sends two requests on one context, 5.97 s apart. --retry adds maxRetries: 1. --agent-timeout previews the fix proposed below by giving Playwright's agents a 5000 ms timeout before Playwright loads.

// client.mjs
import http from "node:http";
import { setTimeout as sleep } from "node:timers/promises";

const mode = process.argv[2];
if (mode === "--agent-timeout") {
	// Preview the proposed fix: give Playwright's agents the timeout that
	// Node's http.globalAgent uses.
	const { Agent } = http;
	http.Agent = function AgentWithTimeout(options) {
		return new Agent({ timeout: 5000, ...options });
	};
	http.Agent.prototype = Agent.prototype;
}
const { request } = await import("playwright-core");
const options = mode === "--retry" ? { maxRetries: 1 } : {};

const ctx = await request.newContext({ baseURL: "http://127.0.0.1:3123" });
console.log("first:", (await ctx.get("/", options)).status());
await sleep(5970);
try {
	console.log("second:", (await ctx.get("/", options)).status());
} catch (error) {
	console.log("second:", error.message.split("\n")[0]);
}
await ctx.dispose();

Expected behavior

The second request succeeds. Every response carries Keep-Alive: timeout=5, so the client should stop reusing the idle socket before the server closes it. Node's own http.globalAgent does this. It closes the idle socket about 4 s after the response, which is the 5 s hint minus Node's 1 s client buffer, and the second request opens a new connection.

Actual behavior

The second request fails, and the server's handler never runs for it:

$ node client.mjs
first: 200
second: apiRequestContext.get: read ECONNRESET
listening on http://127.0.0.1:3123
handler ran for request 1
connection closed 6200 ms after its last response

This failed on 8 of 8 runs across 1.64.1 and 1.65.0.

With --retry, the retry opens a new connection, and the handler runs once for it:

$ node client.mjs --retry
first: 200
second: 200
listening on http://127.0.0.1:3123
handler ran for request 1
connection closed 6204 ms after its last response
handler ran for request 2
connection closed 1 ms after its last response

With --agent-timeout, the client closes the idle socket at 4 s, before the server's deadline, and the second request succeeds without a retry:

$ node client.mjs --agent-timeout
first: 200
second: 200
listening on http://127.0.0.1:3123
handler ran for request 1
connection closed 4003 ms after its last response
handler ran for request 2
connection closed 2 ms after its last response

Additional context

Root cause

APIRequestContext._ensureAgent creates its agents without a timeout (fetch.ts#L174-L183):

// Aligned with the default Node.js global agent options. Connection options such as
// `lookup` stay per-request, since agent options take precedence over request ones.
agent = protocol === 'https:' ? new https.Agent({ keepAlive: true }) : new http.Agent({ keepAlive: true });

Node's Agent.prototype.keepSocketAlive applies the server's Keep-Alive: timeout=N hint only when the hint is lower than a timeout the agent already has (_http_agent.js#L633-L667):

let agentTimeout = this.options.timeout || 0;
// ...
} else if (serverHintTimeout < agentTimeout) {
  agentTimeout = serverHintTimeout;
}

With no agent timeout, agentTimeout is 0, so the hint never applies, and the idle socket stays in the pool until the server closes it. Node's http.globalAgent, which the comment above says Playwright aligns with, is created with timeout: 5000 (internal/http.js#L263-L268), so it does honor the hint.

On the server side, Node 24 sets an idle socket's timer to keepAliveTimeout + keepAliveTimeoutBuffer, 5000 + 1000 ms, when a response finishes (_http_server.js#L1130-L1142). The timer is cleared only when the parser reads the next request (L1167-L1168). If the event loop is busy across the deadline, its next timers phase runs before the poll phase reads the request that is already waiting in the socket buffer. socketOnTimeout then destroys the socket (L900-L909), and the client gets a reset.

The client sent its request at 5.97 s, before the server's 6 s deadline. A client that honors the 5 s hint never gets that close, because it drops the socket at 4 s.

Impact

We hit this in Better Auth's end-to-end suite, which drives a Next.js app under next dev with APIRequestContext (better-auth/better-auth#12354). On slow CI runners, a request sent 5.97 s after the previous response on the same context failed with read ECONNRESET, and the trace showed the reset 78 ms later.

The workaround is maxRetries: 1 on every request. Playwright retries only ECONNRESET (fetch.ts#L300-L326), and the reset request never reached the handler, so the retry is safe here. There is no context-level default, though, so every call site needs the option. A blanket retry is also riskier for a non-idempotent request whose connection resets after the handler ran.

Proposed fix

Give the keep-alive agents a timeout:

const agentOptions = { keepAlive: true, timeout: 5000 };
agent = protocol === 'https:' ? new https.Agent(agentOptions) : new http.Agent(agentOptions);

A 5000 ms timeout matches http.globalAgent, which makes the existing comment accurate. Node then applies any smaller server hint, so against a default Node server the idle socket closes at about 4 s, as --agent-timeout shows. #42720 proposed timeout: 60_000, which also fixes this case, because the 4 s hint is smaller. With 5000 ms, idle sockets are also retired on servers that send no hint, as globalAgent does.

The timeout does not cut off slow responses. Node destroys a socket on agent timeout only while the socket sits idle in the agent's free pool. With the --agent-timeout patch applied, a response that waits 7 s before its headers and 7 s more before its body still returns 200 after 14 s.

A Node-side fix is also open. nodejs/node#66734 reports the same agent behavior, and nodejs/node#66779 would apply the hint when an agent has no timeout. That fix would reach Playwright users only on Node releases that include it, so the Playwright change still helps on current LTS lines.

Related

Environment

System:
  OS: Linux 7.0 Ubuntu 26.04.1 LTS 26.04.1 LTS (Resolute Raccoon)
  CPU: (32) x64 AMD Ryzen 9 9950X 16-Core Processor
  Memory: 96.10 GB / 125.40 GB
  Container: Yes
Binaries:
  Node: 24.22.0 - /usr/bin/node
  Yarn: 1.22.22 - /usr/bin/yarn
  npm: 12.2.1 - /usr/bin/npm
  pnpm: 11.28.6 - ~/.local/bin/pnpm
  bun: 1.3.14 - ~/.local/bin/bun
Languages:
  Bash: 5.3.9 - /usr/bin/bash
npmPackages:
  playwright-core: 1.65.0 => 1.65.0

Activity

  1. github-actions commented on Nov 9, 2026

    @github-actions
    Contributor

    Hi, I'm the Playwright bot. I started to triage this issue on Linux: agent run

  2. github-actions commented on Nov 10, 2026

    @github-actions
  3. microsoft-playwright-automation commented on Nov 10, 2026

    @microsoft-playwright-automation
    Contributor

    Hi, I'm the Playwright bot. I checked the idle connection handling.

    Reproduced the missing idle-socket retirement on Linux, using Node 24.22.2 and main e9d68919607ad347765f2f4aeafcc8046c8d0990 (1.66.0-next). Without an agent timeout, the connection stays open beyond the server's advertised keep-alive timeout. The proposed fix gives both HTTP and HTTPS agents the same 5-second timeout as Node's global agents, so Node can apply a shorter server hint. Request retries are unchanged.

    Reduced check and results

    I extended the existing FE-020 should return server address from response test:

    server.setRoute('/idle', (req, res) => {
      res.on('finish', () => req.socket.setTimeout(30_000));
      res.setHeader('Keep-Alive', 'timeout=2');
      res.end('ok');
    });
    const [serverRequest] = await Promise.all([
      server.waitForRequest('/idle'),
      request.get(server.PREFIX + '/idle'),
    ]);
    await expect.poll(() => serverRequest.socket.destroyed, { timeout: 7000 }).toBe(true);

    The server deliberately keeps its side open, so the check measures client retirement rather than server closure. This failed on all four attempts without the fix and passed with it. It checks the underlying socket lifetime; I did not repeat the separate-process, 5.97-second reset race.

    • Chromium, Firefox and WebKit library projects: global-fetch.spec.ts and browsercontext-fetch.spec.ts passed, with 613 passed and 2 skipped. The new check passed in all three projects; the request transport itself is browser-independent.
    • A separate HTTP check delayed headers for 6 seconds and the body for another 6 seconds: status 200 and the complete body after 12 seconds. The agent timeout did not interrupt the active response.
    • npm run build and npm run flint passed.

    No published versions or headed variations were needed for this browser-independent failure on main. The earlier proposed fix, #42720, is closed without a merge.

    Draft PR: #44024

    Triaged on Linux by the Playwright bot - agent run

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