Skip to content

Background jobs & hosted services

Genie runs background work through two complementary systems:

  1. Hosted services — long-running in-process background workers (notification delivery, search sync, SLA/monitor loops) that run inside the engine and are observable + controllable at runtime.
  2. Hangfire jobs — durable, storage-backed fire-and-forget / scheduled / recurring jobs, managed through a dedicated admin surface.

Engine workers derive from MonitoredBackgroundService (in the Services/HostedServices area). Each runs a processing loop and reports live metrics to an IHostedServiceMonitor, so operators can watch throughput and pause/resume a worker without restarting the app. The engine’s workers:

Dashboard name Class Cycle
App Notification Worker AppNotificationWorkerService notification delivery, 1–5 s
Email / SMS Notification Worker EmailNotificationWorkerService, SmsNotificationWorkerService queue drains
Warehousing Sync Worker WarehousingPollingWorker warehousing poll
Workflow SLA Monitor WorkflowSlaMonitorHostedService calls IWorkflowSlaMonitor once a minute; a failed sweep also waits a minute
Wizard Storage Worker WizardStorageWorker first cycle is the startup migrate + sweep; then drains designer saves, idling in 30 s cycles

Every worker waits for model migration to finish (or be disabled) before its first cycle. All of them except the wizard storage worker are worker loops:

  • They run only on a process with the Worker role, and only when AddWorkers(...) (or the config-driven default) selects them.
  • Only the process holding the worker lease runs them. On the others they show as Standby.

The wizard storage worker runs in every process, because generated wizard views are registered in each process’s memory. See API and worker processes.

Three startup hosted services are deliberately not monitored workers, because they run once rather than in a loop: EngineSqlBootstrapHostedService (a plain IHostedService whose StartAsync must finish before model migration starts), ModelMigrationService (the producer of the migration-ready signal every worker waits on; a failure must stop the host, not retry) and GenieWarmupHostedService (one-shot, best-effort). A worker that runs on a long fixed interval should override ErrorDelay with that interval, or a persistent fault retries every two seconds.

Several processes: one dashboard for all of them

Section titled “Several processes: one dashboard for all of them”

When ConnectionStrings:Redis is set, every process writes a heartbeat to Redis every 5 seconds. The heartbeat carries the node name, roles, worker state and a snapshot of its services. The dashboard reads all of them, so it shows every node whichever node the load balancer picked:

  • which node is the active worker (holds the lease) and which are standbys;
  • which services each node runs, with their live metrics;
  • each node’s Hangfire server name, which matches the Jobs “Servers” tab.

A node that stops heartbeating disappears within 30 seconds. A graceful shutdown removes it at once. Without Redis, the dashboard shows only the node that answered.

If the active worker loses the lease mid-batch, the notification workers stop and hand back what they had not sent. Rows are claimed atomically, so even an overlapping old leader cannot send them twice (see notifications).

Pause and resume are stored in Redis and pushed to every node over pub/sub. They apply to one node (?node=) or to all nodes, and they survive a restart.

Method Route Purpose
GET / live metrics for this node’s services
GET /cluster every node: roles, worker state (Leader / Standby / Unmanaged / None), Hangfire server, services
GET /{name} this node’s metrics for one service
POST /{name}/pause?node= pause a service on one node, or on every node when node is omitted
POST /{name}/resume?node= resume a service on one node, or on every node when node is omitted
GET /{name}/history?node=&from=&to=&limit= cycle history, newest first, for one node or merged across nodes. from / to are ISO timestamps (default: everything kept); limit defaults to 500, max 5000

Pausing stops the inner loop while leaving the background task alive; the worker polls until resumed. The UI exposes all of this through the components/hosted-services admin dashboard, grouped by node.

Each service card has a Details button. It opens a window with two tabs:

  • Overview: the live state of the service on that node. This covers its status, cycles per minute, total cycles and errors, average and last duration, uptime, the last run (counts, outcome and its step-by-step trace), the process (CPU, memory, threads, GC) and the node (roles, worker state, version). You can pause or resume the service from the footer.
  • History: every recorded run, newest first. You can pick a time range (last hour, 24 hours, 7 days, or everything kept), filter by succeeded or failed, search, and copy the list as JSON. Expand a run to see its counts and its trace.

How long history is kept is set with Genie:HostedServices:HistoryRetention: a number and a unit, D (days), H (hours) or M (minutes). The default is seven days.

"Genie": {
"HostedServices": {
"HistoryRetention": "7D", // also "1D", "12H", "30M"
"MaxHistoryEntries": 20000, // per service, per node, in Redis
"MaxInMemoryEntries": 2000, // per service, when there is no Redis
"MergeIdleCycles": true
}
}
genie.ConfigureHostedServices(h => h.HistoryRetention = "2D");

Where it is stored:

  • With Redis, history is shared by every node and survives restarts.
  • Without Redis, each process keeps its own history in memory, up to MaxInMemoryEntries per service, and loses it on restart.

Idle runs are merged. A service that polls every few seconds and finds nothing to do would fill a week of history with identical rows. Back-to-back idle runs are folded into one entry instead, shown as Idle ×240 with the time the idle stretch started. The next run that does real work starts a new entry. Set MergeIdleCycles: false to keep every run.

Every built-in service writes a trace for each run: what it did, in order, how long each step took, and what it found. This includes the app, email and SMS notification workers, the warehousing sync, the workflow SLA check and the wizard storage worker. In the history the trace shows as an indented tree:

10:42:01.204 | ↳ Claim batch (took 12ms)
10:42:01.204 | ↳ claimed=3
10:42:01.204 | ↳ owner=worker-1
10:42:01.217 | ↳ Send 3 email(s) (took 840ms)
10:42:01.511 | ↳ #41 → ana@example.com: sent (attempt 1/3)
10:42:01.790 | ↳ #42 → bo@example.com: sent (attempt 1/3)
10:42:02.057 | ↳ #43 → cy@example.com: failed (attempt 2/3)
10:42:02.057 | ↳ sent=2
10:42:02.057 | ↳ failed=1

Your own services can write the same kind of trace with CycleTrace and return it as the run’s InnerLogs:

public sealed class InvoiceExportWorker(IServiceScopeFactory scopes, IHostedServiceMonitor monitor, IModelMigrationSignal migration)
: MonitoredBackgroundService(monitor, migration)
{
public override string DisplayName => "Invoice Export";
protected override async Task<CycleResult> RunCycleAsync(CancellationToken ct)
{
var trace = new CycleTrace();
List<Invoice> pending;
using (trace.Step("Load unexported invoices")) // the step's line gets "(took Nms)" when it ends
{
pending = await LoadPendingAsync(ct);
trace.Value("found", pending.Count); // indented under the step: "found=12"
}
if (pending.Count == 0)
{
// Outcome "Idle" lets the history merge back-to-back idle runs.
return new CycleResult(TimeSpan.FromMinutes(1), "Idle — nothing to export",
new CycleProcessDetails { Outcome = "Idle", InnerLogs = trace.ToString() });
}
using (trace.Step($"Export {pending.Count} invoice(s)"))
{
foreach (var invoice in pending)
{
try { await ExportAsync(invoice, ct); trace.Line($"#{invoice.Id}: exported"); }
catch (Exception ex) { trace.Line($"#{invoice.Id}: failed").Error(ex); }
}
}
return new CycleResult(TimeSpan.FromSeconds(10), $"Exported {pending.Count} invoice(s)",
new CycleProcessDetails { Outcome = "Success", ProcessedCount = pending.Count, InnerLogs = trace.ToString() });
}
}
CycleTrace method Writes
Step("name") A line now, then indents everything until the returned handle is disposed, then adds (took Nms) to the line.
Line("text") A line at the current depth.
Value("name", value) A name=value line at the current depth.
Error(exception) A red ✖ Type: message line.

A trace is capped at 400 lines, so a huge batch cannot produce an unbounded entry.

For durable background processing Genie integrates Hangfire (wired via the app builder’s ConfigureHangfire). Its admin API is restricted to the System role and short-circuits with 503 when Hangfire storage is not configured on the server.

Method Route Purpose
GET /stats storage statistics (counts per state, servers, recurring jobs)
GET /jobs paginated, filterable job list (state, queue, method, date, id)
GET /jobs/{id} full job detail (parameters, state history, exception)
POST /jobs/{id}/requeue requeue a failed/deleted job
DELETE /jobs/{id} delete a job
GET /queues queues with current counts
GET /servers active Hangfire server instances
GET /recurring recurring job definitions
POST /recurring/{id}/trigger run a recurring job now
POST /recurring/bulk-trigger · /jobs/bulk-requeue · /jobs/bulk-delete batch operations
Need Use
Continuous in-process loop, live pause/resume, engine-internal Hosted service (MonitoredBackgroundService)
Durable, retryable, scheduled/recurring, survives restarts Hangfire job