GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — `fetch` may try to use a closed connection · Issue #3492 · nodejs/undici

fetch may try to use a closed connection #3492

New issue
Copy link
New issue
Copy link
Closed
Closed
fetch may try to use a closed connection#3492
Copy link
Labels
bugSomething isn't workingfetch

Description

@robhogan
robhogan
opened on Aug 21, 2024
Issue body actions

Version

v22.6.0

Platform

Darwin MacBook-Pro-6.local 23.5.0 Darwin Kernel Version 23.5.0: Wed May  1 20:12:58 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6000 arm64

Subsystem

http

What steps will reproduce the bug?

// fetch-test.js
const {createServer} = require('node:http');

const port = 8080;
const url = 'http://localhost:' + port;

const server = createServer((req, res) => res.end()).listen(port, async () => {
  await fetch(url);
  server.closeIdleConnections();

  setImmediate(async () => {
    await fetch(url); // Throws TypeError with cause UND_ERR_SOCKET or ECONNRESET
    server.close();
  });
});

How often does it reproduce? Is there a required condition?

Reproduces consistently for me but the error cause varies roughly evenly between ECONNRESET and UND_ERR_SOCKET (details below)

What is the expected behavior? Why is that the expected behavior?

fetch creates a new connection if there are none open, and the request succeeds.

What do you see instead?

node fetch-test.js
node:internal/deps/undici/undici:13178
      Error.captureStackTrace(err);
            ^

TypeError: fetch failed
    at node:internal/deps/undici/undici:13178:13
    at async Immediate.<anonymous> (/Users/robhogan/workspace/fetch-test.js:11:5) {
  [cause]: SocketError: other side closed
      at Socket.<anonymous> (node:internal/deps/undici/undici:6020:28)
      at Socket.emit (node:events:532:35)
      at endReadableNT (node:internal/streams/readable:1696:12)
      at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
    code: 'UND_ERR_SOCKET',
    socket: {
      localAddress: '::1',
      localPort: 57996,
      remoteAddress: undefined,
      remotePort: undefined,
      remoteFamily: undefined,
      timeout: undefined,
      bytesWritten: 338,
      bytesRead: 122
    }
  }
}

Node.js v22.6.0

OR

node fetch-test.js
node:internal/deps/undici/undici:13178
      Error.captureStackTrace(err);
            ^

TypeError: fetch failed
    at node:internal/deps/undici/undici:13178:13
    at async Immediate.<anonymous> (/Users/robhogan/workspace/fetch-test.js:11:5) {
  [cause]: Error: read ECONNRESET
      at TCP.onStreamRead (node:internal/stream_base_commons:218:20) {
    errno: -54,
    code: 'ECONNRESET',
    syscall: 'read'
  }
}

Node.js v22.6.0

Additional information

This seems to be quite sensitive to timing/the event loop in a way I haven't pinned down.

  • The setImmediate (or setTimeout(cb, 0)) is required to reproduce the issue.
  • Adding another setImmediate before the second fetch makes it succeed.
  • Adding {headers:{'Connection': 'close'}} to the first request succeeds.
Reacted by Vitali Zaidman, Toni Villena, naourass, Joey Mezzacappa, Daniel Tompkins, Girish Ramakrishnan, Eli Black, Nathan Villagaray-Carski, Josep Viciana, Electro Type and 13 more

Activity

Next
  1. avivkeller
    added
    fetch
    on Aug 21, 2024
  2. avivkeller commented on Aug 21, 2024

    @avivkeller
    avivkeller
    on Aug 21, 2024
    Member
    More actions
    const {createServer} = require('node:http');
    
    const port = 8080;
    const url = 'http://localhost:' + port;
    
    const server = createServer((req, res) => res.end()).listen(port, async () => {
      await fetch(url);
      server.closeIdleConnections();
    
      setImmediate(async () => {
        await fetch(url); // Throws TypeError with cause UND_ERR_SOCKET or ECONNRESET
        server.close();
      });
    });
    $ node repro.js
    node:internal/deps/undici/undici:13178
          Error.captureStackTrace(err);
                ^
    
    TypeError: fetch failed
        at node:internal/deps/undici/undici:13178:13
        at async Immediate.<anonymous> (/repro.js:12:5) {
      [cause]: Error: read ECONNRESET
          at TCP.onStreamRead (node:internal/stream_base_commons:218:20) {
        errno: -54,
        code: 'ECONNRESET',
        syscall: 'read'
      }
    }
    
    Node.js v22.6.0
    
  3. vzaidman
    added a commit that references this issue on Aug 21, 2024

    updated node-fetch (#1327)

    fcdefe8
  4. facebook-github-bot
    added a commit that references this issue on Aug 21, 2024

    updated node-fetch (#1327)

    60de111
  5. KhafraDev
    transferred this issue fromnodejs/nodeon Aug 22, 2024
  6. Uzlopak commented on Aug 22, 2024

    @Uzlopak
    Uzlopak
    on Aug 22, 2024
    Contributor
    More actions

    If I put following line in setImmediate then it works as expected, but other tests fail

    undici/lib/dispatcher/client.js

    Line 292 in 69cfd97

    this[kResume](true)

  7. jazelly commented on Aug 22, 2024

    @jazelly
    jazelly
    on Aug 22, 2024
    Member
    More actions

    I don't think this is an undici specific issue, as same thing would happen by using native http.request in node with keepAlive.

    This seems to be an limitation with keepAlive implementation. The second request is assigned to the socket that is about to destroy, as it is not aware of that.

    Reacted by Rob Hogan, jakecastelli, Eli Black, K0 and Matt Fozard
  8. jakecastelli commented on Aug 22, 2024

    @jakecastelli
    jakecastelli
    on Aug 22, 2024
    Member
    More actions

    To extend @jazelly's point - here is a small repo with node:http

    // fetch-test.js
    import { createServer, request } from "node:http";
    
    const port = 8084;
    const url = new URL("http://localhost:" + port);
    
    const server = createServer((req, res) => res.end()).listen(port, async () => {
      function httpRequestPromise(reqOptions) {
        return new Promise((resolve, reject) => {
          const req = request(reqOptions, (res) => {
            console.log(`STATUS: ${res.statusCode}`);
            res.setEncoding("utf8");
            res.on("data", () => {});
            res.on("end", () => {
              resolve();
            });
          });
    
          req.on("error", (error) => {
            console.error(`Request error: ${error.message}`);
            reject(error);
          });
          req.end();
        });
      }
    
      await httpRequestPromise({
        headers: {
          // 'Content-Type': 'application/json',
          Connection: "keep-alive",
        },
        hostname: url.hostname,
        port: url.port,
        path: url.pathname,
      });
    
      server.closeIdleConnections();
      console.log("idle connections should have closed...");
    
      setImmediate(async () => {
        await httpRequestPromise({
          hostname: url.hostname,
          port: url.port,
          path: url.pathname,
        });
        server.close();
      });
    });

    when run this you should see:

    idle connections should have closed...
    Request error: read ECONNRESET
    node:internal/process/promises:394
        triggerUncaughtException(err, true /* fromPromise */);
        ^
    
    Error: read ECONNRESET
        at TCP.onStreamRead (node:internal/stream_base_commons:218:20) {
      errno: -54,
      code: 'ECONNRESET',
      syscall: 'read'
    }
    

    or

    idle connections should have closed...
    Request error: socket hang up
    node:_http_client:530
        emitErrorEvent(req, new ConnResetException('socket hang up'));
                            ^
    
    Error: socket hang up
        at Socket.socketOnEnd (node:_http_client:530:25)
        at Socket.emit (node:events:532:35)
        at endReadableNT (node:internal/streams/readable:1696:12)
        at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
      code: 'ECONNRESET'
    }
    

    if we have NODE_DEBUG=net then we can see:

    Details
    NET 49784: setupListenHandle null 8084 4 0 undefined
    NET 49784: setupListenHandle: create a handle
    NET 49784: bind to ::
    NET 49784: createConnection [
      [Object: null prototype] {
        headers: { Connection: 'keep-alive' },
        hostname: 'localhost',
        port: '8084',
        path: null,
        host: 'localhost',
        keepAlive: true,
        scheduling: 'lifo',
        timeout: 5000,
        noDelay: true,
        servername: 'localhost',
        _agentKey: 'localhost:8084:',
        encoding: null,
        keepAliveInitialDelay: 1000
      },
      [Function (anonymous)],
      [Symbol(normalizedArgs)]: true
    ]
    NET 49784: pipe false null
    NET 49784: connect: find host localhost
    NET 49784: connect: dns options { family: undefined, hints: 1024 }
    NET 49784: connect: autodetecting
    NET 49784: _read - n 16384 isConnecting? true hasHandle? true
    NET 49784: _read wait for connection
    NET 49784: connect/multiple: only one address found, switching back to single connection
    NET 49784: connect: attempting to connect to 127.0.0.1:8084 (addressType: 4)
    NET 49784: afterConnect
    NET 49784: _read - n 16384 isConnecting? false hasHandle? true
    NET 49784: Socket._handle.readStart
    NET 49784: onconnection
    NET 49784: _read - n 16384 isConnecting? false hasHandle? true
    NET 49784: Socket._handle.readStart
    STATUS: 200
    NET 49784: _read - n 16384 isConnecting? false hasHandle? true
    NET 49784: destroy
    NET 49784: close
    NET 49784: close handle
    NET 49784: has server
    NET 49784: SERVER _emitCloseIfDrained
    NET 49784: SERVER handle? true   connections? 0
    idle connections should have closed...
    NET 49784: emit close
    NET 49784: destroy
    NET 49784: close
    NET 49784: close handle
    Request error: read ECONNRESET
    node:internal/process/promises:391
        triggerUncaughtException(err, true /* fromPromise */);
        ^
    
    Error: read ECONNRESET
        at TCP.onStreamRead (node:internal/stream_base_commons:218:20) {
      errno: -54,
      code: 'ECONNRESET',
      syscall: 'read'
    }
    

    Close event was emitted after closeIdleConnections

    NET 39667: SERVER _emitCloseIfDrained
    NET 39667: SERVER handle? true   connections? 0
    idle connections should have closed...  <------------- this is the console log after closeIdleConnections
    NET 39667: emit close
    NET 39667: destroy
    NET 39667: close
    NET 39667: close handle
    
    Reacted by Jason Zhang and Eli Black
  9. KhafraDev commented on Aug 22, 2024

    @KhafraDev
    KhafraDev
    on Aug 22, 2024
    Member
    More actions

    @nodejs/http

  10. mcollina commented on Aug 23, 2024

    @mcollina
    mcollina
    on Aug 23, 2024
    SponsorMember
    More actions

    There are is only one thing to do: always retry the request if the other side is closed. This would mean configuring the retry interceptor by default for fetch also for POST etc in case of a network error.

    Reacted by Carlos Fuentes
  11. Uzlopak
    added
    bugSomething isn't working
    on Aug 25, 2024
  12. neoncube2 commented on Apr 30, 2025

    @neoncube2
    neoncube2
    on Apr 30, 2025
    More actions

    If this issue isn't specific to undici, is there a better place to file this issue?

    Reacted by José Hidalgo Espinel
    Reacted by Toni Villena, José Hidalgo Espinel, Hayato Mizuno and David
  13. takefy-dev commented on May 8, 2025

    @takefy-dev
    takefy-dev
    on May 8, 2025
    More actions

    Hey got the same error i don't know why... is anyone as a a fix?

    Reacted by Erik Terpstra, Cole Corrente, Nicolas, David and times29
  14. RasmusKard commented on Jul 14, 2025

    @RasmusKard
    RasmusKard
    on Jul 14, 2025
    More actions

    This should be relevant nodejs/node#52649

    Fix to reduce likelyhood of the race condition happening is released in V23 nodejs/node@05ad947

    Reacted by Eli Black and Luke Parker
  15. tefkah
    added a commit that references this issue on Jul 21, 2025

    fix: use higher node version to maybe get around obscure race condition

    52e31f7
  16. 6 remaining items

  17. dvl-zeniark
    added 2 commits that reference this issue on Aug 14, 2026

    Replace Next.js quickstart with Astro

    948294b

    Replace Next.js quickstart with Astro

    50841dc
  18. Maher-Reven commented on Sep 24, 2026

    @Maher-Reven
    Maher-Reven
    on Sep 24, 2026
    More actions

    I ran the reporter's repro unchanged across released versions to see where this stands, and the result is more specific than "fixed": the pass rate tracks the scheduling of idle socket validation, including a regression that was introduced and then fixed again inside the 8.10 line.

    Method

    The script from the first post, with only two changes: port 0 instead of 8080 so runs cannot collide, and the second fetch result printed rather than thrown. Each row is N fresh processes, one request pair each, on Node 24.19.0 / macOS 26.5.2 / arm64.

    Results

    undici pass failures
    6.19.8 0/20 ECONNRESET, some UND_ERR_SOCKET
    6.21.3 0/20 same
    7.0.0 → 7.27.0 0/20 each same
    7.27.2 0/100 96 ECONNRESET, 4 UND_ERR_SOCKET
    7.28.0 95/100 5 UND_ERR_SOCKET
    8.0.0 96/100 4 UND_ERR_SOCKET
    8.5.0 94/100 1 ECONNRESET, 5 UND_ERR_SOCKET
    8.6.0 93/100 7 UND_ERR_SOCKET
    8.7.0 95/100 5 UND_ERR_SOCKET
    8.8.0 100/100 —
    8.9.0 200/200 —
    8.10.0 194/200 6 UND_ERR_SOCKET
    8.10.1 200/200 —
    8.10.2 100/100 —
    8.11.2 300/300 —

    So: a deterministic failure through 7.27.2, a roughly 5% race from 7.28.0 through 8.7.0, clean at 8.8.0, back to about 3% at 8.10.0, and clean again from 8.10.1.

    The pattern lines up with idle socket validation

    Those three transitions sit exactly on the three commits that moved when an idle socket is validated:

    first released in commit
    8.8.0 ecf714f8 run idle socket validation off setImmediate instead of setTimeout (#5499)
    8.10.0 c76fe46e revert idle socket validation to setTimeout(0) to prevent stall on idle event loop (#5606)
    8.10.1 8c9182eb drop idle-socket timer floor with a ref'd setImmediate (#5707)

    That is what you would expect from this repro in particular. The second fetch is scheduled inside setImmediate, so it runs in the check phase — after a validation scheduled with setImmediate, but before one scheduled with setTimeout(0). When validation lands in the later phase, the request is handed a socket the server has already closed.

    Worth saying plainly: this is a correlation across released versions, not a git bisect over commits, and I did not read the validation path closely enough to claim causation. But the 8.10.0 dip is not noise — 8.9.0 and 8.10.1 are 200/200 either side of it, and it is the only one of the three releases in that window that carries the setTimeout(0) revert.

    Node's bundled copy

    Node 20.20.2 ships undici 6.24.1 and fails 10/10, which is consistent with the table. Node 20 is out of support, and Node 24.19.0 ships 7.29.0, which is past the deterministic failure but still inside the residual-race band rather than the clean one.

    What this does not cover

    Single machine, macOS arm64, loopback only. A race this narrow is scheduler-sensitive, so the percentages will move on other hardware even if the ordering does not. I did not test Windows or Linux, HTTP/2, or a proxied agent.

    On current undici this looks closable. The reason I am posting the whole table rather than just "cannot reproduce on latest" is the 8.10.0 row — if anything is being backported into that line, the setTimeout(0) revert is the thing to keep an eye on.

    Reacted by ayame113 (val440)
  19. 61465 commented on Oct 15, 2026

    @61465
    61465
    on Oct 15, 2026
    More actions

    Picking this up. undici is very active (@mcollina shipped 5 commits yesterday, v8.12.2 today) and the retry infrastructure (lib/handler/retry-handler.js) already defaults to ['ECONNRESET', ..., 'UND_ERR_SOCKET'] in its errorCodes list — there's just no wire from fetch init to RetryHandler.

    @mcollina — your 2024-08-23 call was "always retry the request if the other side is closed... configuring the retry interceptor by default for fetch also for POST etc in case of a network error." Two shapes before I touch code:

    Shape A — opt-in via init.retry:

    fetch(url, { retry: true })                              // defaults
    fetch(url, { retry: { maxRetries: 3, maxTimeout: 10000 } })
    fetch(url, { retry: false })                             // explicit opt-out

    Backward compatible, fetch keeps no-retry default. Documented alongside dispatcher, duplex. ~400 LOC + tests + docs + types.

    Shape B — default retry on connection-closed errors (your original ask):
    Fetch wraps dispatch with RetryHandler constrained to pre-response-byte network errors (UND_ERR_SOCKET, UND_ERR_CONNECT_TIMEOUT, ECONNRESET before any response bytes). Idempotency-safe because the error class fires only when the server received zero bytes. Transient errors that used to throw would now succeed — most users would read it as the fix. ~500 LOC + migration note.

    Both share the same core wire-up; difference is default-on vs default-off.

    My lean is A first, land it, flip to B once A has baked for a release or two. You know the user base — would you rather I go straight to B? Happy either way; just want to pick the shape before diving in.

  20. mcollina commented on Oct 16, 2026

    @mcollina
    mcollina
    on Oct 16, 2026
    SponsorMember
    More actions

    This is fixed. The race was closed by idle socket validation on keep-alive reuse, with the final piece being the ref'd setImmediate in #5707 (v8.10.1), backported to v7.x in #5769 (v7.29.1). The repro from the first post passes 200/200 on both main and v7.x today, and an HTTP/2 variant passes as well.

    Node 24 will pick this up via the bundled undici bump to 7.30.1 in nodejs/node#66764.

    Retrying on connection errors inside fetch is a separate feature discussion; please open a dedicated issue if you want to pursue it.

    Reacted by Josep Viciana, Rasmus Kard, Rob Hogan and Vitali Zaidman
  21. mcollina
    closed this as completedon Oct 16, 2026
  22. 61465 commented on Oct 16, 2026

    @61465
    61465
    on Oct 16, 2026
    More actions

    Thanks @mcollina — understood. Opening a dedicated feature issue for the opt-in retry option; will link #6030 there as the proposed implementation.

  23. robinchoice
    added a commit that references this issue on Oct 20, 2026

    fix: isolate check daemons from the service AppImage watcher

    c1f0fbc
  24. decolua
    added a commit that references this issue on Nov 8, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    736be95
  25. yheiakadylan
    added a commit that references this issue on Nov 9, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    0be6092
  26. lydx9876
    added a commit that references this issue on Nov 9, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    2140c77
  27. thunderkex
    added a commit that references this issue on Nov 9, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    689cc72
  28. purujawa06-bot
    added a commit that references this issue on Nov 10, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    ffc814d
  29. JinzoU-MwM
    added a commit that references this issue on Nov 18, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    fc1df38
  30. Azhar457
    added a commit that references this issue on Nov 20, 2026

    fix(transport): survive DPI-shaped networks on the claude provider

    6090e84
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

    bugSomething isn't workingfetch

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402792 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.