skip to content

An ASP.NET Core client POSTs card charges to a payment gateway through AddStandardResilienceHandler; what can go wrong by default, and how do DisableForUnsafeHttpMethods and DisableFor help?

level: seniorimportance: should knowfreq 38%

answer

  1. every method is retried by default
  2. a 10-second cut, then a resend
  3. POST, PATCH, PUT, DELETE, CONNECT
  4. it wraps the current ShouldHandle
  5. marked [Experimental] in 10.10

basics

~20 s

The standard handler retries every HTTP method, so a charge the gateway already processed can be resent after a timeout or 5xx and bill twice. DisableForUnsafeHttpMethods stops retries for POST, PATCH, PUT, DELETE and CONNECT; DisableFor takes your own list.

solid answer

~50 s

`HttpRetryStrategyOptions` decides only by outcome, not by method, so out of the box a `POST /charges` is retried on a 503, a 429, an `HttpRequestException` or a 10-second attempt timeout. The last case is the nasty one: the gateway may still finish the first charge after the client has given up on it, and the retry creates a second. In `Configure(o => o.Retry.DisableForUnsafeHttpMethods())` the retry predicate is wrapped so that POST, PATCH, PUT, DELETE and CONNECT are never retried; `o.Retry.DisableFor(HttpMethod.Post)` names methods yourself. Both wrap whatever `ShouldHandle` is set at the moment you call them, so set a custom predicate first. They live in `HttpRetryStrategyOptionsExtensions`, marked `[Experimental]` in 10.10.1. The breaker, rate limiter and timeouts still apply to POSTs. Often cleaner: one client for reads with retries and a separate charge client without them, or retries only where the gateway supports an idempotency key.

code

csharp · 7 lines
csharp
// DisableForUnsafeHttpMethods is [Experimental]: suppress its diagnostic deliberately
builder.Services.AddHttpClient<PaymentChargeClient>(c => c.BaseAddress = new Uri("https://gateway.example.com/"))
    .AddStandardResilienceHandler(o =>
    {
        // customise ShouldHandle first (if at all), then wrap it
        o.Retry.DisableForUnsafeHttpMethods(); // no retry for POST/PATCH/PUT/DELETE/CONNECT
    });

go deeper

for a junior

Recall that the standard handler retries every method by default and that a retried payment POST can charge twice.

for a middle

Explain DisableForUnsafeHttpMethods versus DisableFor, the five methods it covers, and how it wraps ShouldHandle.

for a senior

Design read and write clients for a payment gateway, place idempotency keys correctly and reason about timeouts that fire after the server acted.

for a principal

Set a policy for which downstream writes may ever be retried and what contract, such as idempotency keys, a provider must offer first.

## The default: retries decide by outcome only The standard pipeline's retry uses `HttpRetryStrategyOptions`, whose `ShouldHandle` predicate looks at the **outcome**: status 500 or above, 408, 429, an `HttpRequestException` or a `TimeoutRejectedException`. It never looks at the **method**. The .NET documentation states it plainly: by default the standard resilience handler retries all HTTP methods. For reads such as `GET /payments/{id}` that is what you want. For a card charge it is a liability. ## How a duplicate charge happens 1. The shop sends `POST /v1/charges` for 49.90. 2. The gateway is slow; after 10 seconds the **attempt timeout** abandons the attempt and throws `TimeoutRejectedException`. 3. The retry treats that as transient and, after a backoff, sends the same POST again. 4. Meanwhile the gateway finishes the first request and charges the card. The second request charges it again. The same can happen with a 502 or 503 produced by a proxy after the gateway already processed the charge, or with a connection reset after the request body was sent. The client cannot tell "never arrived" from "done but the answer was lost". ## Turning retries off per method `Microsoft.Extensions.Http.Resilience` adds two extension methods on `HttpRetryStrategyOptions`: | Method | Effect | |---|---| | `DisableForUnsafeHttpMethods()` | no retry for `POST`, `PATCH`, `PUT`, `DELETE` and `CONNECT` | | `DisableFor(params HttpMethod[] methods)` | no retry for the methods you pass | You call them on the retry options of the standard handler: `.AddStandardResilienceHandler(o => o.Retry.DisableForUnsafeHttpMethods())`. A few details matter: - **They are experimental.** Both sit in `HttpRetryStrategyOptionsExtensions`, which carries `[Experimental]` in 10.10.1, so the compiler reports an experimental-API diagnostic that you suppress deliberately. - **They wrap the predicate that exists when you call them.** The method captures the current `ShouldHandle` and installs a new one that also checks the request's method. If you assign `o.Retry.ShouldHandle = ...` afterwards, your assignment replaces the wrapper and POSTs are retried again. Customise `ShouldHandle` first, then call `DisableFor...`. - **The list is conservative.** `PUT` and `DELETE` are idempotent in HTTP terms, but they are not read-only, so the "unsafe" list includes them. Use `DisableFor(HttpMethod.Post, HttpMethod.Patch)` if you want PUT and DELETE retried. - **Only the retry changes.** The rate limiter, both timeouts and the circuit breaker still apply to a POST, so a hung charge is still cut at 10 seconds and a failing gateway still trips the breaker. ## Designing the client for payments Disabling retries is the minimum. Common shapes: - **Two clients.** A `payments-read` client with the standard handler (or hedging) for status checks, and a `payments-write` client for charges whose retry is disabled for unsafe methods. - **Retry only with an idempotency key.** If the gateway deduplicates requests carrying a client-generated key header, retrying a POST that carries the same key is safe; then keep retries but make sure the key is generated once per logical charge, outside the resilience handler. - **Reconcile after a timeout.** When a charge attempt times out, query the payment status before deciding to charge again. ## Common mistakes - Assuming the standard handler is method-aware because it is "standard". - Calling `DisableForUnsafeHttpMethods()` and then overwriting `ShouldHandle`. - Generating the idempotency key inside a `DelegatingHandler` that sits inside the resilience handler, so every retry gets a new key and the gateway sees distinct charges.

  • Does DisableForUnsafeHttpMethods stop the circuit breaker from counting failed POSTs?
    No. It only wraps the retry's `ShouldHandle`. The circuit breaker has its own predicate and still counts failed or timed-out POSTs, which is usually what you want: a gateway failing charges should open the breaker for reads too.
  • If the gateway supports an idempotency key, where must the key be generated?
    Once per logical charge, before the request enters the resilience handler, for example in the typed client method that builds the `HttpRequestMessage`. A handler registered after the resilience handler runs on every attempt, so it would mint a new key per retry and defeat deduplication.

  • Believes the standard handler never retries POST requests
  • Says DisableForUnsafeHttpMethods also excludes GET and HEAD
  • Overwrites Retry.ShouldHandle after calling DisableFor and expects both to apply
  • Thinks disabling retries also disables the breaker and timeouts for POST
  • Generates the idempotency key in a handler that runs per attempt

Assumes Microsoft.Extensions.Http.Resilience 10.10.1 with ASP.NET Core 10, where DisableFor and DisableForUnsafeHttpMethods are still marked [Experimental].