Invoke-RestMethod hangs on long running endpoints
Asked Answered
B

1

9

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.

Bryology answered 18/5, 2021 at 17:10 Comment(2)
This might be related to a lower layer (unrelated to PowerShell). A firewall, for example, uses statefull inspection to open ports for a connection so that the answers can pass through. The ports won't be open forever. They will be closed, as soon as the connection gets closed, or, and that might be the case here, after a timeout. Invoke-WebRequest can for sure not modify such a timeout. And there might be even more services with a similar timeout mechanism.Khz
I am having same issue, but even -DisableKeepAlive also not working. I am calling a nodejs api which runs for around 20 mins. I want to get the response of it and based on that respond to ABJob. Any ideas will be helpfulLentic
B
3

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.

Bryology answered 24/5, 2021 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.