Title: http: aborting a keep-alive response during async iteration emits an unhandled Socket error · Issue #65938 · nodejs/node · GitHub
Open Graph Title: http: aborting a keep-alive response during async iteration emits an unhandled Socket error · Issue #65938 · nodejs/node
X Title: http: aborting a keep-alive response during async iteration emits an unhandled Socket error · Issue #65938 · nodejs/node
Description: Version Reproduced with the standalone script below on: Node version Independent runs Unhandled Socket error / exit 1 v24.19.0 20 20 v24.21.0 20 20 v26.3.0 20 20 v26.8.1 20 20 As of the preparation date, v24.21.0 is the latest LTS releas...
Open Graph Description: Version Reproduced with the standalone script below on: Node version Independent runs Unhandled Socket error / exit 1 v24.19.0 20 20 v24.21.0 20 20 v26.3.0 20 20 v26.8.1 20 20 As of the preparation...
X Description: Version Reproduced with the standalone script below on: Node version Independent runs Unhandled Socket error / exit 1 v24.19.0 20 20 v24.21.0 20 20 v26.3.0 20 20 v26.8.1 20 20 As of the preparation...
Opengraph URL: https://github.com/nodejs/node/issues/65938
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"http: aborting a keep-alive response during async iteration emits an unhandled Socket error","articleBody":"## Version\n\nReproduced with the standalone script below on:\n\n| Node version | Independent runs | Unhandled Socket error / exit 1 |\n| ------------ | ---------------: | ------------------------------: |\n| v24.19.0 | 20 | 20 |\n| v24.21.0 | 20 | 20 |\n| v26.3.0 | 20 | 20 |\n| v26.8.1 | 20 | 20 |\n\nAs of the preparation date, v24.21.0 is the latest LTS release and v26.8.1 is\nthe latest Current release in the [official Node release index](https://nodejs.org/dist/index.json).\nThe v26.8.1 Linux x64 executable was downloaded from nodejs.org and its archive\nwas checked against the official `SHASUMS256.txt`.\n\n## Platform\n\nLinux x64 under WSL2. Output of `uname -srvmo` (hostname omitted):\n\n```text\nLinux 6.18.33.2-microsoft-standard-WSL2 #1 SMP PREEMPT_DYNAMIC Thu Jun 18 21:54:43 UTC 2026 x86_64 GNU/Linux\n```\n\nOther operating systems have not been tested. The first affected Node release\nhas not been bisected.\n\n## Subsystem\n\n`node:http`, `ClientRequest`, `IncomingMessage`, keep-alive socket lifecycle,\nand cancellation through `AbortSignal`.\n\n## What steps will reproduce the bug?\n\nSave the following as `repro.mjs` and run:\n\n```sh\nnode repro.mjs\n```\n\nThe script uses only Node built-ins, binds a local server to `127.0.0.1` on an\nephemeral port, and returns a one-byte HTTP response. It requires no packages,\nexternal services, TLS certificates, DNS customization or application code.\nBoth the request and the response have persistent `error` handlers. Async\niteration is also inside a `try/catch`. The script does not remove any error\nhandlers or install a process-wide exception handler.\n\n```js\n// Standalone upstream reproducer: only Node built-ins and a loopback HTTP server.\nimport http from \"node:http\";\nimport { once } from \"node:events\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nconst agent = new http.Agent({ keepAlive: true });\nconst server = http.createServer((_request, response) => response.end(\"x\"));\nserver.listen(0, \"127.0.0.1\");\nawait once(server, \"listening\");\n\ntry {\n const controller = new AbortController();\n const response = await new Promise((resolve, reject) => {\n const request = http.get(\n `http://127.0.0.1:${server.address().port}/`,\n { agent, signal: controller.signal },\n (incoming) => {\n incoming.on(\"error\", (error) => console.log(\"response error:\", error.code));\n resolve(incoming);\n }\n );\n request.on(\"error\", (error) => {\n console.log(\"request error:\", error.code);\n reject(error);\n });\n });\n\n try {\n for await (const chunk of response) {\n console.log(\"received bytes:\", chunk.length);\n controller.abort(new Error(\"stop reading\"));\n break;\n }\n } catch (error) {\n console.log(\"iteration error:\", error.code ?? error.message);\n }\n\n // Leave time for deferred events; a caught rejection alone proves too little.\n await delay(50);\n console.log(\"survived\");\n} finally {\n agent.destroy();\n server.closeAllConnections();\n await new Promise((resolve) => server.close(resolve));\n}\n```\n\n## How often does it reproduce? Is there a required condition?\n\nThe exact script above failed in all 80 fresh-process runs across the four\nversions in the table. Each run had a five-second external timeout; none of\nthese failures was a timeout. The process exited with code 1 and an unhandled\n`ABORT_ERR` on a `Socket`.\n\nThe trigger is cancellation from inside the response's async iteration while\nusing an agent with `keepAlive: true`. A one-byte response is sufficient. No\nsocket reuse by a second request, large response, concurrency or machine load\nis required by this reproducer.\n\nControl experiments changed one aspect of the script at a time. Each variant\nwas run ten times on **each** of v24.21.0 and v26.8.1:\n\n| Single change | Result on v24.21.0 | Result on v26.8.1 |\n| --------------------------------------- | -------------------------------- | -------------------------------- |\n| Set the agent's `keepAlive` to `false` | 10/10 exit 0, reaches `survived` | 10/10 exit 0, reaches `survived` |\n| Omit `signal` from `http.get` options | 10/10 exit 0, reaches `survived` | 10/10 exit 0, reaches `survived` |\n| Remove the `controller.abort(...)` call | 10/10 exit 0, reaches `survived` | 10/10 exit 0, reaches `survived` |\n| Remove `break`, retaining cancellation | 10/10 unhandled Socket error | 10/10 unhandled Socket error |\n\nThe last control shows that explicit early termination of the iterator is not\nrequired for this particular response. These observations describe this local\nreproducer; they do not establish all affected network timings or environments.\n\n## What is the expected behavior? Why is that the expected behavior?\n\nCancellation should be delivered through the HTTP request/response error paths\nor an iterator rejection that the application can handle. With those paths\nhandled, this script should reach `survived` and exit 0 instead of terminating\nthrough an unhandled error on the underlying socket.\n\nThe [HTTP request documentation](https://nodejs.org/docs/v24.21.0/api/http.html#httprequesturl-options-callback)\ndescribes request cancellation with an AbortSignal as request destruction and\ndocuments an error event carrying `ABORT_ERR` and the supplied cause. Here,\nhandlers are registered on both public HTTP objects, but the error escapes\nthrough their underlying socket.\n\n## What do you see instead?\n\nRepresentative output from v26.8.1; the local script path has been normalized\nto `.../repro.mjs`:\n\n```text\nreceived bytes: 1\nnode:events:505\n throw er; // Unhandled 'error' event\n ^\n\nAbortError: The operation was aborted\n at stream.\u003ccomputed>.AbortError.cause (node:internal/streams/add-abort-signal:47:22)\n at [nodejs.internal.kHybridDispatch] (node:internal/event_target:848:20)\n at AbortSignal.dispatchEvent (node:internal/event_target:789:26)\n at runAbort (node:internal/abort_controller:554:10)\n at abortSignal (node:internal/abort_controller:518:3)\n at AbortController.abort (node:internal/abort_controller:573:5)\n at file:///.../repro.mjs:31:18\n at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\nEmitted 'error' event on Socket instance at:\n at emitErrorNT (node:internal/streams/destroy:170:8)\n at emitErrorCloseNT (node:internal/streams/destroy:129:3)\n at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {\n code: 'ABORT_ERR',\n [cause]: Error: stop reading\n at file:///.../repro.mjs:31:24\n at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\n}\n\nNode.js v26.8.1\n```\n\nNeither the request handler, the response handler nor the iterator catch handles\nthis socket error. The `survived` line is absent.\n\n## Additional information\n\n### Observed lifecycle and suspected cause\n\nAdditional diagnostic instrumentation on v24.21.0 showed:\n\n1. Immediately before cancellation inside the loop, `request.destroyed` was\n `false`, `response.complete` was `true`, and `response.destroyed` was `false`.\n The socket still had `socketErrorListener` registered.\n2. After cancellation, Node removed `socketErrorListener`. A stack captured\n from the socket's `removeListener` event identified `responseKeepAlive()`\n called by `IncomingMessage.responseOnEnd()`.\n3. An observer using the public `events.errorMonitor` symbol then observed\n `ABORT_ERR` with `socket.listenerCount(\"error\") === 0`. The observer did not\n consume the error, and the process still exited 1.\n\nRelevant [v24.21.0 source](https://github.com/nodejs/node/blob/v24.21.0/lib/_http_client.js#L986)\nremoves the socket's error listener during `responseKeepAlive()` and explicitly\nnotes a gap before the deferred free notification. The request destruction path\npasses its error to the socket. These observations suggest a race between\nresponse completion/keep-alive cleanup and deferred error emission after abort.\nThis is a diagnosis hypothesis, not a bisected root cause or proposed core patch.\n\n### Application impact\n\nThis was originally found in an HTTP(S) client that aborts downloads when its\nresponse-size limit is exceeded. The application handled its ordinary request\nfailure, but a later unhandled socket error terminated the whole process.\nThe larger application reproduction also failed over HTTPS with a `TLSSocket`.\nThe standalone HTTP example above removes that application's body limit and\nshows that a large response or TLS is not necessary.\n\nThe one-line `keepAlive: false` control avoids the failure in this example, but\nchanges connection reuse. In the application, a local workaround owns abort\nhandling, rejects with the original reason, and closes the request/response\nwithout supplying an error to their `destroy()` calls. Neither observation is\npresented as the required Node.js fix.\n\n### Related issues and pull requests checked\n\nSearch and review date: **2026-09-09**. Both open and closed entries were included.\nI did not find an exact current report containing this AbortSignal/async-iteration\nreproducer. The following entries appear related, but equivalence has not been\nestablished:\n\n| Reference | State when checked | Relationship |\n| ------------------------------------------------------ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [#33434](https://github.com/nodejs/node/issues/33434) | Closed | Historical unhandled socket error after explicit `socket.destroy(error)` on Node 12. The [closing comment](https://github.com/nodejs/node/issues/33434#issuecomment-1092593268) cites the end of Node 12 releases, not a verified fix. This may share the socket-listener lifecycle gap; the new reproduction uses a request AbortSignal on supported releases. |\n| [#32851](https://github.com/nodejs/node/issues/32851) | Closed | Legacy `request.abort()` destroying a socket after a successful request. Different observed outcome from this unhandled error during response iteration. |\n| [#57360](https://github.com/nodejs/node/issues/57360) | Closed after inactivity | Uses `fetch`, `Readable.fromWeb()` and `.pipe()`, with an error on a Readable. The present example uses core HTTP objects directly and handles errors on both of them. |\n| [#64120](https://github.com/nodejs/node/issues/64120) | Closed | A `Duplex.toWeb()` adapter TypeError involving an undefined controller. The present example has no Web Streams adapter. |\n| [PR #61710](https://github.com/nodejs/node/pull/61710) | Closed | Addresses two calls to `responseKeepAlive()` through request-finish ordering. Related lifecycle area; this report has a pending abort error on a destroyed socket. |\n| [PR #65674](https://github.com/nodejs/node/pull/65674) | Open | Addresses server-side request iteration leaving an incomplete connection reusable. The present report concerns client response cancellation and process termination. |\n\nSearches included combinations of `AbortError`, `AbortController`, `keepAlive`,\n`keep-alive`, `http.request`, `IncomingMessage`, `unhandled`,\n`socketErrorListener` and `responseKeepAlive`, scoped to `repo:nodejs/node`.\nThis search is not proof that no duplicate exists. Please link or redirect this\nreport if an existing issue covers the same behavior.","author":{"url":"https://github.com/DavidOsipov","@type":"Person","name":"DavidOsipov"},"datePublished":"2026-09-09T12:06:53Z","url":"https://github.com/nodejs/node/issues/65938"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react-reconciler,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@d5750093facf |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:a840cde5-e4e2-6130-dafd-411d4fce2d36 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | C358:2B6F5F:2B8ADBB:3D5D741:6AED2687 |
| html-safe-nonce | 6103137daaee34343bf27e7777b0f0173c873b786733fe994197175c712c5928 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDMzU4OjJCNkY1RjoyQjhBREJCOjNENUQ3NDE6NkFFRDI2ODciLCJ2aXNpdG9yX2lkIjoiMzI4ODAwNzE3Mjk1NTEyMTI4NyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 5cbdd4a91dad146e4f2ece96d4183017530b265976c711b35bd62dd9b2e36537 |
| hovercard-subject-tag | issue:5399171842 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/nodejs/node/65938/issue_layout |
| twitter:image | https://opengraph.githubassets.com/d76226ce4fbd8557475cd9b1e9272c95c1eef32b54c628c23b4d201a681dfa4b/nodejs/node/issues/65938 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/d76226ce4fbd8557475cd9b1e9272c95c1eef32b54c628c23b4d201a681dfa4b/nodejs/node/issues/65938 |
| og:image:alt | Version Reproduced with the standalone script below on: Node version Independent runs Unhandled Socket error / exit 1 v24.19.0 20 20 v24.21.0 20 20 v26.3.0 20 20 v26.8.1 20 20 As of the preparation... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | DavidOsipov |
| hostname | github.com |
| expected-hostname | github.com |
| None | 9d95365dda0576efe9b71f45807595e396bd0ca9286fba5367a05048e6ddf8f2 |
| turbo-cache-control | no-preview |
| go-import | github.com/nodejs/node git https://github.com/nodejs/node.git |
| octolytics-dimension-user_id | 9950313 |
| octolytics-dimension-user_login | nodejs |
| octolytics-dimension-repository_id | 27193779 |
| octolytics-dimension-repository_nwo | nodejs/node |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 27193779 |
| octolytics-dimension-repository_network_root_nwo | nodejs/node |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 98b41fa4b5635ceb45a4c54320fced73817ff290 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width