With Hangfire, when can a seller-payout job's method run more than once, and how do you write it so a second run pays nobody twice?
answer
- retries rerun the whole method
- re-fetch after crash or invisibility timeout
- manual requeue from the dashboard
- the job id survives retries
- [IdempotentCompletion] guards finished jobs
basics
~20 sA Hangfire job reruns on every automatic retry, after a crash or expired invisibility timeout, and on a manual requeue. The payout job checks its recorded state first and sends the provider a key that stays stable across runs.
solid answer
~50 sHangfire is at-least-once, and its own features cause re-execution: **`[AutomaticRetry]`** reruns the whole method after any exception (even one thrown after the provider already paid), a **crashed server** or an **expired invisibility timeout** lets another worker fetch the job again, and an operator can **requeue** a Failed or Succeeded job from the dashboard. A payout job therefore starts by loading the payout and returning if it is already `Paid`; it calls the provider with an idempotency key that stays the same across runs, the payout id or `PerformContext.BackgroundJob.Id`, which a retry or re-fetch keeps unchanged; and it records the result in the same transaction that marks the payout paid. Note that each recurring occurrence is a *new* job with a new id, so recurring jobs key on the business date instead. `[IdempotentCompletion]` additionally stops a job that already reached a final state from running again when re-fetched, but it does nothing for a crash mid-run.
code
csharp · 17 linespublic sealed class PayoutJob(MarketplaceDbContext db, IPaymentProvider provider)
{
[AutomaticRetry(Attempts = 5, ExceptOn = new[] { typeof(PayoutRejectedException) })]
public async Task RunAsync(long payoutId, PerformContext context, CancellationToken ct)
{
var payout = await db.Payouts.SingleAsync(p => p.Id == payoutId, ct);
if (payout.Status == PayoutStatus.Paid) return; // a previous run finished
// Same key on every retry, re-fetch and requeue of this job
var key = $"payout-{payout.Id}";
var receipt = await provider.PayAsync(payout.SellerId, payout.Amount, key, ct);
payout.MarkPaid(receipt.Reference, context.BackgroundJob.Id);
await db.SaveChangesAsync(ct); // one transaction
}
}
// Enqueue: jobs.Enqueue<PayoutJob>(j => j.RunAsync(payoutId, null, CancellationToken.None));go deeper
Remember that a Hangfire job can run again after a failure, so it must check whether its work was already done.
List the Hangfire sources of re-execution (retries, crash re-fetch, requeue) and show a job that checks recorded state before acting.
Design payouts with a stable idempotency key, atomic result recording and fast failure on permanent errors, and know which keys survive retries and which change per recurring occurrence.
Set the rule that every background job is reviewed for repeat safety, and decide where idempotency lives: job code, domain state or the external provider.
## Where repeats come from in Hangfire Hangfire processes jobs **at least once**. For a job author the useful list is concrete: these are the Hangfire mechanisms that run the same method again. | Source | What happens | Same job id? | |---|---|---| | `[AutomaticRetry]` (global, 10 attempts) | any exception reschedules the job; the whole method runs again | yes | | server crash or kill mid-run | the queue row stays fetched; after the storage's invisibility timeout another worker runs it | yes | | long job on Hangfire.PostgreSql defaults | the fixed 30-minute invisibility timeout expires while it still runs; a second worker starts it | yes | | graceful shutdown | a job stopping on its token is re-queued and restarted elsewhere | yes | | requeue from the dashboard or `BackgroundJob.Requeue` | an operator runs a Failed or Succeeded job again | yes | | the same thing enqueued twice by the caller | two separate jobs | **no** | | each recurring occurrence | a new job per occurrence | **no** | The painful case is an exception thrown *after* the side effect: the provider paid, then saving the result timed out, and the retry pays again. ## Making the payout job safe to repeat 1. **Check recorded state first.** Load the payout; if it is already `Paid` (or `InProgress` with a provider reference), return or reconcile instead of paying. 2. **Use a stable idempotency key toward the provider.** The payout id works; so does `PerformContext.BackgroundJob.Id`, available by adding a `PerformContext` parameter, which stays the same through retries, re-fetches and requeues of that job. Do not use a fresh GUID per run. 3. **Record the outcome atomically.** Mark the payout paid and store the provider reference in one database transaction, so a crash leaves either 'not paid' (safe to retry) or 'paid' (skipped). 4. **Fail fast on permanent errors.** `[AutomaticRetry(ExceptOn = ...)]` stops pointless retries; idempotency handles the transient ones. 5. **Pass ids, not snapshots.** The job reads current state each run instead of acting on arguments captured at enqueue time. ## Hangfire helpers and their limits - **`[IdempotentCompletionAttribute]`** (Hangfire.Core 1.8): an election filter that stores the job's first final state in a `Completion` job parameter. If the job is later re-fetched or re-elected into Processing, it is put straight back into that stored final state, so a job that already **completed** is not run again, for example after a crash between finishing and acknowledging. It cannot help with a crash *during* the method, and it is not registered globally. - **`[DisableConcurrentExecution]`** prevents two runs from overlapping but still lets both run. - **`[AutomaticRetry(Attempts = 0)]`** removes Hangfire's retries for a job that cannot be made idempotent, leaving a Failed job for a person, at the price of no automatic recovery from transient faults. - The **`RetryCount`** job parameter tells the job it is a retry, which is useful for logging, not as a guard. ## Recurring jobs Each recurring occurrence creates a new background job with a new id. A nightly settlement must therefore key its idempotency on the **business period** (the settlement date), not on the job id, or a manual trigger plus the scheduled run would both pay out. ## Checklist for review - What happens if this method runs twice in a row? Concurrently? - What if it throws after the external call succeeded? - Which key makes the external call safe to repeat, and does it survive a retry?
- Is PerformContext.BackgroundJob.Id a good idempotency key for a nightly recurring settlement?No. Every recurring occurrence, and every manual trigger, creates a new background job with a new id, so two runs for the same night would carry different keys. Key on the business period, such as the settlement date, and check whether that period is already settled.
- Why not simply set Attempts = 0 on every payment job?It avoids Hangfire-driven repeats but not crash re-fetches, invisibility-timeout duplicates or manual requeues, and it turns every transient timeout into a Failed job that needs a person. Idempotent design covers all the sources; disabling retries covers one.
- Hangfire runs each job exactly once, so payouts cannot be duplicated.
- [DisableConcurrentExecution] makes the payout job idempotent.
- A retry gets a new job id, so the job id cannot serve as a key.
- Disabling automatic retries removes every way a job can run twice.
- [IdempotentCompletion] protects against a crash in the middle of the method.
Assumes Hangfire 1.8.25, whose Hangfire.Core ships IdempotentCompletionAttribute (not registered by default) and the global AutomaticRetryAttribute with 10 attempts.