skip to content

With Hangfire, how do job filters such as IClientFilter, IServerFilter and IElectStateFilter work, and how would you add one that alerts when a payout job finally fails?

level: seniorimportance: nice to knowfreq 22%

answer

  1. JobFilterAttribute or a global filter
  2. client: OnCreating / OnCreated
  3. server: OnPerforming / OnPerformed
  4. state: OnStateElection, OnStateApplied
  5. config.UseFilter registers globally

basics

~10 s

Job filters are Hangfire's hooks around creation (IClientFilter), execution (IServerFilter) and state changes (IElectStateFilter, IApplyStateFilter). Apply one as a JobFilterAttribute on a method or class, or globally with config.UseFilter; a final-failure alert fits IApplyStateFilter.

solid answer

~40 s

Hangfire's own features are filters: `[AutomaticRetry]` is an `IElectStateFilter`, `[Queue]` another, `[DisableConcurrentExecution]` an `IServerFilter`. You write your own the same way. **`IClientFilter`** (`OnCreating`, `OnCreated`) runs where the job is created and can set job parameters or cancel creation; **`IServerFilter`** (`OnPerforming`, `OnPerformed`) wraps execution on the worker; **`IElectStateFilter`** (`OnStateElection`) may replace the candidate state; **`IApplyStateFilter`** (`OnStateApplied`, `OnStateUnapplied`) sees the state actually committed. Apply it as an attribute deriving from `JobFilterAttribute`, or globally with `config.UseFilter(...)` inside `AddHangfire`; global filters are single instances, so constructor-inject through the `(provider, config)` overload, not per job. For 'alert when a payout finally fails', use `IApplyStateFilter`: when the applied state is `FailedState`, retries are over, because `[AutomaticRetry]` turns earlier failures into Scheduled. Keep filters fast; they run inside Hangfire's state transactions.

code

csharp · 22 lines
csharp
using Hangfire.States;
using Hangfire.Storage;

public sealed class PayoutFailureAlertFilter(IAlertQueue alerts) : IApplyStateFilter
{
    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        if (context.NewState is FailedState failed
            && context.BackgroundJob.Job.Type == typeof(PayoutJob))
        {
            // retries are over: AutomaticRetry would have elected Scheduled otherwise
            alerts.TryPost($"Payout job {context.BackgroundJob.Id} failed: {failed.Exception.Message}");
        }
    }

    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction) { }
}

// Program.cs
builder.Services.AddHangfire((provider, config) => config
    .UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString))
    .UseFilter(new PayoutFailureAlertFilter(provider.GetRequiredService<IAlertQueue>())));

go deeper

for a junior

Remember that Hangfire features like [AutomaticRetry] and [Queue] are job filters, and that you can write your own as attributes or global filters.

for a middle

Explain the four filter interfaces and when each runs, and how to register a filter globally with UseFilter.

for a senior

Pick the right hook for a requirement such as final-failure alerts, keep global filters thread-safe and fast, and avoid scoped dependencies in them.

for a principal

Decide which cross-cutting concerns belong in Hangfire filters and which in the jobs or the wider observability stack, so behaviour stays discoverable.

## What a job filter is A **job filter** is a class Hangfire calls at defined points in a job's life. Most built-in behaviour is implemented this way, so filters are the supported extension point for cross-cutting concerns: tagging jobs with a tenant id, logging context, metrics, alerts or custom retry rules. ## The filter interfaces | Interface | Methods | Runs | Typical use | |---|---|---|---| | `IClientFilter` | `OnCreating`, `OnCreated` | in the process creating the job | add job parameters (tenant, correlation id); set `Canceled` to skip creation | | `IServerFilter` | `OnPerforming`, `OnPerformed` | on the worker, around the method | logging scope, timing, locks; `Canceled` skips execution | | `IElectStateFilter` | `OnStateElection` | while a new state is being chosen | replace the candidate state (retries, queue rewriting) | | `IApplyStateFilter` | `OnStateApplied`, `OnStateUnapplied` | inside the transaction committing a state | react to the state that actually happened | | `IClientExceptionFilter`, `IServerExceptionFilter` | `OnClientException`, `OnServerException` | when creation or execution throws | custom exception handling | Examples from Hangfire itself: `AutomaticRetryAttribute` (election and apply), `QueueAttribute` (election), `DisableConcurrentExecutionAttribute` (server), `ContinuationsSupportAttribute` (election and apply). ## Applying a filter - **As an attribute**: derive from `JobFilterAttribute` and implement the interfaces; put it on a job method or its type. Hangfire creates attribute instances by reflection, so they cannot receive services through a constructor. - **Globally**: `config.UseFilter(new PayoutFailureAlertFilter(...))` in `AddHangfire`, which adds it to `GlobalJobFilters.Filters`. Use the `AddHangfire((provider, config) => ...)` overload to build it with services from the container. A global filter is **one instance for every job**, so it must be thread-safe and must not hold scoped services such as a `DbContext`. - **Order**: filters run by `Order`, then scope (global, type, method); for filter types that do not allow multiple instances, only the most specific instance survives. ## Alerting on a final failure An alert on *every* exception would fire ten times per failing payout, because each attempt is first elected as Failed and then replaced by a retry. The reliable signal is the state that is actually **applied**: 1. Implement `IApplyStateFilter`. 2. In `OnStateApplied`, check `context.NewState is FailedState`. 3. Optionally restrict to payout jobs by `context.BackgroundJob.Job.Type`. 4. Hand the alert off quickly (a channel, an outbox row); the method runs inside the state-change transaction, and slow I/O there slows every worker. Because `AutomaticRetryAttribute` replaces the Failed candidate while attempts remain, a committed `FailedState` means retries are exhausted or the exception was excluded with `ExceptOn`. ## Pitfalls - Throwing from a filter fails the job, the creation call or the state change it runs in; catch and log inside. - Filters run in every process that creates or runs jobs; a client filter in the web app and a server filter in the worker service are different processes.

  • Why not raise the alert from IServerFilter.OnPerformed when context.Exception is set?
    `OnPerformed` sees every failed attempt, including the nine that `[AutomaticRetry]` will retry. Alerting there produces noise and no signal of finality. `IApplyStateFilter` sees the state actually committed, so a `FailedState` there means no retry was elected.
  • How would you stamp every job with the tenant that created it?
    A global `IClientFilter` whose `OnCreating` calls `context.SetJobParameter("TenantId", ...)` from the current request, and an `IServerFilter` whose `OnPerforming` reads it back with `context.GetJobParameter<string>("TenantId")` to set up the tenant scope before the method runs.

  • Hangfire job filters are ASP.NET Core MVC action filters registered on the controller.
  • A global filter gets a new instance per job, so a scoped DbContext in its constructor is fine.
  • IServerFilter.OnPerformed with an exception means the job's retries are exhausted.
  • Filter attributes can take constructor-injected services from DI.
  • Hangfire has no extension point for state changes.