Field report

How Tenderis monitors its Hangfire jobs with QueueHawk

Tenderis is an AI platform for public tenders in Switzerland: it collects tenders from simap.ch, analyses the tender documents and tells companies which tenders are worth a bid. It is also our sister product — built by the same company, Substring AG — and it reports its Hangfire jobs to QueueHawk. So read this as a field report from inside the house, not as an independent review. The lessons, though, are about Hangfire, and most of them apply whether you use QueueHawk or not.

What runs in the background

Tenderis is a single ASP.NET Core server on .NET 10 — API, Blazor host and Hangfire in one container, with Hangfire on PostgreSQL storage. Its registration file lists 22 recurring job IDs, backed by 16 job classes. 13 of them have a schedule in code; the other 9 are set to Cron.Never() and only run when someone triggers them by hand: an initial import, filling a gap after an outage, a one-off backfill after a deploy, a measurement before and after a model change.

On top of these come on-demand jobs that a user starts with a button: the AI suitability analysis, the evaluation of the tender documents, a catalogue of questions for the contracting authority, a text suggestion, and a campaign's first search run. Some of them take ten to forty minutes, because they make dozens of language-model calls. That is where most of the lessons below come from.

Lesson 1: Task.Run dies with the deploy

Several of these jobs started life as _ = Task.Run(...) in a controller: the request returns, the work continues in the web process. It works — until the next deploy. Kubernetes replaces the pod, the task dies with it, and nothing records that it died. The status row the UI was polling stays on running forever. The user watches a progress indicator with nothing behind it, and cannot start a second attempt, because one is “already running”.

Tenderis learnt this three times: with the suitability analysis, with the question catalogue, and with a campaign's search run. The last one hurt the most, because it can be the very first run of a new customer — the one moment where nothing else proves that the product works. All three are Hangfire jobs now. Hangfire stores the job before it starts, and a job whose process died is handed out again after the restart.

There is a monitoring side to this as well: a loose task is invisible to every job monitor, QueueHawk included. Whatever isn't a Hangfire job produces no state changes, no failures and no history.

Lesson 2: Nothing long belongs in the HTTP request

The other half of the same problem: generating the question catalogue — one model call over up to twelve tender documents — takes minutes, and the ingress in front of the application cuts a request after 60 seconds. The user saw an error, and the result arrived anyway, later, with nobody looking. A text-suggestion feature showed the same pattern: “generation failed”, while the text was still being written.

The pattern that replaced it is unspectacular and works: the endpoint enqueues a job and answers 202 Accepted, a status row per item holds running, done or error, and the UI polls every three seconds — and picks a running job up again after a page reload.

Controller (simplified)
[HttpPost("generate")]
public async Task<IActionResult> Generate(Guid itemId)
{
    await runs.MarkRunningAsync(itemId);   // the row the UI polls
    jobs.Enqueue<QuestionCatalogueJob>(j => j.ExecuteAsync(itemId, null));
    return Accepted();
}

The reload part matters more than it looks. Results you can only find by reloading are worse than none: the user presses the button a second time and pays for the model call twice.

Lesson 3: Long jobs get their own queue

Ten suitability analyses at ten to forty minutes each would occupy every worker of a default Hangfire server. Scraping, campaign matching and deadline reminders — the jobs customers depend on every hour — would wait behind them. Tenderis therefore runs two Hangfire servers in the same process: one for the default queue, and one that only serves a queue called analyse, with a fixed number of workers (three by default, configurable). The default server deliberately does not listen on that queue.

Program.cs
services.AddHangfireServer(o =>
{
    o.ServerName = Environment.MachineName;
    o.Queues     = ["default"];
});

services.AddHangfireServer(o =>
{
    o.ServerName  = $"{Environment.MachineName}-analyse";
    o.Queues      = ["analyse"];
    o.WorkerCount = 3;
});

// on each long-running job class
[Queue("analyse")]
public class DocumentAnalysisJob { /* ... */ }

Whoever starts an analysis beyond those three waits in line, and the UI shows the position — read from Hangfire's monitoring API (EnqueuedJobs("analyse", …)). A visible queue position turns “it's broken” into “it's my turn in a few minutes”.

Lesson 4: A job that runs longer than 30 minutes may run twice

On PostgreSQL storage, a fetched job only counts as taken for the InvisibilityTimeout — 30 minutes by default. After that, Hangfire.PostgreSql hands the job out again, without checking whether the first worker is still alive. In Tenderis, a suitability analysis that hung in retries against the language model started a second time exactly 30 minutes after the first one, in parallel. The [DisableConcurrentExecution] lock on it didn't help: it had already expired after its own DistributedLockTimeout.

The fix is the sliding invisibility timeout: as long as the worker lives, it keeps extending its lease; if the process dies — a deploy — the job is free again after five minutes.

Hangfire.PostgreSql storage options
cfg.UsePostgreSqlStorage(o => o.UseNpgsqlConnection(connectionString),
    new PostgreSqlStorageOptions
    {
        UseSlidingInvisibilityTimeout = true,
        InvisibilityTimeout           = TimeSpan.FromMinutes(5),
        DistributedLockTimeout        = TimeSpan.FromMinutes(30),
    });

Other storages have their own variant of this setting. Whatever you use, find out what it does with a job that runs longer than its lease — before a long job finds out for you.

Lesson 5: Overlap protection has a price

The scheduled scraper and embedding jobs carry [DisableConcurrentExecution]: a recurring job must never run twice at the same time. Two consequences are easy to miss.

For the jobs in the analyse queue, Tenderis replaced the attribute with a lock that doesn't wait: try for two seconds, and if another run for the same item holds it, skip. Note both exception types — Hangfire.PostgreSql throws its own, not the generic one:

A lock that doesn't wait
var connection = storage.GetConnection();
IDisposable lease;
try
{
    lease = connection.AcquireDistributedLock(key, TimeSpan.FromSeconds(2));
}
catch (Exception ex) when (ex is DistributedLockTimeoutException
                               or PostgreSqlDistributedLockException)
{
    connection.Dispose();
    return;   // another run for this item holds the lock: skip, and log it
}

using (connection)
using (lease)
{
    // ... do the work ...
}

A skip is a success in Hangfire's eyes, so no error-rate alert will ever see it. Here that's intended — the work is being done by the other run — but write the skip to the job log so that a human can.

Lesson 6: Clean up after runs that never finished

Even with everything in Hangfire, a process can die between “set status to running” and “set status to done”. Tenderis runs a cleanup job every ten minutes: status rows that have been running for more than 30 minutes are marked as failed, with a message the user can read. Two refinements came from production:

Lesson 7: One list of recurring jobs, named by task

Recurring jobs used to be registered in two branches, one for production and one for development, which listed almost the same jobs. One job existed only in the development branch — production had the feature, and the feature's document was empty until someone noticed. Another stood on Cron.Never() in every environment and never ran by itself. Neither produces an error message: a job that never runs never fails.

Today every recurring job is registered exactly once, with its production and development schedule side by side:

Registration (simplified)
var options = new RecurringJobOptions
{
    TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Zurich")
};

RecurringJob.RemoveIfExists("ChScraperJob");           // the ID before the rename
RecurringJob.AddOrUpdate<ChScraperJob>("Scraper.CH",
    j => j.ExecuteAsync(null),
    isScheduled ? "20 4,9,13,17 * * *" : Cron.Never(),
    options);

One detail that costs everybody a few minutes once: Cron.Never() shows up in the dashboard as 0 0 31 2 * — the 31st of February, a date that doesn't exist. Tenderis's job handbook records a job that was documented as running while it stood on “never” in production, because it was missing from the whitelist. After scheduling a job, look at the dashboard. (The cron expression explainer shows what a schedule really means.)

What QueueHawk watches

The integration in Tenderis is exactly this, in Program.cs next to the Hangfire setup — no job code was changed:

Program.cs
builder.Services.AddQueueHawk(options =>
{
    options.ApiKey      = builder.Configuration["QueueHawk:ApiKey"];
    options.Environment = builder.Environment.EnvironmentName;
});

The agent registers Hangfire filters that capture every state change, plus a background service that sends a heartbeat every 30 seconds. Where no key is configured — as in development — the agent logs that it is unauthorized and otherwise stays out of the way; it never throws into a job. What that gives Tenderis:

One naming detail worth knowing: QueueHawk names a job type Class.Method. Three of Tenderis's recurring IDs — new tenders, corrections and a full backfill — call the same method with different arguments, so the 22 recurring IDs appear as 20 job types. That's fine for “the analysis job is failing”. If you want a separate error-rate rule per recurring job, give each its own method.

What it does not see

A monitor that only watches Hangfire knows only Hangfire. In Tenderis, that leaves four gaps — written down, so nobody assumes otherwise:

Checklist for your own project

  1. Everything that has to survive a deploy is a Hangfire job, not Task.Run.
  2. Nothing that can outlast your proxy's timeout runs inside the request: 202 Accepted, a status row, polling — and resumable after a reload.
  3. Long jobs get their own queue and their own server with a fixed worker count.
  4. Know your storage's invisibility timeout. If jobs can run longer, use the sliding variant.
  5. For every [DisableConcurrentExecution], decide deliberately: wait, fail or skip. Keep run budgets shorter than the gap between two scheduled runs.
  6. Have a cleanup for status rows stuck on running — one that asks Hangfire before declaring anything failed.
  7. Register recurring jobs in one list, with an explicit time zone, and remove renamed IDs. After every change, look for 0 0 31 2 * in the dashboard.
  8. Log, then rethrow. A swallowed exception is a success.
  9. Alert on missing heartbeats, and put error-rate rules on the jobs whose failure nobody would otherwise notice.
  10. Write down, per job, how you would notice that it didn't run — and turn checks that aren't jobs into a job that fails.

If you work with public tenders in Switzerland, this is the machinery behind Tenderis. If you run Hangfire, the rest of the blog goes deeper into individual points: common Hangfire errors, jobs stuck in Enqueued and why job history disappears after a deploy.

← All articles Try QueueHawk free →

Heartbeat and error-rate alerts for your Hangfire jobs

One line in Program.cs, no changes to your jobs. Free for one application.

Start free