Getting a third-party API call to return 200 OK takes an afternoon. Keeping that integration correct for years, while the provider times out, throttles you, has a bad deploy or quietly changes a response field, is the actual job.
I learned this the expensive way. In the WMS integration I rebuilt, the original low-code flow worked on the happy path. Its problem was what happened off it: syncs failed silently, payloads dropped without a trace, and people spent hours reconciling inventory by hand. None of that was a "the API is down" problem. It was a "nobody decided what should happen when it misbehaves" problem.
This playbook is the set of decisions I now make up front on every .NET integration, especially when an agency is going to hand it to a client's team. The code uses current Microsoft guidance (Microsoft.Extensions.Http.Resilience, built on Polly v8), and every default quoted below links to its source.
Note
Scope: outbound calls from your .NET service to someone else's API. Inbound webhooks and callbacks are a different problem (signature checks, replay windows, out-of-order delivery) and deserve their own post.
Define the integration's failure modes
Before choosing any resilience policy, list what the integration does and what it costs when each part goes wrong. The single most useful split is reads versus state-changing requests. A failed read can be repeated almost for free. A failed write might already have happened.
| Operation | Example | If it fails | If it runs twice |
|---|---|---|---|
| Read | Get shipment status | Stale screen, retry later | Harmless |
| Idempotent write | PUT a full address record | Data out of date | Harmless if the API honours PUT semantics |
| Non-idempotent write | POST a shipment or a payment | Order stuck, customer waiting | Duplicate shipment, double charge |
| Batch sync | Nightly inventory push | Drift between systems | Depends entirely on how the batch is keyed |
Then, for each provider, write down three things you'll need later: its documented rate limits, whether it supports idempotency keys, and whether it has a sandbox. If the documentation doesn't say, ask now. Finding out during an incident is worse.
The row that causes the most damage is the non-idempotent write, because of one fact that's easy to forget:

A timeout means you stopped waiting. It says nothing about whether the provider did the work. Microsoft's Retry pattern guidance describes exactly this case: the service processes the request successfully but fails to send a response, and the retry logic sends it again. Everything in the rest of this post follows from taking that seriously.
Build a consistent HttpClient foundation
Every provider gets one typed client, registered through IHttpClientFactory. That gives you pooled connections, one place for the base address and authentication, and one place to attach resilience. The typed client is also the boundary: provider-specific DTOs, status codes and quirks stay inside it, and the rest of the application talks to an interface in its own language.
// Program.cs
builder.Services
.AddHttpClient<ICarrierClient, CarrierClient>(client =>
{
client.BaseAddress = new Uri(builder.Configuration["Carrier:BaseUrl"]!);
})
.AddStandardResilienceHandler(options =>
{
// The standard handler retries every HTTP method by default, POST included.
options.Retry.DisableForUnsafeHttpMethods();
});
public interface ICarrierClient
{
Task<ShipmentStatus?> GetStatusAsync(string trackingNumber, CancellationToken ct);
Task<CreateShipmentResult> CreateShipmentAsync(Shipment shipment, CancellationToken ct);
}
Two habits matter more than they look:
- Pass the
CancellationTokenall the way down. If the caller has given up (a user closed the page, a job is shutting down), the HTTP call should stop too. - Know which timeout you're dealing with.
HttpClient.Timeoutdefaults to 100 seconds and throws aTaskCanceledException. The standard resilience handler adds its own timeouts, and when its total timeout fires your code gets a PollyTimeoutRejectedExceptioninstead. That exception is neither aTimeoutExceptionnor anHttpRequestException, so acatch (HttpRequestException)block won't see it. Microsoft has a clear write-up of which timeout fired. If you raise the handler's total timeout above 100 seconds, raiseHttpClient.Timeoutwith it, or the client cuts the request off first.
Here is what AddStandardResilienceHandler() puts around every request:

These are sensible defaults for an internal service. For a third-party API, check each one against the provider: is 10 seconds per attempt realistic for their slowest endpoint? Is a 100-request minimum before the circuit breaker reacts meaningful at your traffic volume? The full defaults table is worth reading once, carefully.
Retry only when it is safe
The standard handler retries on HTTP 500 and above, 408, 429, HttpRequestException and TimeoutRejectedException, with exponential backoff and jitter, and it honours the provider's Retry-After header. That's good behaviour for reads. For writes, it's the source of the duplicate in figure 1.
Warning
By default, the standard resilience handler retries all HTTP methods. Microsoft's own example of the risk: a retried POST that inserts a record can duplicate data. Call options.Retry.DisableForUnsafeHttpMethods() to exclude POST, PATCH, PUT, DELETE and CONNECT, or options.Retry.DisableFor(HttpMethod.Post, HttpMethod.Patch) if the provider's PUT and DELETE really are idempotent. (Microsoft Learn)
A few rules I apply to every integration:
- Bounded, always. A fixed number of attempts and a total time budget. Microsoft's guidance is blunt: never implement an endless retry mechanism, because it stops an overloaded service from recovering.
- Backoff with jitter. Without randomness, every client that failed at the same moment retries at the same moment too.
- Respect
Retry-After. A429 Too Many Requests(RFC 6585) usually comes with aRetry-Afterheader, which RFC 9110 allows to be either a number of seconds or an HTTP date. The standard handler reads it for you. If you write your own retry logic, handle both forms. - Don't retry what can't succeed. A
400or422means the request is wrong. Sending it again only adds noise. - Plan for retries running out. After the last retry, the standard handler doesn't throw: it returns the last error response. Your code still needs to decide what that means for the business operation.
The subtler trap is retrying at more than one layer. Each layer looks reasonable on its own:

Microsoft's transient-fault guidance uses the same arithmetic: two layers retrying three times each means nine attempts against the service. Add a message queue's redelivery on top and a provider outage turns into a self-inflicted load test, often one that gets you rate-limited for longer. Pick one layer to own retries for each operation and switch them off elsewhere. The same goes for HttpClient defaults: if you've added AddStandardResilienceHandler() to every client through ConfigureHttpClientDefaults, call RemoveAllResilienceHandlers() before adding a different pipeline to one client, rather than stacking two.
Prevent duplicate actions with idempotency
Disabling POST retries in the HTTP handler stops accidental duplicates, but the job still has to finish. The safe way to retry a write is to make it idempotent: give the logical operation one key, and send that same key on every attempt.
Many providers support this with an Idempotency-Key request header. Two things to know before relying on it:
- It isn't a finished standard. The IETF's Idempotency-Key header draft reached revision 07 in October 2025 and has not become an RFC. Header name, key format, retention and conflict behaviour are whatever each provider documents.
- Providers differ in the details. Stripe, a well-documented example, accepts keys up to 255 characters, keeps them for at least 24 hours, and returns an error if you reuse a key with different parameters. Another provider may keep keys for minutes, or not support them at all.
The key has to belong to the operation, not to the HTTP attempt. Create it when you record the intent to do the work, store it with that record, and reuse it on every retry, including retries after a process restart:
public async Task<CreateShipmentResult> CreateShipmentAsync(Shipment shipment, CancellationToken ct)
{
// Generated and saved with the shipment row before the first attempt,
// so a retry from a restarted worker sends the same key.
var key = shipment.IdempotencyKey.ToString();
using var request = new HttpRequestMessage(HttpMethod.Post, "shipments")
{
Content = JsonContent.Create(CreateShipmentRequest.From(shipment)),
};
request.Headers.Add("Idempotency-Key", key);
using var response = await _http.SendAsync(request, ct);
return await CreateShipmentResult.FromResponseAsync(response, ct);
}
Retries for this call then live in exactly one place, the background job that owns the shipment. That's the layer that can see the stored key.
Some edge cases to handle explicitly:
- Request fingerprints. If the payload can change between attempts (a recalculated price, a new timestamp), either freeze the payload with the key or treat a changed payload as a new operation with a new key. Sending a different body under an old key is undefined at best and an error at worst.
- Concurrent requests. Two workers picking up the same job can send the same key at the same moment. Some providers reject the second request with a conflict while the first is still running. Treat that as "in progress, check again later," not as a failure.
- Retention windows. If your retry schedule can outlast the provider's key retention, a late retry is a brand-new request. Keep your retry window inside theirs.
- Providers without idempotency support. Local deduplication (a unique constraint on your own table, Microsoft's Idempotent Consumer pattern) protects you from sending twice. It can't tell you whether an ambiguous attempt succeeded on their side. For that you need a lookup: search the provider for your own reference number before retrying, and if you can't tell, stop and flag it for a person rather than guessing.
Important
The rule underneath all of this: when the outcome of a write is unknown, find out before you repeat it. Reconcile, then retry.
Limit the impact of provider outages
Retries handle blips. Outages need different tools, and each one should answer a specific failure mode rather than be added because it's on a checklist:
| Failure mode | Mechanism | What it buys you |
|---|---|---|
| Provider is down and every call fails slowly | Circuit breaker | Fail fast for a while instead of tying up threads and stacking timeouts |
| A burst of work overwhelms their rate limit | Concurrency limit (the standard handler's rate limiter) | Steady, predictable traffic instead of a wall of 429s |
| The business can't wait for the provider to recover | Durable queue (database outbox, Service Bus) | Accept the work now, deliver it when they're back |
| One slow endpoint drags down everything else | Separate clients per endpoint group | A slow label API doesn't block status lookups |
The durable queue is usually the most valuable and the least used. If a user action "creates a shipment," the reliable version writes the intent to your database in the same transaction as the order, returns immediately, and lets a worker deliver it with the idempotency key from the previous section. A provider outage then becomes a delay in the queue, not an error page and a support ticket.
Don't reach for every mechanism by default. A low-volume integration with a reliable provider might need nothing beyond sensible retries and a queue. Fit the mechanism to the failure you've actually listed.
Test the provider contract
Most integration bugs I've fixed weren't in the retry logic. They were a renamed field, a date in an unexpected format, an error body that didn't match the documentation, or a header the sandbox didn't require but production did. Testing for those takes more than one layer:

Contract tests on recorded fixtures are fast and run on every build. Capture real sandbox responses, success and each error shape, as JSON files, then assert that your client sends the right request and maps each response correctly:
[Fact]
public async Task Maps_a_422_to_a_rejected_shipment_and_sends_the_idempotency_key()
{
var handler = new StubHandler(
HttpStatusCode.UnprocessableEntity,
await File.ReadAllTextAsync("Fixtures/create-shipment-422.json"));
var client = new CarrierClient(new HttpClient(handler) { BaseAddress = new("https://carrier.test/") });
var shipment = TestData.Shipment();
var result = await client.CreateShipmentAsync(shipment, CancellationToken.None);
Assert.Equal(ShipmentOutcome.Rejected, result.Outcome);
Assert.Equal("postcode", result.Errors.Single().Field);
Assert.Equal(
shipment.IdempotencyKey.ToString(),
handler.LastRequest!.Headers.GetValues("Idempotency-Key").Single());
}
Be honest about what these prove: that your code matches your copy of the contract. They can't detect the provider changing theirs.
Spec checks close part of that gap when the provider publishes an OpenAPI document. Pull it on a schedule, diff it, and fail the build when a field you depend on changes. You'll see "consumer-driven contract testing" recommended a lot, but classic Pact needs the provider to run verification against your contract, and third parties rarely will. Pact's own FAQ notes that public APIs are a poor fit. PactFlow's bi-directional contract testing compares your expectations to the provider's OpenAPI spec instead. That's useful, but it's only as accurate as the spec they publish.
Fault injection tests the resilience pipeline itself, which unit tests with a stubbed handler skip entirely. Microsoft's Dev Proxy sits between your app and the API and returns random 429s and 5xxs, adds latency past your attempt timeout, and checks that you actually wait for Retry-After. It's the quickest way I know to prove a POST really is sent only once.
Sandbox tests on a schedule catch everything else: expired credentials, a provider deploy that changed validation, a sandbox that has quietly drifted from production. Keep them out of the per-commit build, since they're slow and depend on someone else's uptime, but alert on failures.
Make production failures actionable
When something goes wrong at 2 a.m., the on-call person needs to answer three questions quickly: what failed, for which records, and is it safe to replay? Design the telemetry for those questions:
- Latency and outcome per provider endpoint, so "the carrier is slow" is a graph, not a hunch.
- Retries, throttling and circuit-breaker state. A rising retry rate is the earliest warning you'll get. Log each retry with the attempt number and the status that caused it.
- Failed business operations, not just failed HTTP calls. "Shipment 88231 could not be created after 3 job attempts" is actionable. "HTTP 503" isn't.
- Correlation identifiers. Log your operation ID, the idempotency key and any request ID the provider returns. When you open a support ticket with them, that request ID is the first thing they'll ask for.
- Redaction. Never log authorization headers, API keys or full payloads containing personal data. Log identifiers and shapes, and decide what's safe before the first incident, not during it.
Then build the two tools that turn an incident into a routine task:
- Reconciliation. A scheduled job that compares your records with the provider's ("shipments we think exist versus shipments they say exist") and reports differences. This is what catches the kind of silent failures that sank the low-code WMS flow.
- Safe replay. A way to re-run failed operations, through the same idempotent path with the same stored keys, so replaying something that actually succeeded is harmless.
Create a repeatable agency handover
If you're an agency building this for a client, the integration isn't finished when it works. It's finished when the client's team can run it without you. My handover pack is short and the same every time:
- Configuration, documented. Every setting with its default, what it controls and when to change it: base URLs, timeouts, retry counts, rate limits. Secrets stay in the client's vault, never in the repository.
- Test fixtures and how to refresh them, so the contract tests keep tracking the real API.
- Ownership. Who holds the provider account, who gets the alerts, who talks to the provider's support.
- A recovery runbook. What each alert means, how to check provider status, how to run reconciliation, how to replay safely, and when to stop and escalate.
Write it inside the client's existing tools, whether that's their wiki, their ticket templates or their alerting, rather than in a separate document nobody will open again.
A readiness checklist
Before an integration goes live, I want to be able to tick every one of these:
- Every operation is classified as a read, an idempotent write or a non-idempotent write
- Retries are bounded, use backoff with jitter, respect
Retry-After, and live in exactly one layer per operation -
POSTand other unsafe methods are excluded from automatic HTTP retries - Every state-changing operation has a stored idempotency key, or a documented lookup when the provider doesn't support one
- Timeouts are set deliberately, and the code handles both
TaskCanceledExceptionandTimeoutRejectedException - Contract tests cover requests, responses and each error shape, and fault injection proves the retry behaviour
- Telemetry carries correlation IDs with secrets redacted
- Reconciliation and safe replay exist, and a runbook explains when to use them
None of this is exotic. It's the difference between an integration that works in the demo and one that's still quietly correct a year later, after the provider's third bad deploy.
If you're an agency with an integration like this on the roadmap, this is the kind of work PBX Digital does alongside agency teams: inside your tools and delivery process, with founder-led architecture oversight from start to handover. Book a 45-min intro call.