Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke-RestMethod hangs on long running endpoints

We are using Invoke-RestMethod in a PowerShell script to call a GET method endpoint with a variable length runtime. Some calls may return after a couple of seconds, some may take up to 20 minutes. We've set a 50 minute timeout on the call via the -TimeoutSec parameter.

Calls that take only a couple of seconds return fine and output the expected response. Longer calls (5 minutes, for example) never return and the Invoke-RestMethod command uses up the entire 50 minutes timeout, despite us confirming on the web server logs that the server has long since returned a 200 OK.

try 
{
    $Url = "https://example.com/task"   # GET
    $Timeout = 3000                     # 50 minute timout
    $Response = Invoke-RestMethod $Url -TimeoutSec $Timeout
        
    Write-Host $Response
}
catch 
{
    Write-Host $_.Exception
}

There is no authentication on the endpoint. The PowerShell version is 7. The script is being ran on the same machine hosting the web server being called.

Is this a configuration issue with Invoke-RestMethod that we are not aware of? We had similar issues with Invoke-WebRequest using essentially the same script.

like image 845
Ryan B Avatar asked May 18 '21 17:05

Ryan B


1 Answers

We were able to resolve this problem by adding the -DisableKeepAlive switch to the Invoke-RestMethod command. It seems the HTTP keep-alive feature prevented PowerShell from concluding those long running calls.

like image 156
Ryan B Avatar answered Sep 20 '22 06:09

Ryan B