Skip to content

Keep-Alive max parameter prevents connection reuse #5022

@BrainTR

Description

@BrainTR

Bug Description

When the server has a request limit per connection via the Keep-Alive max parameter, Undici reuses the initial connection until the limit is reached.
After the limit is reached, the server sends a "Connection: close" header, and Undici closes the connection.
In subsequent requests, despite the "Connection: Keep-Alive" header, Undici closes the connection.

Reproducible By

import { request, Agent } from 'undici';

const dispatcher = new Agent({ connections: 1 });

async function testRequest(id) {
    const url = 'https://tgftp.nws.noaa.gov/testfile';
    const { body, headers } = await request(url, { dispatcher });
    await body.dump();
    console.log({
        id,
        connection: headers['connection'],
        keepAlive: headers['keep-alive'],
    });
}

async function run() {
    for (let id = 1; id <= 110; id++) {
        await testRequest(id);
    }
}

run();

Expected Behavior

Undici should reuse connections when possible.

Logs

{ id: 1, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=100' } // new connection
{ id: 2, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=99' } // reused connection
{ id: 3, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=98' } // reused connection
{ id: 4, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=97' } // reused connection
...
{ id: 99, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=2' } // reused connection
{ id: 100, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=1' } // reused connection
{ id: 101, connection: 'close', keepAlive: undefined } // reused connection
{ id: 102, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=100' } // new connection
{ id: 103, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=100' } // new connection
{ id: 104, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=100' } // new connection
{ id: 105, connection: 'Keep-Alive', keepAlive: 'timeout=300, max=100' } // new connection
...

Environment

  • Node.js: v24.14.0 (undici 8.0.1)
  • Platform: Ubuntu 24.04.4 LTS

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions