http-client-resilience
IHttpClientFactory patterns with Polly for retries, circuit breakers, timeouts, and resilient HTTP communication. Includes best practices for HTTP client configuration and error handling. Use when configuring resilient HTTP clients in ASP.NET Core, implementing retry policies with Polly, or setting up circuit breakers for external service calls.
What this skill does
## Rationale
HTTP calls to external services are inherently unreliable. Network issues, service outages, and transient failures are common in distributed systems. Without proper resilience patterns, your application will experience cascading failures. These patterns using `IHttpClientFactory` and Polly provide production-grade reliability for HTTP communication.
## Patterns
### Pattern 1: Named HttpClient with Resilience
Configure named clients with comprehensive resilience policies including retry, circuit breaker, and timeout.
```csharp
// Program.cs - Configuration
builder.Services.AddHttpClient("PaymentApi", client =>
{
client.BaseAddress = new Uri("https://api.payment-provider.com/v1/");
client.Timeout = TimeSpan.FromSeconds(30);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("X-API-Key", builder.Configuration["PaymentApi:Key"]!);
})
.AddStandardResilienceHandler(options =>
{
// Retry configuration
options.Retry.MaxRetryAttempts = 3;
options.Retry.Delay = TimeSpan.FromSeconds(1);
options.Retry.BackoffType = DelayBackoffType.Exponential;
// Circuit breaker configuration
options.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(1);
options.CircuitBreaker.FailureRatio = 0.5;
options.CircuitBreaker.MinimumThroughput = 10;
options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
// Timeout configuration
options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(10);
options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(30);
});
// Typed client for type-safe usage
public interface IPaymentClient
{
Task<PaymentResult> ProcessPaymentAsync(PaymentRequest request, CancellationToken ct = default);
Task<RefundResult> ProcessRefundAsync(string transactionId, CancellationToken ct = default);
}
public class PaymentClient : IPaymentClient
{
private readonly HttpClient _httpClient;
private readonly ILogger<PaymentClient> _logger;
public PaymentClient(IHttpClientFactory httpClientFactory, ILogger<PaymentClient> logger)
{
_httpClient = httpClientFactory.CreateClient("PaymentApi");
_logger = logger;
}
public async Task<PaymentResult> ProcessPaymentAsync(PaymentRequest request, CancellationToken ct = default)
{
var response = await _httpClient.PostAsJsonAsync("payments", request, ct);
if (response.StatusCode == HttpStatusCode.TooManyRequests)
{
_logger.LogWarning("Payment API rate limit hit");
throw new PaymentRateLimitException("Payment provider is experiencing high load");
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<PaymentResult>(ct)
?? throw new PaymentException("Invalid response from payment provider");
}
public async Task<RefundResult> ProcessRefundAsync(string transactionId, CancellationToken ct = default)
{
var response = await _httpClient.PostAsync($"payments/{transactionId}/refund", null, ct);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<RefundResult>(ct)
?? throw new PaymentException("Invalid response");
}
}
```
### Pattern 2: Custom Resilience Pipeline with Polly
For advanced scenarios, build custom Polly pipelines with specific handling for different failure types.
```csharp
// Custom resilience pipeline configuration
builder.Services.AddResiliencePipeline("critical-api", builder =>
{
// Add retry with specific handling
builder.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
{
MaxRetryAttempts = 5,
Delay = TimeSpan.FromSeconds(2),
BackoffType = DelayBackoffType.Exponential,
ShouldHandle = args => args.Outcome switch
{
{ Result: { StatusCode: HttpStatusCode.TooManyRequests } } => PredicateResult.True(),
{ Result: { StatusCode: HttpStatusCode.ServiceUnavailable } } => PredicateResult.True(),
{ Result: { StatusCode: HttpStatusCode.GatewayTimeout } } => PredicateResult.True(),
{ Exception: HttpRequestException } => PredicateResult.True(),
{ Exception: TimeoutRejectedException } => PredicateResult.True(),
_ => PredicateResult.False()
},
OnRetry = args =>
{
Console.WriteLine($"Retry {args.AttemptNumber} for {args.Outcome.Result?.RequestMessage?.RequestUri}");
return ValueTask.CompletedTask;
}
});
// Add circuit breaker
builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions<HttpResponseMessage>
{
SamplingDuration = TimeSpan.FromMinutes(2),
FailureRatio = 0.6,
MinimumThroughput = 20,
BreakDuration = TimeSpan.FromMinutes(2),
ShouldHandle = args => args.Outcome.Result?.IsSuccessStatusCode is false
? PredicateResult.True()
: PredicateResult.False(),
OnOpened = args =>
{
Console.WriteLine($"Circuit opened! {args.FailureRatio * 100}% failure rate");
return ValueTask.CompletedTask;
},
OnClosed = args =>
{
Console.WriteLine("Circuit closed - service recovered");
return ValueTask.CompletedTask;
}
});
// Add timeout per attempt
builder.AddTimeout(TimeSpan.FromSeconds(15));
});
// Usage with typed client
public class InventoryClient
{
private readonly HttpClient _httpClient;
private readonly ResiliencePipeline<HttpResponseMessage> _pipeline;
public InventoryClient(
IHttpClientFactory factory,
ResiliencePipelineProvider<HttpResponseMessage> pipelineProvider)
{
_httpClient = factory.CreateClient("InventoryApi");
_pipeline = pipelineProvider.GetPipeline("critical-api");
}
public async Task<StockLevel> GetStockAsync(string sku, CancellationToken ct = default)
{
var response = await _pipeline.ExecuteAsync(
async token => await _httpClient.GetAsync($"stock/{sku}", token),
ct);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<StockLevel>(ct)
?? throw new InvalidOperationException("Invalid response");
}
}
```
### Pattern 3: Razor Pages Integration
Properly integrate HTTP clients in Razor Pages with proper disposal and error handling.
```csharp
// Typed client registration
builder.Services.AddHttpClient<IGeoLocationService, GeoLocationService>(client =>
{
client.BaseAddress = new Uri("https://api.geolocation.com/");
client.Timeout = TimeSpan.FromSeconds(10);
})
.AddStandardResilienceHandler(options =>
{
options.Retry.MaxRetryAttempts = 3;
options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(60);
});
// Service implementation
public interface IGeoLocationService
{
Task<LocationInfo?> GetLocationAsync(string ipAddress, CancellationToken ct = default);
}
public class GeoLocationService : IGeoLocationService
{
private readonly HttpClient _httpClient;
private readonly ILogger<GeoLocationService> _logger;
public GeoLocationService(HttpClient httpClient, ILogger<GeoLocationService> logger)
{
_httpClient = httpClient;
_logger = logger;
}
public async Task<LocationInfo?> GetLocationAsync(string ipAddress, CancellationToken ct = default)
{
try
{
var response = await _httpClient.GetAsync($"json/{ipAddress}", ct);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<LocationInfo>(ct);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Failed to get location for IP {Ip}", ipAddress)Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.