In my ASP.NET Core application, some long-running background tasks fail due to transient network errors, while others fail due to unrecoverable business validation issues. By default, Hangfire retries failed jobs up to 10 times.
Applying Retry Attributes
I know I can use the AutomaticRetry attribute at the method level:
// Customize retry attempts and strategy for a specific method
[AutomaticRetry(Attempts = 3, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
public void ProcessPayment(int orderId)
{
// Payment processing logic
PaymentGateway.Charge(orderId);
}Global Configuration Questions
I want to apply a default retry policy globally across all jobs while overriding it for specific background operations. How can I set a global retry attempt limit during registration in Program.cs? Also, how can I capture exceptions from a failed background job and send alert notifications to developers before the job is placed in the Deleted state?
Hangfire applies an
AutomaticRetryAttributeby default. You can set the retry count and delay schedule globally, or setAttemptsto0when automatic retries should be disabled.Set a custom global retry policy
Configure the global filter during application startup, before starting Hangfire servers. Remove the default filter first so the new settings do not run alongside it:
Use
AttemptsExceededAction.Deleteinstead if the job should be removed after exhausting its retries. The delay array controls the retry schedule; choose values that make sense for the failures your job may encounter.Disable automatic retries
To disable them for all jobs, replace the default filter with one configured for zero attempts:
For a single job, use
[AutomaticRetry(Attempts = 0)]on its method. You can also set a different attempt count there for jobs that need their own policy. Avoid applying multiple automatic-retry filters to the same job unless you have checked how their combined behavior works in your Hangfire version.Disabling this filter stops Hangfire's automatic retry behavior; it does not prevent a job from being requeued for other reasons, such as server shutdown handling or an explicit state change.