Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Last active April 30, 2026 09:39
Show Gist options
  • Select an option

  • Save MirzaLeka/f9cfc788ee90a1060a6465abc6f2148d to your computer and use it in GitHub Desktop.

Select an option

Save MirzaLeka/f9cfc788ee90a1060a6465abc6f2148d to your computer and use it in GitHub Desktop.

Retry HTTP requests in .NET with Polly

Polly is a powerful library for .NET that helps you handle transient faults and improve the resilience of your applications.

Setup

using Polly;
using System.Net;

			// named client
			var httpClientBuilder = services.AddHttpClient("CharactersAPI", client =>
			{
				client.BaseAddress = new Uri(configuration["CharactersUri"]?.ToString());
				client.DefaultRequestHeaders.Add("Accept", "application/json");

				//// Add your auth header here
				//client.DefaultRequestHeaders.Authorization =
				//	new AuthenticationHeaderValue("Bearer", configuration["CharactersApiToken"]);

			})
			.AddHttpMessageHandler<CharactersAuthHandler>()
			.AddPolicyHandler(GetRetryPolicy());
      
      
		private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
		{
			return Policy<HttpResponseMessage>
				.HandleResult(response =>
				{
					// Retry ONLY on 405 or 500+
					bool isRetryStatus =
						response.StatusCode == HttpStatusCode.MethodNotAllowed ||
						(int)response.StatusCode >= 500;

					if (!isRetryStatus)
						return false;

					// Retry ONLY on the specific route
					var path = response.RequestMessage?.RequestUri?.AbsolutePath ?? "";
					return path.Contains("/api/Characters/Update") &&
						   path.Contains("/broken");
				})
				.WaitAndRetryAsync(
					retryCount: 10,
					sleepDurationProvider: attempt => TimeSpan.FromSeconds(1),
					onRetry: (outcome, timespan, attempt, context) =>
					{
						Console.WriteLine(
							$"Retry {attempt} after {timespan.TotalSeconds}s due to {outcome.Result.StatusCode}"
						);
					}
				);
		}      

Usage

			var httpClient = httpClientFactory.CreateClient("CharactersAPI");
			var characterResult = await httpClient.PutAsync($"/api/Characters/Update/{id}/broken", content);;

			if (!characterResult.IsSuccessStatusCode)
			{
				return null;
			}

			return await characterResult.Content.ReadAsAsync<Character>();

The request will be retried on failure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment