skip to content

With Hangfire, what does [DisableConcurrentExecution(timeoutInSeconds)] actually guarantee, and when is a dedicated queue with one worker the better tool?

level: seniorimportance: should knowfreq 30%

answer

  1. a distributed lock around the method
  2. default resource: Type.Method
  3. Resource with {0} placeholders
  4. waiting holds a worker
  5. timeout throws, then retries

basics

~20 s

[DisableConcurrentExecution] holds a storage distributed lock while the job method runs, so runs sharing a lock resource never overlap. It does not skip duplicates: the second run waits on its worker and fails into retries after the timeout.

solid answer

~50 s

`[DisableConcurrentExecution(timeoutInSeconds: 600)]` is a server filter: in `OnPerforming` it acquires a **distributed lock** in the job storage, named after the job's type and method (`SettlementJobs.RunAsync`) unless you pass a `Resource` such as `"payout:{0}"`, formatted with the job's arguments; `OnPerformed` releases it. A second instance of the job that starts meanwhile **blocks its worker** waiting for the lock; if the timeout passes it throws a `DistributedLockTimeoutException`, and the normal `[AutomaticRetry]` cycle reschedules it. So it guarantees *no overlap*, not *no duplicates*: both runs still execute, one after the other. With many queued instances, workers fill up waiting on one lock. When the real requirement is 'run these one at a time', a dedicated queue served by a server with `WorkerCount = 1` serialises without parking workers; when it is 'run once', make the job idempotent instead.

code

csharp · 14 lines
csharp
public sealed class PayoutJobs(IPayoutService payouts)
{
    // Runs for the same payout never overlap; different payouts run in parallel.
    [DisableConcurrentExecution("payout:{0}", 60)]
    public Task PaySellerAsync(long payoutId, CancellationToken ct)
        => payouts.PayIfNotPaidAsync(payoutId, ct);   // still checks: no dedup
}

public sealed class SettlementJobs(ISettlementService settlement)
{
    // Method-wide lock named "SettlementJobs.RunAsync"
    [DisableConcurrentExecution(timeoutInSeconds: 30 * 60)]
    public Task RunAsync(CancellationToken ct) => settlement.RunNightlyAsync(ct);
}

go deeper

for a junior

Remember that [DisableConcurrentExecution] prevents two runs of the same job method from overlapping by taking a lock.

for a middle

Explain the storage lock taken in OnPerforming, the default Type.Method resource versus a formatted Resource, and the timeout exception that leads to retries.

for a senior

Weigh it against a single-worker queue and idempotent design, size the timeout to the run time, and watch for parked workers and PostgreSQL's stale-lock window.

for a principal

Decide where mutual exclusion belongs: in Hangfire filters, in queue topology, or in the domain's own data, given the cost of each under load.

## What the attribute does `DisableConcurrentExecutionAttribute` is a job filter implementing `IServerFilter`. Around the execution of a job method: 1. **`OnPerforming`** computes a lock **resource** and calls `AcquireDistributedLock(resource, timeout)` on the storage connection, waiting up to `timeoutInSeconds`. 2. The method runs while the lock is held. 3. **`OnPerformed`** disposes the lock. The lock itself is the storage's distributed lock: a SQL Server application lock, a row in Hangfire.PostgreSql's lock table, or an expiring Redis key, so it works across every server sharing that storage. ## The resource decides what is exclusive | Constructor | Resource | Effect | |---|---|---| | `[DisableConcurrentExecution(600)]` | `Type.Method`, e.g. `SettlementJobs.RunAsync` | no two runs of that method overlap, whatever the arguments | | `[DisableConcurrentExecution("payout:{0}", 60)]` | the format string filled from job arguments, lower-cased | runs for the same first argument are exclusive; different payouts run in parallel | The per-argument form fits a marketplace well: two jobs for payout 4711 must not overlap, but payouts for different sellers should not wait for each other. ## What it does not do - **It does not deduplicate.** Both jobs run; the second simply starts after the first releases the lock. If the first already paid the seller, the second pays again unless the job checks. - **It does not free the worker.** A blocked job sits in Processing on a worker that does nothing but wait. Twenty queued instances of a locked job can occupy twenty workers. - **It fails on timeout.** If the lock is not acquired within `timeoutInSeconds`, the filter throws `DistributedLockTimeoutException` (on PostgreSQL, its subclass `PostgreSqlDistributedLockException`); the job fails and `[AutomaticRetry]` schedules a retry. - **On Hangfire.PostgreSql, very long holds can be lost.** Lock rows older than `DistributedLockTimeout` (10 minutes by default) are treated as stale, so a job holding its lock longer than that can see another acquire it. ## Alternatives and when to choose them | Requirement | Better tool | |---|---| | Jobs of one kind strictly one at a time, possibly many queued | a dedicated queue served by a server with `WorkerCount = 1` | | A recurring job must not overlap its next occurrence | `[DisableConcurrentExecution]` with a timeout shorter than the interval, or a fast exit when the previous run is still active | | The effect must happen once even if the job runs twice | an idempotent job: check state, use the job id as an idempotency key | | Short critical section inside a longer job | a lock taken in code around that section only | ## Practical guidance 1. Choose `timeoutInSeconds` from the expected run time of the job holding the lock; a timeout shorter than that guarantees failures and retries. 2. Prefer a narrow resource (`"payout:{0}"`) over the method-wide default. 3. Keep the locked work short, especially on PostgreSQL storage. 4. Never rely on the attribute for exactly-once effects.

  • A recurring settlement job takes 70 minutes but runs hourly; what happens with [DisableConcurrentExecution(600)]?
    The next occurrence starts while the previous one holds the lock, waits 10 minutes on a worker, then fails with a lock-timeout exception and enters automatic retries, which may collide again. Either make the timeout longer than the run, change the schedule, or let the job exit quickly when the previous run is still active.
  • Why is a WorkerCount = 1 queue sometimes better than the attribute?
    Jobs on that queue wait as Enqueued rows in storage, not as blocked workers, and they run strictly one after another on the single worker. The attribute instead parks each waiting job on a worker and turns long waits into failures and retries.

A single-occupancy fitting room with a queue outside: nobody shares the room, but everyone in line still goes in eventually, and each person waiting is a shop assistant standing idle beside them.

  • [DisableConcurrentExecution] drops the second job if one is already running.
  • The lock is held in memory, so it only works with a single server.
  • Waiting for the lock does not use a worker.
  • The attribute makes a job run exactly once.
  • The default lock covers only jobs with identical arguments.