Skip to content

RetryHandler retries non-idempotent POST requests on 504, which can duplicate side effects such as Graph sendMail #851

Closed

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 default ShouldRetry returns true for 503, 504, and 429, regardless of the request method.
  • HttpRequestMessageExtensions.cs#L100-L110: IsBuffered() returns false only for a POST, PUT, or PATCH whose content length is unknown. A POST with a known-length JSON body counts as buffered.
  • RetryHandler.cs#L76 and #L146: a request is retried when IsBuffered() and ShouldRetry are 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:

  1. 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.
  2. Add an option, for example RetryNonIdempotentRequests, that excludes POST and PATCH from retries, so callers can opt out without turning off retries entirely.
  3. 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.

Activity

  1. moved this to Needs Triage 🔍 in Kiotaon Nov 4, 2026
  2. moved this from Needs Triage 🔍 to Done ✔️ in Kiotaon Nov 13, 2026
  3. baywet commented on Nov 13, 2026

    @baywet
    Member

    Thanks for all the great work!

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

    No labels
    No labels

    Type

    No type

    Projects

    • Status
      Done ✔️

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions