How do you distinguish between transient errors (worth retrying) and permanent errors (should fail immediately) when designing error handling for calls to external dependencies?
Short answer
Transient errors (network timeouts, temporary service unavailability, rate limit responses) are typically identified by specific exception types or HTTP status codes (like 503, 429) known to represent temporary conditions, appropriate for retry logic with backoff -- permanent…
Advertisement
AModel answer
Transient errors (network timeouts, temporary service unavailability, rate limit responses) are typically identified by specific exception types or HTTP status codes (like 503, 429) known to represent temporary conditions, appropriate for retry logic with backoff -- permanent errors (like 400 Bad Request indicating malformed input, or 404 indicating a genuinely missing resource) should fail immediately without retrying, since retrying an inherently unrecoverable error just wastes time and resources without any chance of success.
var retryPolicy = Policy
.Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.ServiceUnavailable || (int)r.StatusCode == 429)
.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));
// 400/404 responses are NOT retried -- they're permanent failuresReal-world example
A payment processing integration correctly retries a 503 Service Unavailable response from the payment gateway up to three times with backoff, but immediately surfaces a 400 Bad Request (indicating a genuinely malformed payment request) to the caller without any wasted retry attempts.
Likely follow-ups
- How do you classify a timeout -- transient or permanent?
- What's the risk of retrying a non-idempotent operation without careful consideration?
Related topics