Repository navigation
Description
Summary
RetryHandler retries any request whose body can be replayed, including POST and PATCH, when the response is 429, 503, or 504. For 429 and 503 that is generally safe, because the server is saying it didn't process the request. A 504 doesn't mean that: a gateway timed out waiting, and the service behind it may already have acted.
For a non-idempotent POST, the retry then repeats the side effect. With Microsoft Graph's POST /users/{id}/sendMail, one call that gets a 504 can deliver the same email up to four times with the default MaxRetry of 3. The caller sees a single failure ("Too many retries performed") and has no way to tell that one or more copies may already have been sent.
Where this happens
At main (2d42841):
RetryHandlerOption.cs#L99-L103: the defaultShouldRetryreturnstruefor 503, 504, and 429, regardless of the request method.HttpRequestMessageExtensions.cs#L100-L110:IsBuffered()returnsfalseonly for a POST, PUT, or PATCH whose content length is unknown. A POST with a known-length JSON body counts as buffered.RetryHandler.cs#L76and#L146: a request is retried whenIsBuffered()andShouldRetryare both true. Neither check considers whether the method is idempotent.
Reproduction
I hit this through the Microsoft Graph PowerShell SDK. Microsoft.Graph.Authentication 2.40.0 bundles Microsoft.Kiota.Http.HttpClientLibrary 2.0.0 and Microsoft.Graph.Core 4.0.1.
The script below points the SDK at a local stub that answers every request with 504, then calls sendMail once with the default retry settings. It needs no tenant and sends no mail. It needs permission to listen on port 80, because Invoke-MgGraphRequest resolves relative URIs against the environment's host without a custom port. macOS allows that without elevation.
Repro-SendMailRetry.ps1
# Shows Microsoft.Graph.Authentication resending a POST /sendMail after a 504.
# A local stub stands in for Graph, so no tenant is needed and no mail is sent.
# Needs permission to listen on port 80 (macOS allows it; Linux and Windows
# usually need elevation).
param([string]$ModulePath = 'Microsoft.Graph.Authentication')
$ErrorActionPreference = 'Stop'
Import-Module $ModulePath
# Stub Graph endpoint: answers every request with 504 and records it.
$requests = [System.Collections.ArrayList]::Synchronized([System.Collections.ArrayList]::new())
$listener = [System.Net.HttpListener]::new()
$listener.Prefixes.Add($(if ($IsMacOS) { 'http://*:80/' } else { 'http://localhost:80/' }))
$listener.Start()
$server = [powershell]::Create().AddScript({
param($Listener, $Requests)
while ($Listener.IsListening) {
try { $context = $Listener.GetContext() } catch { break }
[void]$Requests.Add("$($context.Request.HttpMethod) $($context.Request.Url.AbsolutePath)")
$context.Response.StatusCode = 504
$context.Response.Close()
}
}).AddArgument($listener).AddArgument($requests)
[void]$server.BeginInvoke()
try {
# Point the SDK at the stub and sign in with an unsigned token; the stub ignores it.
$encode = { param($o) [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($o | ConvertTo-Json -Compress))).TrimEnd('=').Replace('+', '-').Replace('/', '_') }
$now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
$token = "$(& $encode @{ alg = 'none'; typ = 'JWT' }).$(& $encode @{ aud = 'https://graph.microsoft.com'; tid = [guid]::Empty; appid = [guid]::NewGuid(); roles = @('Mail.Send'); iat = $now; nbf = $now; exp = $now + 3600 }).x"
Add-MgEnvironment -Name 'ReproStub' -GraphEndpoint 'http://localhost' -AzureADEndpoint 'https://login.microsoftonline.com' | Out-Null
Connect-MgGraph -Environment 'ReproStub' -AccessToken (ConvertTo-SecureString $token -AsPlainText -Force) -NoWelcome
# Default retry settings, but a short delay so the repro runs quickly.
Set-MgRequestContext -RetryDelay 1 | Out-Null
$context = Get-MgRequestContext
Write-Host "MaxRetry=$($context.MaxRetry) RetryDelay=$($context.RetryDelay)"
$body = @{
message = @{
subject = 'Test'
body = @{ contentType = 'Text'; content = 'Test' }
toRecipients = @(@{ emailAddress = @{ address = 'someone@contoso.com' } })
}
} | ConvertTo-Json -Depth 5
try {
Invoke-MgGraphRequest -Method POST -Uri '/v1.0/users/sender@contoso.com/sendMail' -Body $body -ContentType 'application/json'
}
catch {
Write-Host "Invoke-MgGraphRequest failed: $($_.Exception.Message)"
}
Write-Host "Requests received by the stub: $($requests.Count)"
$requests | ForEach-Object { Write-Host " $_" }
}
finally {
Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
Remove-MgEnvironment -Name 'ReproStub' -ErrorAction SilentlyContinue | Out-Null
$listener.Stop(); $listener.Close(); $server.Dispose()
}Output on macOS, PowerShell 7.6:
MaxRetry=3 RetryDelay=1
Invoke-MgGraphRequest failed: Too many retries performed. More than 3 retries encountered while sending the request. (HTTP request failed with status code: GatewayTimeout.) ...
Requests received by the stub: 4
POST /v1.0/users/sender@contoso.com/sendMail
POST /v1.0/users/sender@contoso.com/sendMail
POST /v1.0/users/sender@contoso.com/sendMail
POST /v1.0/users/sender@contoso.com/sendMail
I've reproduced the duplicate sends on PowerShell 7 only. On Windows PowerShell 5.1, which uses the SDK's .NET Framework build, I've confirmed that MaxRetry = 0 limits the call to a single request; a Pester test covering that on both runtimes is here.
Expected behavior
A 504 on a non-idempotent request shouldn't be retried automatically, or at least not by default. The handler can't know whether the server acted on the request, so a retry can turn one side effect into several.
Possible fixes
Any of these would help, roughly from most to least protective:
- In the default
ShouldRetry, don't retry 504 for non-idempotent methods (POST and PATCH; PUT and DELETE are idempotent per RFC 9110), while still retrying 429 and 503. - Add an option, for example
RetryNonIdempotentRequests, that excludes POST and PATCH from retries, so callers can opt out without turning off retries entirely. - If the current default stays, document that POST and PATCH are retried on 504 and that this can repeat side effects, with the workaround below.
Workaround
Set RetryHandlerOption.MaxRetry to 0 for non-idempotent requests. In the Graph PowerShell SDK that's Set-MgRequestContext -MaxRetry 0 around the call, restoring the previous values afterward, and handling retries in the caller where it can decide which failures are safe to resend.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone ✔️
Activity
jackson-asmith commentedon Nov 13, 2026
Vincent Biret (@baywet) all seven ports are merged, thanks for the quick reviews and for opening the issues with test checklists, which made the porting much smoother:
Go: microsoft/kiota-http-go#312 · feat: add option to retry only…
Python: microsoft/kiota-python#897 · feat(http): add option to retry…
Java: microsoft/kiota-java#2251 · feat(http): add option to retry…
TypeScript: microsoft/kiota-typescript#2230 · feat(http): add option to retry…
PHP: microsoft/kiota-php#143 · feat(http-guzzle): add option to…
Dart: microsoft/kiota-dart#179 · feat(http): add option to retry…
Ruby: microsoft/kiota-ruby#225 · feat(http): add option to retry…
baywet commentedon Nov 13, 2026
Thanks for all the great work!