Skip to content
Edit this page

Running in production

Health checks

Bellhop adds a health check that reports the node Healthy, Degraded or Unhealthy:

builder.Services.AddHealthChecks().AddBellhopHealthCheck(tags: ["ready"]);

Map it to readiness, not liveness. A database outage must not take your application down: while the store cannot be reached the node keeps retrying, the host keeps running, and the check reports Unhealthy. An orchestrator that restarts on a failed liveness probe would restart the pod in a loop for as long as the outage lasts; one that takes the pod out of readiness simply waits:

app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = check => check.Tags.Contains("ready") });
// Liveness runs no check, so a store outage never restarts the pod.
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });

The check reports Unhealthy while the node is still starting, while the store does not answer or its schema is not one this version runs on, and on a worker node while its loops have stopped or keep failing. It reports Degraded while jobs wait longer than SchedulingLagThreshold (60 seconds) to be claimed, or failures and dead letters on this node pass their thresholds. After an Unhealthy run, the first passing run reports Degraded, and the node reports Healthy again only after HealthyAfterPasses (3) passing runs in a row. ASP.NET Core's health endpoints answer Degraded with 200, so readiness fails only while the node is Unhealthy.

On the Redis store, every result also carries the server's persistence mode (redis.persistence: aof, snapshot-or-none or unknown) and, when INFO gives them, its redis.used_memory and redis.maxmemory in bytes. The check reports Degraded while used_memory is above MemoryDegradedShare (0.8, set in UseRedis) of maxmemory, so you hear of it before the server refuses writes; a server with no maxmemory (0) never does.

The Redis store also reports Degraded while it reconciles. Each namespace keeps a generation marker that worker nodes move forward every RecurringReconcileInterval (5 minutes, set in UseRedis). When a worker finds it missing, or older than the value it last saw, as after FLUSHALL, a restore from an older copy or a failover to a lagging replica, it logs StoreWasReset (4315, Error) and replaces it, and every worker node pauses claims and recurring occurrences while it writes its registration and code-defined recurring jobs again, for one LeaseDuration (60 seconds) after that started, so running jobs re-assert their leases first. The other workers join silently (StoreReconciliationJoined, 4317), and each logs StoreReconciled (4318) when its pause ends. The first worker on a new server does the same without a report (StoreInitialised, 4316), so the first claim on a new installation waits one LeaseDuration. Enqueues are never held; due recurring instants are handled by their misfire policy when the pause ends, and a trigger-now during it fails with a message that says to try again. Nodes without the worker, and a BellhopTestHarness worker, which the test drives, never write the marker: on a server that only they use, nothing is claimed until a worker node starts. Inline execution is refused the same way: its call throws and the job stays enqueued. A rollback to data less than RecurringReconcileInterval old is not detected.

The worker that detected a reset also logs StoreResetStateLost (4320, Error): runtime-defined recurring jobs, the maintenance pause, queue pauses, runtime throttle limits and recurring-job pauses may have been lost and are back at their defaults, and a paused code-defined recurring job is Active again. Nodes keep no copy of them, so set again what you still need. The script that replaced the marker records the reset in the store as unacknowledged in the same step, so the record stays even when its reply is lost, and every node that uses the store, worker or not, reports Degraded until an operator acknowledges the reset on the dashboard, long after the reconciliation has ended; the result carries the reset's time in redis.unacknowledged_reset. While the detecting worker runs, it checks the record after each heartbeat: if a later loss that no node detected removed it, it writes it again (StoreResetRecordRestored, 4321, Warning), and once it finds the reset acknowledged it stops (StoreResetAcknowledged, 4322). The store keeps one record: a later reset replaces it, and an acknowledgement covers every reset recorded before it. A first marker on a new server records nothing.

While a reset is unacknowledged, the dashboard's Overview page shows it in a warning banner with its time and what may have been lost. Check those settings and set again what you still need, then press Acknowledge on the banner and confirm; the button needs operate permission, and a viewer sees the banner without it. The JSON API reads the record at GET {path}/api/store/reset, which answers {"reset": null} for none, or the reset's resetAt, acknowledged and acknowledgedAt, and acknowledges it with POST {path}/api/store/reset/acknowledge and the body {"resetAt": "..."}, the resetAt as read, so a reset recorded after you looked is not acknowledged unseen: that call answers 409 and nothing changes, 404 when no reset is recorded, and 200 with the reset when it is acknowledged, by this call or an earlier one. The dashboard's audit log names the action acknowledge store reset and the reset's time. A store that records no resets, any but the Redis store, answers {"reset": null} and refuses the acknowledgement with 409.

Jobs that were running when the store was reset keep running. While the store reconciles, a run whose record the reset erased writes it again at its next lease renewal or progress write, as Processing with its lease, queue, concurrency key, unique key and recurring occurrence, so no second job takes its concurrency slot, queue limit, unique key or overlap once claims resume (RunRecordRecreated, 4323, Warning); its history before the reset, its batch, its parent and its progress are gone. A job that took its unique key during the pause never ran, and is cancelled in the same write with reason DuplicateAfterReset (DuplicateCancelledAfterReset, 4324, Warning): enqueue it again if it is still wanted. The node raises no job event, hook or notification for that cancel; its only trace is the job's state and history, and warning 4324. A run that renews its lease after the reconciliation has ended, or once its lease has passed, gets nothing back, as any run whose lease expired. So does a run whose unique key a Processing or Failed job holds by then, as after the run's record was deleted by hand or evicted before the reset and a second job with the key was claimed: the first run to write its record again keeps the key, so two active jobs never hold one. A run that finishes after the reset without its record keeps its outcome in a minimal record, written only when the store was reset since its claim: Succeeded, DeadLettered for any failure, or Cancelled, with one transition that names the node and the reason RecreatedAfterReset (RunOutcomeRecreated, 4325, Warning, which names the state kept). A failure kept so is never retried, even though the node logs that it scheduled a retry. A success's result and the job's continuations and batch are not kept.

The check's description names only exception types, but the result carries the exception: keep the default response writer on probes that anyone can reach, since a writer that serializes the entries would publish exception messages. Each readiness probe reads the store, so restrict the probes to your orchestrator where you can (for example with RequireHost on a management port).

MinNodesAlive fails every worker node at the same moment. With Bellhop:MinNodesAlive above its default of 1, each worker node reports Unhealthy while fewer worker nodes than that have sent a heartbeat within NodeLostAfter (5 minutes). They all see the same count, so they all fail together: an orchestrator that restarts on Unhealthy restarts the whole cluster at once. Use it for alerting or readiness, never for liveness. Nodes that only enqueue (AddClient) never evaluate it, so a lost worker never takes a web API out of readiness.

The dashboard's access rules

The dashboard is protected by your application's ASP.NET Core authorization; there is no Bellhop authorization filter to write. A team without an identity provider can protect it with basic authentication against users kept in configuration instead.

  • With an authorization requirement, such as .RequireAuthorization("Admins"), the users it accepts can view every page and operate: trigger, pause and edit recurring jobs, requeue dead letters, and pause and resume queues. Once permission policies, roles or claims (below) decide the levels, the requirement still has to pass but grants no level of its own.
  • With separate view and operate policies, viewers see everything and only operators change anything:
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("JobsViewers", policy => policy.RequireRole("Support", "Admins"));
    options.AddPolicy("JobsOperators", policy => policy.RequireRole("Admins"));
});
app.MapBellhopDashboard("/jobs").RequirePermissionPolicies("JobsViewers", "JobsOperators");
  • By role or claim, without writing policies (DashboardPermission is in Bellhop.Dashboard.Security): each .RequireRole(...) grants its level to signed-in users in any of its roles, and each .RequireClaim(...), such as .RequireClaim(DashboardPermission.Operate, "scope", "jobs.operate"), to signed-in users with that claim (.RequireClaim(DashboardPermission.View, "scope"), with no values, accepts any value). The calls add up: a user needs any one of them, not all, and gets the highest level among those they hold, operate including view. A rule that needs a role and a claim together is a policy for .RequirePermissionPolicies(...). Here Support views and Admins operate:
app.MapBellhopDashboard("/jobs")
    .RequireRole(DashboardPermission.View, "Support")
    .RequireRole(DashboardPermission.Operate, "Admins");
  • Roles and claims match as on your other endpoints: values case-sensitively, claim types in any case, as ASP.NET Core's own RequireRole and RequireClaim do.
  • A signed-in user with none of them is refused with 403, or views where .AllowAnonymous() lets anonymous requests view; an anonymous request gets your scheme's challenge.
  • Next to .RequireAuthorization(...), every request must still pass that policy. So .RequireAuthorization("Admins").RequireRole(DashboardPermission.View, "Support") lets only Admins who are also in Support view, and nobody operate; the node warns about it when it starts (event 3016) unless the dashboard is .ReadOnly(). Next to .RequirePermissionPolicies(...), each policy, role and claim grants its own level.
  • .ReadOnly() refuses every operate action, whoever asks.
  • Outside Development the application does not start with a dashboard that has no authorization requirement, such as .RequireAuthorization(...) or .RequireBasicAuth(), unless you call .AllowAnonymous(), which lets anonymous requests view it but never operate. A dashboard protected only by the host's fallback policy can be viewed, never operated.
  • In Development, a dashboard with no requirement is open: anonymous requests can operate when the request's host name is a loopback name (localhost or a name under it, or a loopback address such as 127.0.0.1 or [::1]), and only view otherwise; with a fallback policy it is view-only for requests that pass it. The host-name rule protects browsers against DNS rebinding; it does not stop another machine, which can send any host name. So keep a Development application bound to loopback, or give its dashboard a requirement, and never run a reachable deployment in the Development environment. The node logs which rules it applies when it starts.

View shows every job's arguments, parameters and failure stack traces. Allow anonymous viewers only where everyone who can reach the dashboard may see that, and keep secrets and personal data out of job arguments: pass ids, as SendWelcomeEmail(UserId) does.

Every page holds a Server-Sent Events stream open for live updates, and a job's page and the nodes page hold a second one, so an open tab holds one connection, or two on those pages. Browsers allow only six connections to one origin over HTTP/1.1, so serve the dashboard over HTTP/2 (Kestrel and most proxies do over HTTPS) if operators keep many tabs open.

Basic authentication

For a team without an identity provider, .RequireBasicAuth() signs users in with a name and a password kept, as a hash, in configuration:

app.MapBellhopDashboard("/jobs").RequireBasicAuth();

The node reads the users from the Bellhop:Dashboard:BasicAuth section when it starts. MaxFailedLogins and LoginLockoutWindow are shown with their defaults (option reference):

{
  "Bellhop": {
    "Dashboard": {
      "BasicAuth": {
        "Users": [
          { "Name": "alice", "PasswordHash": "$pbkdf2-sha256$i=600000$<salt>$<hash>", "Permission": "Operate" },
          { "Name": "support", "PasswordHash": "$pbkdf2-sha256$i=600000$<salt>$<hash>" }
        ],
        "MaxFailedLogins": 5,
        "LoginLockoutWindow": "00:15:00"
      }
    }
  }
}

Make each hash with DashboardPasswordHash.Create from the Bellhop.Dashboard package. A .NET 10 file-based program does it: save these lines as hash-password.cs, with #:package Bellhop.Dashboard@*-* as its first line, run dotnet run hash-password.cs, and type the password. The terminal shows it as you type, but it stays out of the shell's history.

var password = Console.ReadLine() ?? throw new InvalidOperationException("Type the password, then press Enter.");
Console.WriteLine(Bellhop.Dashboard.Security.DashboardPasswordHash.Create(password));
  • A user has a name, a hash and a permission. The name is what the user signs in with, matched exactly, and what the audit log records for the user's actions: 1 to 64 ASCII letters, digits, ., _, - and @, starting with a letter or digit, with no two names differing only in case, and neither anonymous nor unnamed. The permission is View or Operate; a user given none can only view, and where no user can operate the node warns when it starts (event 3025) unless the dashboard is .ReadOnly(). .RequireBasicAuth(options => ...) can change the options after they are read from configuration.
  • The hash is salted PBKDF2-HMAC-SHA256 with at least 600,000 iterations, in the form $pbkdf2-sha256$i=<iterations>$<salt>$<hash> that DashboardPasswordHash.Create writes. The application does not start with a plain-text password, an Argon2 or PBKDF2-HMAC-SHA1 hash, fewer iterations, or more than 10,000,000, which would make every sign-in slow: the message names the user and shows how to make the hash, and never shows what was configured. It does not start without users either, or with a user whose name or permission is not valid.
  • Keep the hashes as secrets, in user secrets while you develop and your host's secret store in production. A hash cannot be turned back into its password, but whoever holds it can guess passwords offline at their own pace, so choose long passwords.
  • Failed sign-ins lock out a user name, or a client address. After MaxFailedLogins failures within LoginLockoutWindow, 5 within 15 minutes by default, for one user name from any address, or from one address for any names, that name or address is refused for the next LoginLockoutWindow, even with the right password. A refused attempt is not counted and does not extend the lockout, and a successful sign-in does not clear earlier failures. A name that is no user's is counted like a user's, and a name and password that cannot be read count against the address. Sign-ins whose passwords are still being checked count towards the limit too, so a burst of different guesses at once gets no more checks than the limit allows, and the rest are refused without being counted; sign-ins at once with the same name and password, such as a browser's requests for one page, share one check. A node checks at most one password per processor at once, for all its dashboards together, so a flood of guesses cannot take every core from the node's jobs: a sign-in that finds no free check within 2 seconds is refused with the same 401 and is not counted, so during such a flood users may have to sign in again once it passes. Each node tracks up to 100,000 names and as many addresses; when either is full of recent failures, it counts no new ones until some expire, and logs event 3024. IPv6 addresses are counted by their /64 prefix, which one host usually holds whole. The node logs each lockout as event 3023, naming the user, or the address; never a name that is no user's, which may be a mistyped password. Anyone who knows a user's name can lock the user out this way for a while; API keys keep working.
  • Every refused sign-in gets the same answer: 401 with the challenge WWW-Authenticate: Basic realm="Bellhop dashboard", charset="UTF-8", so a browser asks for the name and password again, whether the name is unknown, the password wrong or the user locked out. Event 3003, at Debug, says why. A user with view permission who tries to operate is answered 403.
  • Each node counts on its own, in memory, and forgets the failures when it restarts. Behind a load balancer that spreads requests over N nodes, a guesser gets up to N × MaxFailedLogins tries per window.
  • Behind a reverse proxy, configure ASP.NET Core's forwarded headers middleware with your proxies, so the dashboard sees each client's own address; otherwise every request comes from the proxy's address, and one guesser locks everybody out.
  • Serve the dashboard over HTTPS only. The browser sends the password, merely encoded, with every request. There is no sign-out: the browser keeps the name and password until it is closed. Checking a password costs a few hundred milliseconds of CPU, so the node remembers a password it verified for 5 minutes, as a keyed digest in memory, and a browser's further requests do not pay it again.
  • It is the dashboard's only authorization requirement. Outside Development the application starts with it, in Development it does not open the dashboard to anonymous requests, and it needs no AddAuthorization(); the host's fallback policy does not apply to the dashboard. Combined with .RequireAuthorization(...), .RequirePermissionPolicies(...), .RequireRole(...) or .RequireClaim(...), the application does not start. .AllowAnonymous() still lets requests that send no name and password view, never operate, and .ReadOnly() refuses every operate action to users too. With .RequireApiKey(), a request with a key is judged by the key alone: keys never count towards a lockout and are never locked out.

API keys for scripts

Scripts, CI jobs and the CLI call the dashboard's JSON API with an API key, created on the dashboard by an operator. Add .RequireApiKey() to the dashboard:

app.MapBellhopDashboard("/jobs")
    .RequireRole(DashboardPermission.Operate, "Admins")
    .RequireApiKey();

An Admin then opens API keys, gives the key a name (lowercase letters, digits, ., _ and -, up to 64 characters), a scope, view or operate, and an expiry: 90 days unless another date, or never, is chosen. The dashboard shows the key once, bellhop_ and 64 hexadecimal digits; store it in the script's secret store at once, as the dashboard keeps only its SHA-256 hash and cannot show it again. The JSON API does the same with POST /jobs/api/keys/create, and POST /jobs/api/keys/revoke revokes one. A script sends its key in the Bellhop-Api-Key header:

using var request = new HttpRequestMessage(HttpMethod.Get, "queues");
request.Headers.Add("Bellhop-Api-Key", apiKey);
using var response = await http.SendAsync(request, ct);
response.EnsureSuccessStatusCode();
var queues = await response.Content.ReadAsStringAsync(ct);
  • A key authenticates with its scope and the principal apikey: followed by its name, which the audit log records for every action it performs. It never creates or revokes a key, whatever its scope: only an operator does that, on the dashboard, so a leaked key cannot make more.
  • A revoked or expired key, or one never issued, is answered 401 from the moment it is revoked or its expiry passes, on every node: each request with a key reads it from the store, with nothing cached. A live-update stream (GET /jobs/api/events) opened with a key ends at the key's expiry; one open when the key is revoked ends at its next reconnect, within 5 minutes, as a stream does after a sign-out. Failed keys are never counted and a key is never locked out; a key's 256 random bits are what makes guessing one infeasible.
  • A key works only on the dashboard it was created on. Another dashboard of the application, or one mapped at another path, refuses it with 401, does not list it and cannot revoke it. Map the dashboard at the same path on every node. Moving a dashboard to another path leaves its keys behind: they stop authenticating, no dashboard lists or revokes them, and their names stay taken. Create new keys on the moved dashboard, or map it at the old path again to manage the old ones.
  • Names are never reused. To rotate a key, create one with a new name, move the script to it, then revoke the old one; several keys can be active at once.
  • .RequireApiKey() protects nothing. It adds a way in for scripts; requests without a key are judged exactly as before, so outside Development the dashboard still needs an authorization requirement, such as .RequireBasicAuth(), or .AllowAnonymous(). A .ReadOnly() dashboard refuses every operate action to keys too. Without .RequireApiKey(), a request that sends the header is answered 401.
  • Restoring the store from a backup brings back the keys as they were then: a key revoked after the backup was taken authenticates again. Revoke such keys again after a restore. A Redis flush removes every key.

The dashboard's lists

Every list the dashboard shows is read a page at a time, so a page costs the same however many jobs, queues, nodes or keys the store holds. A client cannot ask for a larger page than these:

List JSON API One page
Jobs and dead letters GET /jobs/api/jobs limit, 1 to 100, 50 by default
Recurring jobs GET /jobs/api/recurring 100
A recurring job's occurrences GET /jobs/api/recurring/history the newest 50, not paged further
Queues GET /jobs/api/queues 100
Nodes GET /jobs/api/nodes and its stream, GET /jobs/api/nodes/events 25
Worker nodes on the overview GET /jobs/api/overview the first 25 by id of those with a heartbeat in the last 24 hours
Tags GET /jobs/api/tags 100
Throttles GET /jobs/api/throttles 100
API keys GET /jobs/api/keys 100
Launches GET /jobs/api/launches the newest 100, not paged further
Notification deliveries GET /jobs/api/notifications the newest 50, and the newest 50 failed

A paged answer carries next; pass it as after to read the following page, and it is null on the last one. The pages have First page and Next page links, and the page's after in their address. A record kept while a client pages through is listed once; one added or removed meanwhile may or may not be. The API keys page reads only the keys created on its own dashboard, so no page or next names another dashboard's key. The nodes page reads only the nodes seen in its 24 hours, so a page is never short while more follow.

A page of the jobs list walks the index of one filter it gives and stops once the page is full, except for a creation time range given alone. On PostgreSQL, SQL Server and SQLite such a page reads every job created in the range, below the page's after, and sorts them, however few it shows: a day's range reads that day's jobs, and a broad one, such as everything created before yesterday, nearly the whole table, again for each page. Add a state, name, queue or parent to the range, and the page walks that filter's jobs instead.

The job page

A job's page stays live while it is open. It reads the job over a Server-Sent Events stream of its own, GET {path}/api/jobs/{id}/events, which the server reads from the store once per PollInterval (1 second by default), so a captured line or a progress report shows within one interval of being stored, also when the job runs on another node. Where the browser has no EventSource, a proxy refuses or buffers the stream, or nothing arrives within 10 seconds, the page reads GET {path}/api/jobs/{id} every 2 seconds instead. When the job is deleted or removed by retention, the page says the job is not found.

The search box above the captured log shows only the lines that contain its text, in any letter case, in their message, category, property names and values, or exception. It runs in the page, over every captured line of the job, which the page holds whole (a log is at most CapturedLogLimit, 256 KB by default), including the lines that arrive while it is open. Lines are masked before they leave the server, so searching for a [Sensitive] value finds nothing.

The jobs list shows each job's progress as a bar with its percentage, and reads its page again every 2 seconds while it shows a processing job. A list shows only the fraction; the progress message is on the job's page, masked with the job's own values.

The Relations section shows the job's direct relations: its parent, and whether the job continues it (on success, on failure or on completion) or was created by it; its batch, as one node with its name, state and member count, however many members it has; and its first 50 children, with a link to the jobs list filtered by parent for the rest. Each job shows its state, which updates while the page is open. A parent or batch that is no longer stored shows its id. The rest of a chain is a link away, on the parent's or a child's page.

AddJobLink<TJob>(text, url) puts a link on the page of each job of a type, to a page of the application's own. The function computes the URL from the job, read from its payload. Here each order review links to its order:

[JobName("review-order")]
public sealed record ReviewOrder(Guid OrderId, [Sensitive] string CardToken) : IJob;

public sealed class ReviewOrderHandler : IJobHandler<ReviewOrder>
{
    public Task HandleAsync(ReviewOrder job, JobContext ctx, CancellationToken ct) => Task.CompletedTask;
}
builder.Services.AddBellhop(bellhop => bellhop.AddJob<ReviewOrder, ReviewOrderHandler>());

var app = builder.Build();
app.MapBellhopDashboard("/jobs")
    .RequireAuthorization("Operators")
    .AddJobLink<ReviewOrder>("Open the order", job => new Uri($"https://shop.example/orders/{job.OrderId}"));
  • Only an absolute http or https URL is shown. A function that returns null shows no link.
  • A function that throws, or a payload that cannot be read, shows no link and logs event 3017. A URL that is not http or https, that depends on a [Sensitive] member, or that contains text equal to the value of one, shows no link and logs event 3018, which never quotes the URL. The rest of the page is shown either way. A link is computed on every view of a job's page, so each event is a warning the first time for a job type and cause, and again at most once a minute, and at Debug in between.
  • Lists show no links, and HTTP jobs get none.
  • The node that serves the dashboard reads the payload, so it must register the job type with AddBellhop, also when it runs no worker. AddJobLink throws for a type the node does not register, for the built-in HTTP job, for a second link to one type on one dashboard, and once the host has started.

For a job type with [Sensitive] members, such as ReviewOrder's CardToken, the function runs twice: with the job as stored, and with those members at their defaults, null even where the type does not allow it. The link is shown only when both calls give the same URL, so no [Sensitive] value reaches a link, in any encoding. This fails closed:

  • A function that reads a [Sensitive] member for anything, even its length in a guard, shows no link (event 3018).
  • A URL that changes from call to call, such as one with a nonce or a timestamp, is never shown.
  • Side effects of the function run twice.
  • When the function throws, event 3017 logs only the exception's type, as its message could quote a [Sensitive] value.
  • A job that cannot be read without its [Sensitive] members, such as one whose member is required, shows no link (event 3018).
  • The URL is also searched for the text of each [Sensitive] value, so a short value, such as a two-digit number, refuses a URL that holds the same digits by chance.
  • Where the function branches on a [Sensitive] member, whether a link shows can tell a viewer whether that member holds its default.

So compute the URL from the job's other members, the same way on every call, and without side effects.

Proved by JobEventsTests.ALineAHandlerWritesOnAWorkerNode_ReachesADashboardOnlyNodesStream_OnePollIntervalAfterTheStoreHoldsIt, JobEventsTests.AStreamThatCannotOpen_AnswersExactlyAsTheJobsDetail_BeforeAnyStreamByte, JobPageBrowserTests.WhileThePageIsOpen_ALineWrittenAndAProgressReported_ShowWithoutAReload, JobPageBrowserTests.TheSearch_ShowsOnlyTheLinesContainingTheText_WithoutCase_InTheirMessageCategoryPropertiesOrException_AndSaysHowMany, JobPageBrowserTests.SearchingForAnUnmaskedSensitiveValue_FindsNothing_WhileTheLineShowsTheMaskInItsPlace, JobsPageBrowserTests.AJobWithProgress_ShowsABarAtItsFractionWithThePercentage_AndAJobWithoutShowsNone, DashboardJobsTests.EverySummary_ShowsOnlyTheProgressFraction_AndNullWithout_WhileTheDetailShowsItsWholeReportOnce, DashboardJobsTests.TheDetail_ShowsEachJobsConditionParentAndBatch_AndNoJobItIsNotRelatedTo, JobPageBrowserTests.TheRelations_ShowTheParentAndBatchAboveTheJob_AndItsChildrenBelow_EachWithItsState_AndNoOtherJob, JobPageBrowserTests.ARelatedJobsStateChange_ShowsInTheGraphWithoutAReload, JobLinkTests.JobsOfALinkedType_LinkWhereEachComputes_UnderItsNameOrAnAlias_WhileOtherTypesHttpJobsAndListsShowNone, JobLinkTests.AUrlThatIsNotAnAbsoluteHttpOrHttpsUrl_ShowsNoLink_AndIsRefusedWithAReason_ThatNeverQuotesIt, JobLinkTests.AUrlThatDependsOnASensitiveValue_InAnyForm_OrChangesFromCallToCall_ShowsNoLink_AndIsRefused_WithoutLoggingTheFunctionsException and JobLinkTests.AFunctionThatThrowsQuotingASensitiveValue_ForATypeWithMarkedMembers_IsWarnedOfWithItsTypeOnly_AndTheValueIsLoggedNowhere.

The nodes page

The nodes page lists the nodes of the application's namespace that sent a heartbeat or took a metrics sample in the last 24 hours, 25 a page by node id, with their latest figures and a chart of each over those 24 hours, in five-minute steps. A node id is new at each start, so a node that stopped drops off the page a day later. A page is found without reading the samples: one probe of the store per node that holds samples, up to the page's last, and the nodes whose heartbeat is within the 24 hours; then the page's own nodes' samples are read.

  • Samples. Every running node, with or without the worker, takes a sample of itself every NodeSampleInterval (15 seconds by default) and writes it in one store write: the share of the machine's processor time its process used over the interval, its working set, its GC heap after the latest collection and the thread pool's queue length; on a node with the worker also its jobs in flight, its concurrency, and its utilisation, the share of its slots that held a job over the interval. A node writes samples whether or not anyone views the dashboard, and whether or not it maps one, from when it is running until it starts to stop. A sample whose write fails is dropped and logged (NodeSampleWriteFailed, 1149); the chart shows the gap.
  • Heartbeats. Only nodes with the worker send heartbeats, so a node with a heartbeat is shown alive, lost (no heartbeat for NodeLostAfter) or stopped, with its concurrency and utilisation. A client-only or dashboard-only node is listed from its samples alone, as "No worker".
  • Live. The page reads the nodes over a stream of its own, GET {path}/api/nodes/events, which the server reads from the store once per NodeSampleInterval; where streams do not work it reads GET {path}/api/nodes as often instead. Each update reads the page's nodes' whole day of samples, about 5,760 per node at the default interval, for each open page, so keep the page closed when you are not using it, and do not lower NodeSampleInterval for the page alone.
  • Retention. Worker nodes remove samples taken more than NodeSampleRetention ago (7 days by default) with retention cleanup, about once a minute. While no worker node runs, no sample is removed. Sample times are each node's own clock. At the defaults the store keeps about 40,000 samples per node, a row each on the SQL stores and an entry in one hash and one sorted set per namespace on Redis; a 1-second interval keeps fifteen times as many. An application whose nodes all run without the worker, such as one on the in-memory store, never removes its samples.

The tags and throttles pages

The Tags page lists each tag a stored job carries, 100 at a time, with how many jobs carry it, how many of those succeeded and how many failed, meaning were dead-lettered; a job awaiting a retry, a cancelled job and a job in any other state count in neither. The counts are read when the page opens, after each of its actions and on Refresh, not live as jobs change, since a read counts the outcomes of every job of the page's tags; they are over the jobs still stored, so deleting jobs and retention lower them, and a key:value tag is one tag. Selecting a tag opens the jobs list filtered by it.

  • Bulk actions. An operator requeues, cancels or deletes the jobs with a tag, as IJobClient does for one job: a requeue takes succeeded, dead-lettered and cancelled jobs; a cancel takes every job that has not finished, and asks a processing one to stop; a delete takes every job that is not processing. One run reads the tag's jobs once, at most 1000 of them, and gives each its own atomic step, so a job tagged after the run starts is not touched, and one whose state changed meanwhile is skipped. The answer says how many jobs were changed and how many skipped, and how many of those a requeue left because another active job holds the unique key. With more than 1000, the page offers to go on with the rest. A run cut off midway leaves each job whole or untouched and is logged: a store failure as TaggedJobsActionFailed (2487, Error), a client that went away or the host stopping as TaggedJobsActionStopped (2488, Warning); running it again is safe. The JSON API does the same with POST /jobs/api/tags/requeue, cancel and delete.
  • Throttles. The Throttles page lists each key with a concurrency Max or a rate limit, and each concurrency key a processing job holds, 100 at a time: its Max, its rate limit, how many jobs of every namespace on the store hold it, this namespace's holders (up to 20) and waiting jobs, and when the longest-waiting of them started waiting. No history of past waits is kept. The page follows the jobs live at most every 15 seconds, as each read counts every listed key's holders and waiting jobs; a limit changed from it shows at once. A concurrency key with no setting and no holder is not listed, however many jobs wait for it: set its Max from the form below the list. On Redis, the page reads sets the store keeps per key, never the jobs themselves. On SQL Server, the read passes over the jobs other sessions lock at that moment (READPAST), so a key held only by a job whose row is locked then can be missing from one read, and its running count can be lower than the jobs that hold it.
  • Changing a limit. An operator sets or removes a key's Max or rate limit, which IThrottleManager stores, so it holds for the next claim on every node and through restarts and redeploys until it is changed again; an application that sets the limit in code when it starts overwrites it, and on Redis a store reset loses it. Jobs already running are never stopped by a lower limit. The JSON API takes POST /jobs/api/throttles/max with { "key": "reports", "max": 3 } (null removes it) and POST /jobs/api/throttles/rate with { "key": "mail", "limit": 100, "window": "00:01:00", "kind": "sliding" } (only the key removes it).

Launching jobs

The dashboard's Launch page creates a job of any type the node serving the dashboard registers with AddBellhop (AddJob, AddJobsFromAssemblyContaining or AddHttpJobs): every registered type is offered, with no attribute or switch to opt in. Launching is an operate action: a viewer sees the page but cannot launch, and a .ReadOnly() dashboard refuses every launch. A node that maps only the dashboard launches too, since the dashboard writes through the store and a worker on the same store runs the job; it must still register the job type, as the form is built from it.

The form comes from the payload record and its DataAnnotations:

public enum ReportFormat
{
    Pdf,
    Csv,
}

[JobName("send-report")]
public sealed record SendReport(
    [Display(Name = "Report title")][Required][StringLength(80)] string Title,
    [Display(Name = "Send to")][Required][EmailAddress] string Recipient,
    [Range(1, 10)] int Copies,
    ReportFormat Format,
    DateTimeOffset? NotBefore,
    [Sensitive] string? ShareToken) : IJob;
  • Labels and rules: [Display] gives a field its label and description; [Required], [Range], [StringLength], [MinLength], [MaxLength] and [Length] its rules; [DataType], [EmailAddress] and [Url] the kind of input (date, time, email, URL, password or multi-line text); [Sensitive] a password input. Attributes on a positional record's parameters count as on its properties.
  • Shapes: an enum is a choice of its values; a DateTimeOffset is a date, a time and a time zone, sent with that zone's offset; a DateTime is sent without an offset; a nullable field can be left empty; a nested record is a group of fields; a collection has items to add and remove. A dictionary, or a shape the form cannot show, is a JSON field.
  • The schema is the type's JSON schema (draft 2020-12), from the System.Text.Json metadata of the node's serializer, at GET /jobs/api/launch. With a JsonSerializerContext, include every job type in it: a type it leaves out is launched from JSON text (Debug event 3019).

An operator chooses how to launch:

  • Run now enqueues the job.
  • Schedule for schedules it for a date and a time in an IANA time zone, such as Europe/Berlin, or UTC. A time the zone skips at a daylight-saving change runs at the end of the gap, and a time it repeats at its first instance, as recurring jobs read them. A time that is not later than now is refused: choose Run now instead.
  • Make recurring adds a runtime-defined recurring job with a name, a schedule (a cron expression, or @every and an interval), and UTC or local time in a zone. Every policy takes its default, and the next run is computed from now; the schedule's next five runs show while it is typed (see the schedule preview). A name already used in code, configuration or at runtime is refused, and nothing changes; edit, pause and trigger it from the recurring page.

The server decides. It reads the payload with the node's serializer and checks every DataAnnotations rule, on each field, in nested records, in the items of collections and in the values of dictionaries, before anything is created, so a script that posts to POST /jobs/api/launch directly gets the same answer as the page: 400 with errors, each refused field's path with why, and nothing created. Rules on a type rather than a field, and IValidatableObject, are not run. A value the check cannot reach is refused rather than accepted unchecked: one nested deeper than 64 levels, or in a dictionary that is not a non-generic IDictionary. Where a rule, a label or a collection throws while the payload is checked, the answer is 400 with a fixed text, logged as warning 3021. No answer or log message quotes a value of the payload: a field's error, [Sensitive] or not, is the rule's error message template filled with the field's name and the rule's own settings, and the audit log names the job type and what was created. A custom rule that builds its message from the value in IsValid is shown with its template instead, since that message could quote the value. Where the node's serializer throws over a payload, the answer is 400 with a fixed text, warning 3021 names the exception's type, and Debug event 3022 carries the exception, whose message could quote the payload; a refusal by the core or the application's enqueue middleware (NotValid) is logged the same way, as its message could also quote a value. An HTTP job that carries credentials, in an Authorization, Proxy-Authorization or Cookie header or in its URL, is refused like one created in code; put them on a named HttpClient registration. A payload larger than PayloadHardLimit is refused with 413.

A script launches with an operate API key:

{ "jobName": "send-report", "mode": "schedule", "date": "2026-12-24", "time": "09:00", "timeZone": "Europe/Berlin",
  "payload": { "Title": "Year end", "Recipient": "finance@example.com", "Copies": 1, "Format": 0 } }

The payload's property names are the ones the node's serializer writes, as the schema gives them.

Who launched what. A job launched from the dashboard carries the parameter Bellhop.LaunchedBy (JobParameters.LaunchedByKey), the launcher's principal name as a JSON string: the signed-in user's name, apikey: and the key's name, or anonymous on an open Development dashboard. Enqueue middleware sees it in ctx.Parameters, and the job's page shows it with the other parameters. A recurring job has no parameters, so its runs do not carry it; its launch record keeps the name. The page lists the newest 100 launches, with who launched which job or recurring job, and when, from every node and dashboard over the store; the store keeps the newest 1000 of each namespace. A launch stays listed after its job is deleted or removed by retention, and a refused launch is never listed. When the store cannot record a launch, the launch is made all the same, the answer says it was not recorded, and the node logs warning 3020.

A replaced client or manager. Launches, and the tags page's requeue, cancel and delete, always go through Bellhop's own client and recurring job manager: an application that registers its own IJobClient or IRecurringJobManager, such as a decorator that applies a policy, is not called for a launch or a bulk action by tag. Put such a policy in enqueue middleware, which Run now and Schedule for run, or in the payload's validation rules. The dashboard's other actions use the application's replacement where it registers one: requeueing dead-lettered jobs goes through its IJobClient; triggering, pausing and resuming a recurring job go through its IRecurringJobManager, and editing a recurring job's schedule is refused while it is replaced; changing a limit on the throttles page goes through its IThrottleManager.

Custom launch editors

Where the generated form does not suit a type, AddLaunchEditor<TJob>(modulePath) replaces it with an editor of the application's own, a JavaScript module the application serves on the dashboard's origin:

builder.Services.AddBellhop(bellhop => bellhop.AddJob<SendReport, SendReportHandler>());

var app = builder.Build();
app.UseStaticFiles();
app.MapBellhopDashboard("/jobs")
    .RequireAuthorization("Operators")
    .AddLaunchEditor<SendReport>("/js/send-report-editor.js");
  • The module default-exports mount(element, context). The page calls it with the element to render into and a context of jobName, schema (the payload's JSON schema, or null), value (the payload so far), setValue(value), which the editor calls with the payload whenever it changes, and disabled, true when the request may not launch. mount may return a function the page calls to clean up. Where the module fails to load, the page says so and shows the generated form.
  • The path is on the dashboard's origin: it starts with /, not //, and holds no white space. The dashboard's content security policy runs scripts from its own origin only, and the module runs with the operator's rights, so serve it from the application, never from a place users can upload to.
  • The rules still hold: the editor's payload goes through the same POST /jobs/api/launch, which the server checks as any other.
  • Other types keep the generated form. AddLaunchEditor throws for a type the node does not register, for a second editor of one type on one dashboard, and once the host has started.

Proved by DashboardLaunchTests.TheLaunchPage_OffersEveryRegisteredJobType_ByName_WithTheSchemaOfItsPayload, DashboardLaunchTests.Olga_LaunchesSendReportWithRunNow_AndOneJobIsEnqueuedWithHerNameAndTheValues_ListedInRecentLaunches, DashboardLaunchTests.ScheduleFor_SchedulesTheJobForTheInstant_WithTheOperatorsName_AndListsTheLaunch, DashboardLaunchTests.ScheduleFor_OneInstantEnteredAsTheWallClockOfAnyZone_SchedulesTheJobForThatInstant, DashboardLaunchTests.ScheduleFor_ATimeTheZoneSkips_RunsAtTheGapsEnd_AndOneNotInTheFuture_Is400CreatingNothing, DashboardLaunchTests.MakeRecurring_AddsARuntimeRecurringJobWithThePayload_RunningFromNow_AndListsWhoLaunchedIt, DashboardLaunchTests.ValuesThatBreakThePayloadsRules_Are400WithTheErrorsAtTheirFields_AndNothingIsCreated, DashboardLaunchTests.AnHttpJobWithCredentials_IsRejectedPointingToNamedClients_AndNothingIsStored, DashboardLaunchTests.AViewer_AReadOnlyDashboard_AndAnAnonymousViewerOutsideDevelopment_CannotLaunch, DashboardLaunchTests.LaunchesByAUserAKeyAndAnAnonymousDevelopmentRequest_InEveryMode_AreListedOnBothNodes_WithThePrincipalWhatWasCreatedAndWhen, DashboardLaunchTests.ALaunchTheStoreFailsToRecord_IsStillMade_Answers200NotRecorded_AndLogsAWarning, LaunchSchemaTests.EachField_CarriesTheLabelAndRulesOfItsAnnotations_OnAPositionalParameterOrAProperty, LaunchPayloadValidatorTests.ARuleThatQuotesTheValue_IsShownAsItsTemplate_NeverEchoingTheValue_OfASensitiveMemberOrAnother and DashboardLaunchEditorTests.ARegisteredEditor_IsNamedForItsJobTypeOnly_AndEveryOtherTypeKeepsTheGeneratedForm.

Recurring jobs in the dashboard

The Recurring page lists the recurring jobs, 100 at a time by name, each with its schedule and time zone, its next five runs in that zone, its last outcome, and its misfire policy, overlap policy and validity window. Operators trigger, pause, resume and edit a job from it. Each job's name links to the job's own page, which reads the job by its name alone.

The schedule preview. While an operator types a schedule into a job's edit form, or into Make recurring on the Launch page, its next five runs show under the fields, in the chosen zone with that zone's offset at each run, so a daylight-saving change shows. The server computes them once the form has not changed for 300 ms, the way adding or editing the job computes its next run, so the preview is what saving a new or changed schedule would store; an edit that keeps the schedule keeps the stored next run instead:

  • Now is the store's clock, the one saving reads, not the browser's.
  • The validity window of the job being edited trims the preview, as the scheduler creates no occurrence outside it. Make recurring adds a job without a window, so its preview has none.
  • A refused schedule, an expression that does not read or local time without a valid IANA zone, shows the explanation saving would answer with, and no run. The preview never stops a save: the server checks what is saved again.
  • Fewer runs show when the schedule or the window has fewer left, and "The schedule has no further run." when it has none.

A recurring job's page (#/recurring/ and the job's name) shows its settings: the schedule and zone, the misfire policy (RunOnce, Skip, or RunAll with its maximum), the overlap policy (Skip, Queue with how many occurrences may wait, Allow or CancelPrevious) and the validity window, From and Until, or None. A job that sets no policy shows RunOnce and Skip. Below them are its last 50 occurrences, newest first, each with the time it was for in the job's zone, its outcome, its job and its duration:

  • Outcome. A started occurrence shows its job's result, succeeded, dead-lettered or cancelled, or the job's state while it has not finished. A skipped one says why (an overlap, a full queue, or a job paused, orphaned or removed while it waited), and a waiting one that it waits for the earlier occurrences to finish.
  • Duration is the run time of the job's latest attempt that ran: from when it entered Processing to when it left it. A retried job's earlier attempts and its waits between them are not counted. It shows once the job has finished.
  • What is kept. Occurrences are kept under the job's name and never removed, on every store, while retention removes finished jobs (after RetentionSucceeded, RetentionCancelled or RetentionDeadLettered). An occurrence whose job retention or a delete removed stays listed as "Job no longer stored", without an outcome or a duration. A removed recurring job's page says it is no longer stored and still lists its occurrences, in UTC. On Redis each refresh of the page reads only the newest 50 occurrences, through an index of their ids; the occurrences themselves still grow by one with every run, about 525,000 a year for a job that runs every minute, as on every store.

Both pages read the store again as the overview changes. The JSON API behind them, which a script can call with a view API key:

  • GET /jobs/api/recurring/preview?schedule=…&timeMode=utc|local&timeZone=…&name=… answers timeZone and up to five occurrences in that zone's offset. A refused query or schedule is 400 with the explanation in detail; name, optional, names the stored job whose window trims the runs, and is 404 when no such job is stored.
  • GET /jobs/api/recurring/job?name=… answers one job as the list shows each, read by its name alone, and 404 when no job with the name is stored.
  • GET /jobs/api/recurring/history?name=… answers the job's last 50 occurrences, newest first, each with its state, scheduledFor, jobId, skipReason, its job's jobState, an outcome (succeeded, deadLettered, cancelled, unfinished, jobRemoved, waiting or skipped), the attempt's startedAt and endedAt, and durationSeconds. The job need not be stored any more.
  • GET /jobs/api/recurring?after=… answers a page of 100 jobs and the next page's after, and gives each job's misfirePolicy, maxRunAllOccurrences, overlapPolicy, maxQueuedOccurrences, activeFrom and activeUntil too.

The OpenAPI document at /jobs/api/openapi.json describes each.

Proved by DashboardSchedulePreviewTests.ACronScheduleInBerlin_PreviewsTheNextFiveAfterTheStoresNow_InBerlinsOffset_AsTheEditAndMakeRecurringThenStoreIt, DashboardSchedulePreviewTests.ThePreview_FollowsTheExpressionAndTheZone_WithNothingSaved, DashboardSchedulePreviewTests.AcrossADaylightSavingChangeInBerlin_ASkippedTimeRunsOnceAtTheGapsEnd_AndARepeatedOneOnceAtItsFirstInstance, DashboardSchedulePreviewTests.AnInvalidScheduleOrLocalTimeWithoutAValidIanaZone_PreviewsNothing_AndIs400SayingWhatIsWrong_AsTheEditAndTheLaunchAre, DashboardSchedulePreviewTests.AStoredJobsValidityWindow_TrimsThePreview_ToFewerThanFive_AndNoneOnceItHasPassed_NeverMoreThanFive, DashboardRecurringHistoryTests.OfSixtyOccurrencesInEveryState_TheFiftyNewestAreShownNewestFirst_EachWithItsOutcomeJobAndTheLastAttemptsRunTime, DashboardRecurringHistoryTests.AJobWithSevenOccurrences_ShowsAllSeven_NeverAnotherJobs_AndKeepsThemOnceTheJobIsRemoved, DashboardRecurringHistoryTests.TheList_ShowsEachJobsMisfireAndOverlapPolicies_WithTheirMaxima_AndItsValidityWindow, DashboardNodeRegistrationTests.OnEachRegistrationOfTheDashboardNode_ThePreviewMakeRecurringTheEditAndTheHistory_WorkThroughTheStore_AndShowWhatAWorkerHostRan, SchedulePreviewBrowserTests.TheEditFormsPreview_FollowsTheExpressionAndTheZone_AndShowsTheServersProblem_WithNothingSaved, SchedulePreviewBrowserTests.MakeRecurringsPreview_FollowsTheExpressionAndTheZone_AndShowsTheServersProblem_WithNothingSaved, RecurringJobPageBrowserTests.ThePage_ShowsTheSettings_AndTheOccurrencesNewestFirst_WithOutcomeJobAndDuration_AndShowsANewOneAsItComes and RecurringJobPageBrowserTests.TheJobsNameOnTheRecurringPage_OpensItsPage_WhichShowsDefaultsAndNoOccurrence_AndAJobNoLongerStoredSaysSo.

PostgreSQL

  • Bellhop keeps its tables in a schema of its own, bellhop by default (UsePostgres(connectionString, options => options.Schema = "jobs") changes it), and nothing outside it.
  • While Bellhop:AutoMigrate is on, its default, the first node to start creates or upgrades the schema, under a lock so that nodes starting together migrate it once. To have a DBA apply changes instead, turn it off and give them the script from BellhopSchema.GetScript(BellhopSchema.Postgres, fromVersion).
  • With Bellhop:AutoMigrate off, the nodes' role needs no more than USAGE on the schema, SELECT, INSERT, UPDATE and DELETE on its tables, and USAGE on its sequences, which give jobs their ids, enqueue order and lease tokens. Migrating needs the right to create objects in the schema as well.
  • The connection string comes from configuration, never from code: user secrets while you develop, your host's secret store or environment variables in production. Bellhop never logs it.
  • Bellhop's SQL uses nothing newer than PostgreSQL 12. The test suite runs against PostgreSQL 18 by default.
  • The store wakes idle nodes through LISTEN/NOTIFY on its own connection. UseRedisNotifications (Bellhop.Redis) adds wake-ups through Redis, as the SQL Server section describes; it is meant for stores without their own, but works here too.
  • Leave the database's default_transaction_isolation at read committed, PostgreSQL's default. A continuation is resolved by a second statement in its parent's write, which must see a continuation added while that write waited; under repeatable read it would not, and the continuation would keep awaiting. A batch is moved the same way, by a statement that must see the other members that finished while its member's write waited for the batch.
  • Upgrade every node before using continuations or chains (ContinueWithAsync, ChainAsync). A node of the release before keeps working on the new schema, but when it finishes or cancels a job it does not resolve that job's continuations, which then keep awaiting until an operator cancels them.
  • Apply the schema's job results (version 8) before any node of this release runs jobs, with Bellhop:AutoMigrate on or by your DBA's script. On version 7 such a node's requeues fail, and so does every success of a job that returns a result. A node of the release before keeps working on version 8, but a job it requeues keeps its earlier result, which GetResultAsync then returns again once the job succeeds on that node, since that node stores no new one.
  • Upgrade every node before creating batches (CreateBatchAsync). A node of the release before keeps working on the new schema, but it never moves a batch: when it finishes, cancels or deletes a member, the batch stays open and its batch continuations keep awaiting, even once every member has finished, until an operator cancels them. It also deletes or removes a job without cancelling the job's awaiting continuations.
  • With Bellhop:AutoMigrate off, apply every migration up to the dashboard launches (schema version 19) before you start a node of this release: it refuses to start on any earlier version, since every statement it runs on a job reads or writes the columns of versions 12, 13 and 15, every one on a notification delivery reads those of version 14, its heartbeats, failed attempts and alerts write those of version 16, a dashboard that requires API keys reads the keys of version 17 on every request that presents one, every running node writes a metrics sample of itself to version 18's table every interval, and a dashboard records every launch in, and lists the recent ones from, the launches of version 19. Its script from BellhopSchema.GetScript(BellhopSchema.Postgres, fromVersion) takes the schema from any earlier version to the newest, 20, in one run.
  • Version 17 adds the api_keys table and changes no other table. A node of the release before keeps working on it, as it never reads or writes a key.
  • Version 18 adds the node_samples table and changes no other table. A node of the release before keeps working on it, as it never reads or writes a sample.
  • Version 19 adds the launches table and changes no other table. A node of the release before keeps working on it, as it never reads or writes a launch.
  • Version 20 adds indexes of jobs, job_transitions, nodes, recurring_jobs and api_keys and changes no table. A node of the release before keeps working on it, and a node of this release also runs on version 19, where retention cleanup removes the same jobs but reads every finished job's history on each run, once a minute on every worker node, the dashboard's jobs list, dead letters and overview counts read the whole jobs table when a filter matches fewer jobs than a page, its pages of nodes and recurring jobs read past the other namespaces' rows, and its page of API keys and the marking of expired keys read every key of the namespace. Building the indexes blocks writes to jobs and job_transitions, and so every job created and every change of a job's state on the running nodes, until they are built, and briefly the heartbeats and recurring job writes. On a large table apply it when the load is low. The five new indexes of jobs are written on every job created and every change of a job's state, which adds to the cost of each claim and finish.
  • Version 15 adds each job's latest progress and its captured log's size and truncation mark as columns of jobs, with defaults, so no table is rewritten, and the job_log_lines table. A node of the release before keeps working on it: it never writes or reads a job's log or progress, and deleting a job or removing it by retention still removes the job's log lines, through the table's cascading foreign key.
  • Building the index of job_index by job id (version 10) blocks writes to job_index while it runs, so deletes and retention cleanup on the nodes of the release before that are still running wait for it. On a large table apply it when the load is low.
  • A node of the release before keeps working on versions 12 and 13, but the jobs it creates carry no tags or correlation id, so the dashboard's tag and correlation-id filters do not find them; upgrade every node before relying on those filters.

  • Applying version 13 adds the namespace columns without rewriting any table, but it rebuilds the unique-key index and builds a claim index over every waiting job, holding a lock on jobs while it does: claims, renewals and finishes of running nodes wait until it commits, and long-running ones can lose their lease. On a large table apply it when the load is low.

  • Applying version 16 adds its columns without rewriting any table, but it runs in one transaction, so the locks its ALTER TABLE statements take on jobs, job_transitions, recurring_misses and nodes are held until it commits, through every index it builds on them: every read and write of those tables waits until then, the running nodes' claims, finishes, heartbeats and dashboard reads included, and long-running jobs can lose their lease. On a large table apply it when the load is low.
  • A node of the release before keeps working on version 16, but the failed attempts it records carry no attempt number, so a RepeatedFailures rule cannot count them, and it records no clean stop, so a NodeLost rule reports it lost after a rolling deploy stops it. While it holds the notification lease it alerts only the dead-letters it made itself, from its own memory, and its deliveries mark no event delivered: when the lease then moves to a node of this release whose DeadLettered rule is already recorded, that node alerts the same dead-letter again, suppressed while the earlier delivery's subject cooldown is open, and as a second alert once that cooldown has ended or the delivery failed. To avoid it, upgrade the nodes with the alerts registration in one step, or take the registration off the nodes of the release before first.

SQLite

The SQLite store (dotnet add package Bellhop.Sqlite --prerelease, then bellhop.UseSqlite(connectionString)) is meant for development and small deployments that run a single node.

  • One node per file. Pointing two nodes at one database file, as two processes or as two hosts in one process, is unsupported and its behaviour is undefined. Bellhop does not check for it. When you need more than one node, use PostgreSQL.
  • Bellhop keeps its tables in the file under a prefix, bellhop_ by default (UseSqlite(connectionString, options => options.TablePrefix = "jobs") gives jobs_ tables), and touches nothing else in it.
  • The connection string names a database file, such as Data Source=jobs.db. An in-memory database and a read-only connection string are refused when the store is created, since each connection would see a database of its own, or none it can write. Bellhop never logs the connection string.
  • While Bellhop:AutoMigrate is on, its default, the node creates or upgrades the tables when it starts, inside a SQLite write transaction. It turns on write-ahead logging (WAL) for the file, so reads run beside the one writer; a file whose file system cannot keep WAL, such as some network shares, fails the migration. To apply the tables by hand instead, turn it off and run the script from BellhopSchema.GetScript(BellhopSchema.Sqlite, fromVersion) with sqlite3 -bail <file> < script.sql.
  • With Bellhop:AutoMigrate off, apply the tables up to version 4 before you start a node of this release: version 2 adds the dashboard's API keys, version 3 the node samples, which every running node writes every interval, and version 4 the dashboard's launches, and the node refuses to start on an earlier version. A node of the release before keeps working on versions 2, 3 and 4, as it never reads or writes a key, a sample or a launch.
  • Version 5 adds indexes of the jobs, the job transitions, the nodes, the recurring jobs and the API keys and changes no table. A node of the release before keeps working on it, and a node of this release also runs on version 4, where retention cleanup removes the same jobs but reads every finished job's history on each run, the dashboard's jobs list, dead letters and overview counts read every job when a filter matches fewer jobs than a page, its pages of nodes and recurring jobs read past the other namespaces' rows, and its page of API keys and the marking of expired keys read every key of the namespace; the jobs list without a filter, of a namespace with few jobs, also reads past the other namespaces' jobs. Five of the new indexes of the jobs, by state, name, queue, parent and creation time, are written on every job created and every change of a job's state; the sixth, by namespace, only when a job is created or removed.
  • The store's clock is the host's TimeProvider, since there is no database server to ask. A FakeTimeProvider registered in tests therefore drives every due time, lease and retention judgement.
  • SQLite has one writer at a time, so the node's writes take turns. An idle node finds a new job at its next poll, within PollInterval: the store does not wake workers when work arrives.
  • Creating a job in your own transaction works with a SqliteTransaction on the same file (connection.BeginTransaction(), which takes the write lock at once). While that transaction is open the node's own writes wait for it, up to the connection string's Default Timeout (30 seconds by default), then fail and are retried at the next poll, so keep such transactions short. A job id returned inside a transaction that rolls back names no job, and SQLite may give it to the next job created.

SQL Server

The SQL Server store (dotnet add package Bellhop.SqlServer --prerelease, then bellhop.UseSqlServer(connectionString)) runs on SQL Server 2019, 2022 and 2025, Azure SQL Database and Azure SQL Managed Instance. It talks to the server through Microsoft.Data.SqlClient, with no Entity Framework Core.

  • Bellhop keeps its tables in a schema of its own, bellhop by default (UseSqlServer(connectionString, options => options.Schema = "jobs") changes it), and nothing outside it. The name is 1 to 128 lowercase letters, digits or underscores and is not one of SQL Server's own schemas.
  • While Bellhop:AutoMigrate is on, its default, the first node to start creates or upgrades the schema, under an application lock (sp_getapplock) so that nodes starting together migrate it once. To have a DBA apply changes instead, turn it off and give them the script from Bellhop.SqlServer.Schema.BellhopSchema.GetScript(BellhopSchema.SqlServer, fromVersion); apply it with sqlcmd -b -i <file>, which stops at the first error. Each migration in it runs in its own transaction under the same lock.
  • With Bellhop:AutoMigrate off, apply the schema up to version 4 before you start a node of this release: version 2 adds the dashboard's API keys, version 3 the node samples, which every running node writes every interval, and version 4 the dashboard's launches, and the node refuses to start on an earlier version. A node of the release before keeps working on versions 2, 3 and 4, as it never reads or writes a key, a sample or a launch.
  • Version 5 adds indexes of jobs, job_transitions, nodes and api_keys and changes no table. A node of the release before keeps working on it, and a node of this release also runs on version 4, where retention cleanup removes the same jobs but reads every finished job's history on each run, once a minute on every worker node, the dashboard's jobs list, dead letters and overview counts read the whole jobs table when a filter matches fewer jobs than a page, its page of nodes reads past the other namespaces' nodes, and its page of API keys and the marking of expired keys read every key of the namespace. On every version the page of recurring jobs walks the table's primary key from its cursor and so reads past the other namespaces' recurring jobs, which code defines and so are few. Building the indexes takes locks on jobs and job_transitions that block writes to them, and so every job created and every change of a job's state on the running nodes, until they are built, and briefly the heartbeats. On a large table apply it when the load is low. The five new indexes of jobs are written on every job created and every change of a job's state, which adds to the cost of each claim and finish.
  • The database needs compatibility level 130 (SQL Server 2016) or later: the store reads JSON with OPENJSON.
  • The store is correct with READ_COMMITTED_SNAPSHOT on, Azure SQL Database's default, or off, SQL Server's.
  • A claim picks its job with the UPDLOCK and READPAST hints, so workers on many nodes skip a job another claim has locked instead of queueing behind it.
  • SQL Server has no LISTEN/NOTIFY, so the store does not wake workers when work arrives: an idle node finds a new job at its next poll, within PollInterval.
  • Waking nodes through Redis. With bellhop.UseRedisNotifications(redisConnectionString) from the Bellhop.Redis package (or a multiplexer of the application's), a write that makes work available publishes a wake-up on Redis, so idle nodes claim at once rather than at their next poll. SQL Server stays the only source of truth: Bellhop never reads or writes a key on Redis, only publishes and subscribes. A store call never waits for its publish or fails because of Redis. While Redis is down the nodes poll SQL Server at PollInterval, as without it; the host starts when Redis is unavailable and logs WakeupsNotSubscribed (4304, Warning) once, not at every wait, until a subscription succeeds. During an outage the subscription's loss and return are logged as WakeupsLost (4302, Warning) and WakeupsRestored (4303), and the first failed publish as WakeupNotPublished (4330, Warning) and the next one that succeeds as WakeupsPublishedAgain (4331). A job created in your own transaction publishes nothing, as Bellhop does not see your commit: the next poll finds it. An application that enqueues only inside its own transactions therefore gains nothing from this mode: its jobs are found at the next poll, within PollInterval, as without Redis. docs/redis-key-layout.md, under "Notifications for SQL stores", lists the channels.
  • When SQL Server, or an application lock's wait, picks one of the store's reads or writes as a deadlock victim, the store runs it again (a job created in your own transaction excepted: that error ends your transaction, and reaches you), a few times at most, and logs SqlServerDeadlockRetried (4101, Warning). An occasional one under heavy contention is expected; a steady stream is worth reporting.
  • Creating a job in your own transaction works with a SqlTransaction on the store's database; one on another database is refused. If another create wins the job's unique key while yours runs, the store rolls back only its own writes and answers with the duplicate, unless your session has SET XACT_ABORT ON: then that error dooms your transaction and the call fails with it. A call that fails otherwise, or is cancelled by its token or the command timeout, also rolls back to its own savepoint, so your transaction keeps no part of the job; under SET XACT_ABORT ON, SQL Server rolls back your whole transaction on such a cancel instead.
  • Alert events are read once every transaction that wrote before them has ended (MIN_ACTIVE_ROWVERSION()), so a write transaction left open in the database holds back the events after it until it ends: they are delayed, never lost. Copying the schema's rows into another database, such as a bacpac import, gives the new database a lower rowversion counter: each rule is then logged once per node as SqlServerNotificationEventPositionsAhead (4102, Error), and the message says how to reset the rules' places. A restore, a database copy or a failover keeps the counter and needs nothing.

Sharing a store between applications

Applications that share one store each set Bellhop:Namespace, as the concepts page describes.

  • Upgrade first. Set an application's namespace only once every node of every application sharing the store runs this release. A node of an earlier release knows no namespaces: it claims, recovers and reads every namespace's jobs as if they were its own, and its dashboard shows them all.
  • The guard. A node whose namespace is not default refuses to start while a node of an earlier release has sent a heartbeat within NodeLostAfter, and names it; such a node records no namespace. Only worker nodes send heartbeats, so a client-only node or a dashboard of an earlier release is not detected, and the guard runs only when a node starts: a node of an earlier release started later is not refused. A default node starts beside one, since it counts as the default namespace's.
  • The store must keep namespaces. A node with a namespace refuses to start on a store that does not report it can. The in-memory, PostgreSQL, SQL Server and SQLite stores can; on SQLite one node still owns the file, so applications cannot share it.
  • What stays shared: queue pauses and concurrency limits, the maintenance pause, throttles, the notification lease and its rules, and recurring job names. Pausing queue email from one application's dashboard pauses it for every application. The store has one notification lease and one set of alert rules, so every application's dashboard shows the same ones.
  • Moving an application into a namespace starts it on an empty one: its jobs and recurring jobs stay in the namespace it left. Drain it first, or leave the application that already has data on default and give the newcomer the namespace.
  • On PostgreSQL, SQL Server and SQLite a namespace is a column of the same tables. A sweep of one namespace (promotion, unroutable marking, the scheduling lag) reads past the due or waiting jobs of the others in the same index, and promotion's look for its next due job reads past theirs due within the next PollInterval, so a namespace with a large backlog and no running node slows the others' sweeps. Retention cleanup likewise walks every namespace's finished jobs older than its cutoff, so it reads past the others' that a longer retention keeps or that no worker of theirs has removed. Redis keeps each namespace's scheduled and retry jobs in sets of their own, so its promotion reads no other namespace's jobs.

Alerts

Notification rules are evaluated on nodes with the alerts registration, AddAlerts. It is separate from the client and the worker, so it can sit on a web node, on a worker node or on a node of its own, and a node-lost alert still fires when the last worker is down. A node without it reads no rule and evaluates none. A rule names a channel, and the channel says where the rule's notifications go. A web node that enqueues jobs and alerts, logging its backlog alert at Critical for the log pipeline to page on:

bellhop.AddClient().AddAlerts(alerts => alerts
    .AddRule(new NotificationRule
    {
        Name = "backlog",
        Trigger = NotificationTrigger.QueueDepth,
        Threshold = 500,
        Channel = "ops-pager",
        Cooldown = TimeSpan.FromMinutes(30),
    })
    .AddChannel(new NotificationChannel
    {
        Name = "ops-pager",
        Type = NotificationChannelType.Logger,
    }));

Rules can also be defined in configuration section Bellhop:Notifications:Rules, and channels in Bellhop:Notifications:Channels, one entry each, named by its key. Here the configured rules notify a generic webhook, whose host the destination allowlist must permit:

{
  "Bellhop": {
    "DestinationAllowlist": [ "alerts.example.com" ],
    "Notifications": {
      "Rules": {
        "dead-letters": {
          "Trigger": "DeadLettered",
          "Channel": "ops-mail"
        },
        "backlog": {
          "Trigger": "QueueDepth",
          "Threshold": "100",
          "Channel": "ops-mail"
        }
      },
      "Channels": {
        "ops-mail": {
          "Type": "Webhook",
          "Url": "https://alerts.example.com/bellhop/ops-mail"
        }
      }
    }
  }
}
  • Trigger and Channel are required. Template and Cooldown, 10 minutes by default, are optional (see Cooldowns, the cap and digests). Durations are written as [d.]hh:mm:ss, such as 00:30:00.
  • Each trigger reads its own settings, and a rule sets exactly those: Threshold for RepeatedFailures (the attempt number), FailureRate (a fraction below 1, with its Window) and QueueDepth; Tolerance for RecurringLate and ThrottleStarved; nothing more for DeadLettered and NodeLost. A setting the trigger does not read, or one Bellhop does not read at all, is an error.
  • Rule names ignore case. A rule defined both in code and in configuration is the code's, as a whole: in the example, backlog notifies ops-pager above 500, not ops-mail above 100.
  • Rules are not secret: every dashboard viewer sees their settings, templates included. Keep credentials out of them.
  • The section is read through IOptionsMonitor, so a reload applies at the next check. A reload with an invalid rule is not applied at all and is logged as NotificationRulesRefused (event 1043); at start, an invalid rule fails the start.

Among the running nodes with the alerts registration and at least one rule, one holds the store's notification lease, for LeaseDuration and renewed every LeaseDuration / 3, and only that node evaluates the rules and writes their deliveries. The store checks the lease in the same write as each delivery, so a node that paused past its lease and resumes writes nothing. A stopping node releases the lease and another takes it at its next check; a crashed one's lease is taken once it has expired. The holder publishes its rules to the store, and the dashboard's Notifications page lists them, with the node that holds the lease, or a warning when none does: then no rule is evaluated anywhere.

On PostgreSQL the notification tables come with schema version 5. A node that runs on version 4, with Bellhop:AutoMigrate off during a rolling deploy, starts, but its notification checks fail and log NotificationCheckFailed (event 1038) until the migration is applied; then it takes the lease without a restart.

The cooldowns come with schema version 14, and the rule versions, event marks and failure-rate counts with version 16. With Bellhop:AutoMigrate off, a node of this release refuses to start on a schema older than version 19 (see PostgreSQL), so an alerts node never runs without them. Nodes of the release before this one fire only DeadLettered rules, for the dead-letters they made themselves while they held the lease, from their own memory, under the same cooldowns; nodes of releases before version 14 create no rule deliveries, so they open no cooldown.

Delivery due times and errors come with schema version 11. With Bellhop:AutoMigrate off, a node of this release refuses to start on a schema older than version 19 (see PostgreSQL), so an alerts node never runs without them.

Proved by NotificationDutyTests.OfSeveralAlertsNodes_OneTakesTheLease_AndRenewsItEveryHeartbeatInterval_WhileNoOtherTakesIt, NotificationDutyTests.AHolderThatPausesPastTheLease_LosesItToAnotherNode_OnlyOnceLeaseDurationHasPassedSinceItsLastRenewal_AndItsPreparedWriteFails, NotificationDutyTests.ANodeWithoutTheAlertsRegistration_RunsNoNotificationCheck_WithOrWithoutTheWorker_WhileAnAlertsNodeBesideItDoes, NotificationLeaseStoreTests.NodesWritingAtRandomMoments_LandOnlyTheWritesOfTheTakeThatHoldsTheLease and AlertsTests.TheSnippetAndTheConfigurationOnThePage_LoadBothRules_TheCodesBacklogReplacingTheConfigurations.

Cooldowns, the cap and digests

A rule fires for a subject (see What each trigger watches): for DeadLettered, the job, by its id. Each firing creates a delivery, and the store decides, in the same lease-checked write, whether it is sent:

  • Subject cooldown. The first delivery for a rule and subject is Pending and opens that subject's cooldown, for the rule's Cooldown. Later firings for the subject within it are recorded as Suppressed and extend nothing.
  • Rule cooldown and its cap. The first Pending delivery of a rule also opens the rule's cooldown, of the same length, which is not restarted while it is open. Within it at most Bellhop:NotificationMaxDeliveriesPerCooldown deliveries, 10 by default and from 1 to 1000, are created Pending, whatever their subjects; later ones are Suppressed by the cap. A delivery that is both a duplicate and over the cap counts as a duplicate.
  • Digest. When a rule cooldown ends and the cap suppressed deliveries in it, the lease holder creates one digest delivery for the rule at its next check, sent through the rule's channel like any delivery: Bellhop alert digest: notification rule dead-letters (deadLettered) suppressed 40 deliveries over its cap during its cooldown, for 40 subjects: …. It lists the subjects in the order they were first suppressed, up to 3000 characters, then says how many more there were; the store keeps the first 100. A flood therefore gives at most the cap's worth of alerts and one digest per cooldown, never silence. A digest never uses the rule's template, and is never suppressed or counted.
  • Retries keep a cooldown open. While a delivery created in a cooldown is still pending, retries included, that cooldown stays open past its length, so a delivery still being retried is not joined by the next one: with the default retries, a cooldown can last about 20 minutes. A delivery that fails after its last attempt closes its subject's cooldown at once, so a channel outage does not silence the subject; it still counts towards the cap.
  • Test deliveries are outside every cooldown: they are never suppressed and never counted.

The cooldowns are kept in the store, so they hold across a lease handover: the next holder suppresses what the last one would have. The cap is one option for every rule, read by the node that holds the lease. Each created delivery is logged as NotificationDeliveryCreated (1075, Debug), and each digest as NotificationDigestCreated (1076).

A rule watching a condition records nothing for a subject while its subject cooldown is open, or once the cap has suppressed that subject in the open rule cooldown, so a condition that lasts is alerted once per cooldown, not suppressed every check; once a delivery for it fails, the next check alerts it again.

Proved by NotificationCooldownStoreTests.EachBranchOfTheDecision_IsTakenAsTheOpenCooldownsDecide_AndADuplicateWinsOverTheCap, NotificationCooldownStoreTests.ARuleFiringForManySubjects_CreatesTheCapPending_AndTheRestCapped_ThenOneDigestOfThem, NotificationCooldownStoreTests.APendingOpener_KeepsBothCooldownsOpenPastTheirLength_AndOnceItIsSentBothEnd, NotificationCooldownStoreTests.ALeaseHandoverInsideOpenCooldowns_KeepsThem_SoTheNewHoldersFiringsAreSuppressed_AndTheCountIsNotReset, NotificationCooldownPropertyTests.RandomFiringsOutcomesTestsDigestsAndClockMoves_MatchTheReferenceModel_AndKeepTheCooldownInvariants, DeadLetterCooldownTests.ASyncCrmJobDeadLetteredTwice2MinutesApart_UnderA10MinuteCooldown_IsSentOnce_AndSuppressedOnce, DeadLetterCooldownTests.MoreDeadLettersThanTheCapWithinOneCooldown_SendTheCapsWorth_AndOneDigestNamingTheRest_WhileTestDeliveriesAreSentAndNotCounted and DeadLetterNotificationTests.AJobDeadLetteredOnACombinedNodeThatHoldsTheLease_FiresTheRuleOnce_WithTheJobsIdAsSubject_WhicheverWayItWasDeadLettered.

What each trigger watches

The holder evaluates every rule at each check, in the store, across every namespace: one lease holder alerts for every application that shares the store. Up to 100 events or subjects of a rule fire per evaluation, and a rule with more is evaluated again, up to 10 times a check; the rest wait for the next check. A rule whose evaluation fails is logged as NotificationRuleEvaluationFailed (1079, Warning) and the other rules are evaluated; while it keeps failing it is logged at Debug as NotificationRuleEvaluationStillFailing (1081) and at Warning again once a minute, and as NotificationRuleEvaluationRecovered (1082) once it is evaluated again.

Some triggers watch events, each of which happens once:

  • DeadLettered: every time a job is dead-lettered, on any node, for any reason. The job's id is the subject. A job requeued and dead-lettered again is alerted again.
  • RepeatedFailures: every attempt that fails (an exception, a timeout, a permanent failure or a declined retry, the last attempt included) when the job's attempt number is the threshold. The job's id is the subject. A lease expiry, a release at shutdown and a cancellation are not failed attempts, and a requeue starts the count again.
  • RecurringLate: every record of missed instants a recurring job's trigger, schedule change, pause or removal writes, one per record however many instants it covers, and every occurrence whose job is created more than the tolerance after its due time. The recurring job's name is the subject.
  • NodeLost: every worker node whose latest heartbeat is NodeLostAfter old, as the holder's option sets it, once per heartbeat it went silent after; a node that heartbeats again and is lost again is alerted again. The node's id is the subject. Only worker nodes send heartbeats, so only they can be reported. A worker that stops cleanly records it, waiting at most 5 seconds, and is not reported; one that cannot is logged as NodeStopNotRecorded (1080, Warning) and is reported once NodeLostAfter has passed.

The store finds these events from what it records, and marks each one delivered for the rule's name in the same lease-checked write that creates its delivery, also when that delivery is suppressed. So whichever node holds the lease, and through every handover, an event is alerted once per rule name, and events that happen while no node holds the lease are alerted when one next does. A rule is known by its name, trigger, threshold and tolerance: the first evaluation of a rule the store has never seen with those starts it at the store's present, alerts nothing, and logs NotificationRuleStarted (1078, Information). Events recorded before a rule's start are never alerted by it, so a new rule, a renamed one, or one whose trigger, threshold or tolerance changed does not alert the stored backlog, and an event recorded between an edited rule's last check and its new version's first is alerted by neither. Changing a rule's channel, template, window or cooldown keeps it. A rule removed and added back unchanged, or an edit rolled back, continues where it stopped and alerts what happened meanwhile, but not what another version of the same name already alerted. An event whose job retention or a delete removed before a check found it is not alerted. Neither store ever removes a rule's versions or the marks of the events it delivered: each threshold or tolerance edit adds a version, and each alerted event adds one mark per rule name, kept for good.

On PostgreSQL an event is read only once every transaction that began before it has ended, since ids are given at insert and transactions commit out of order. A write transaction left open anywhere on the database server therefore holds back the events after it until it ends: they are delayed, never lost.

Moving the database to another cluster. On PostgreSQL each event, and each rule's place among them, is positioned by the server's transaction ids, which belong to that server: a dump restored into another cluster, or a logical replica promoted in its place, has its own, usually lower. Each rule whose place is then ahead of every transaction on the new server is logged once per node as NotificationEventPositionsAhead (4003, Error), and alerts none of its once-only events until the new server's transactions pass that place, which may take very long. Nothing is alerted twice meanwhile. To start every rule afresh on the new server, with the alerts nodes stopped, run this in the Bellhop schema (bellhop here); events recorded before it that were not yet alerted are then never alerted, as for a new rule. It rewrites every row of the three tables, so run it when the load is low:

BEGIN;
UPDATE bellhop.job_transitions SET xact = NULL WHERE xact IS NOT NULL;
UPDATE bellhop.jobs SET xact = NULL WHERE xact IS NOT NULL;
UPDATE bellhop.recurring_misses SET xact = NULL WHERE xact IS NOT NULL;
UPDATE bellhop.notification_rule_versions
SET events_xact = txid_snapshot_xmin(txid_current_snapshot()), events_id = 0,
    starts_xact = txid_snapshot_xmin(txid_current_snapshot()), starts_id = 0;
COMMIT;

Other triggers watch conditions, read again at every check:

  • FailureRate: a job name, in every namespace, whose failed attempts are more than the threshold, a fraction, of its ended attempts (succeeded or failed) within the window. There is no minimum: one failed attempt out of one is a rate of 1. The job name is the subject. On PostgreSQL the attempts are counted from the store's first check of a failure-rate rule on, in whole minutes, so a window's start may be up to a minute late, an attempt whose write commits after a later one was counted is not counted, and the attempts of a job that retention or a delete removed still count until they leave the window; the in-memory store counts from the jobs it holds, so a removed job's attempts no longer count there. Each evaluation of a failure-rate rule counts at most 30,000 job transitions (every change of a job's state, not only ended attempts): with one such rule and the default LeaseDuration of 60 seconds, a check every 20 seconds, the counts keep up with about 1,500 transitions a second. Above that they lag, which is logged once as NotificationRatesBehind (4004, Warning), and NotificationRatesCaughtUp (4005) once they have caught up.
  • QueueDepth: a queue with more Enqueued jobs than the threshold, counted over every namespace, as the queue-depth gauge counts them: a paused queue and jobs a queue limit holds back count. The queue is the subject.
  • ThrottleStarved: a throttle key at its limit (a concurrency key with as many processing jobs as its Max, a rate-limit key with as many starts in its window as its limit) while a job it holds back, in a queue that is not paused, has waited Enqueued longer than the tolerance since it last entered Enqueued. Nothing is starved while the maintenance pause is on. The key is the subject.
  • RecurringLate also fires for a recurring job that has not started: one that is not paused or orphaned whose next run is due more than the tolerance ago, or with a waiting occurrence due that long ago. So one occurrence can give up to three deliveries, not started, started late and missed, all for the same subject, and the subject cooldown merges those close together.

Earlier releases fired DeadLettered rules only for the jobs the lease holder itself dead-lettered, from a queue in its memory. That queue, and its events NotificationDeadLettersDropped (1077) and NotificationDeadLetterNotQueued (2056), are gone: every node's dead-letters are alerted, and the alerts registration need not run on a worker node.

Channels

A channel has a Type and, for the three webhook types, a Url and an optional ClientName:

Type What it sends Accepted when
Webhook a POST of a fixed JSON envelope (below) the answer is any 2xx
Slack a POST to a Slack incoming webhook: the message as plain text, with formatting, mentions and unfurling off the answer is any 2xx
Teams a POST to a Microsoft Teams Workflows webhook (the "post to a channel when a webhook request is received" flow): an Adaptive Card 1.4 with the message as plain text. The Office 365 connector webhooks that Microsoft is retiring are not supported the answer is any 2xx
Logger one log entry at Critical, category Bellhop.Notifications, event 1065 NotificationAlert: Bellhop alert {DeliveryId} from notification rule {Rule} for {Subject}: {Message} always, unless the logger throws
  • Url is required for Webhook, Slack and Teams: an absolute http or https URL of at most 2048 characters, without user information. Logger takes neither Url nor ClientName.
  • ClientName names the HttpClient registration the webhook is posted through: Bellhop by default, which AddAlerts registers as AddHttpJobs does, one registration for both. Another registration must be opted in with UseForBellhopHttpJobs(), the same opt-in as HTTP jobs'; a webhook that needs credentials gets them there, in a delegating handler or its default request headers, never in the URL.
  • Channel names ignore case. A channel defined both in code (AddChannel) and in configuration is the code's, as a whole. Defining the same name twice in code throws.
  • Channels are read once, at start: a change to the section applies at the next restart. A channel that is not valid, or whose ClientName is not opted in, fails the start before the store is touched; the error names each bad channel, and never its URL.
  • A rule may name a channel that is not defined: that is not a start error. Its deliveries are not accepted on the node that sends them, so they are retried and then failed, with a reason that names the missing channel.

Outbound rules. A webhook is an outbound call like an HTTP job's request, under the same rules: its host must be on Bellhop:DestinationAllowlist, which is empty by default, so add hooks.slack.com, your Teams workflow's host or your receiver's host; a host only a wildcard entry covers must not resolve to a private or loopback address, which is checked again when the connection is made; a registration opted in with UseForBellhopHttpJobs(hosts) sends only to its hosts; and a redirect is followed only to the same scheme, host and port, at most MaxRedirects times (0 by default). A destination these rules refuse fails the delivery at once, as retrying cannot succeed: it is logged as NotificationDeliveryFailed and counted in the metric.

Secrets. A webhook URL lets anyone who holds it post, so Bellhop treats it as a secret: logs, the stored reason of a failed attempt, exception messages, the dashboard and the channel's ToString name at most its host. Keep it out of appsettings.json and source control, in a secret store or an environment variable such as Bellhop__Notifications__Channels__ops-mail__Url. Microsoft.Extensions.Http's own request logging writes each URL with its path, so UseForBellhopHttpJobs() removes it from every registration it opts in, the Bellhop one included; a logger you add after it logs the path again. Tracing is not covered: the HttpClient instrumentation of OpenTelemetry or Application Insights records each request's URL with its path (url.full, the query redacted), so filter Bellhop's webhook requests out of it, or keep traces as private as the URLs. A channel's name and type are not secret.

Message templates

A rule's Template is the message its notifications carry; without one, the message is Bellhop alert: notification rule {rule} ({trigger}) fired for {subject}. The placeholders are:

Placeholder Value
{rule} the rule's name
{trigger} the trigger's camelCase name, such as queueDepth
{subject} what the delivery is about: a job, a job name, a queue, a node or a throttle key
{deliveryId} the delivery's id
{createdAt} when the delivery was created, in UTC, as yyyy-MM-ddTHH:mm:ssZ

Anything else, an unknown placeholder such as {job} included, is literal text, so a template keeps rendering as it did when later versions add placeholders. There is no escape syntax. A test delivery's message is Bellhop test alert for notification rule {rule} ({trigger}), sent with 'send test' on the dashboard., or, when the rule has a template, the template after [Test]. A digest has a message of its own (see Cooldowns, the cap and digests), its subject is digest, and its subjects are placed as values.

Escaping. The template's own text is kept as written. Every value a placeholder puts in is treated as untrusted, as a subject may come from a job's or a queue's name: each control, format (bidirectional overrides, zero-width characters) and line or paragraph separator character in it is written as \uXXXX. Then, per channel:

  • Webhook: the body is written by a JSON writer, so no value can break out of its string, and is sent as application/json; charset=utf-8. Beside the message it carries the delivery's fields, the rule and the subject as stored:
{"deliveryId":42,"rule":"backlog","trigger":"queueDepth","subject":"default","isTest":false,"isDigest":false,"createdAt":"2026-11-21T10:15:00Z","attempt":1,"message":"Bellhop alert: notification rule backlog (queueDepth) fired for default."}
  • Slack: the whole text escapes &, < and > as Slack requires, so no <!channel>, user mention or <url|label> link can be formed, and the request turns parsing, link names and unfurling off. Values are also defanged: a zero-width space follows every ., : and @ in them, so a value cannot become a link, a domain, an e-mail address or a plain @channel.
  • Teams: the text goes in a TextRun, which reads no Markdown; values are defanged as for Slack.
  • Logger: the rule, the subject and the message are logged as structured values, neutralized as above.

Sending, retries and failures

The node that holds the notification lease sends the due deliveries, on a loop apart from the lease's, so a slow channel never delays a renewal or the node's stop. Every 5 seconds it reads up to 20 due deliveries and sends them, at most 4 at once, each on its own. Before each attempt it records the attempt in the store, so a node that crashes after sending still counts it; a webhook has 10 seconds to answer, over the whole exchange. Every write is checked against the lease in the same store step, so a node that lost the lease changes nothing.

  • Accepted: the delivery is Sent and never attempted again; logged as NotificationDeliverySent (1066).
  • Not accepted: an answer other than 2xx, a redirect not followed, a refused connection, a host that does not resolve, no answer within 10 seconds, or no rule or channel of that name on the sending node. While attempts remain, the delivery stays Pending and is attempted again after 10 seconds, 2 minutes, 8 minutes and then every 10 minutes, so the default 5 attempts span about 20 minutes; logged as NotificationDeliveryRetrying (1067), with the reason and the wait.
  • Failed: after the last attempt, or at once when the outbound rules refuse the destination, the delivery is Failed, logged as NotificationDeliveryFailed (1068, Error) with the rule, the channel, its type and host and the reason, and counted in the metric. The dashboard's Notifications page lists failed deliveries with their reason.

Bellhop:NotificationMaxAttempts, 5 by default and from 1 to 20, sets the attempts in all, the first included, for every delivery the node sends; a smaller value cuts the schedule above, a larger one adds attempts 10 minutes apart. Attempts are counted in the store, so a delivery started by one lease holder continues on the next with the attempts already made.

A delivery is sent at least once. When the outcome of a send cannot be recorded, because the lease was lost meanwhile (NotificationOutcomeUnrecorded, 1069) or the node stopped mid-send, the delivery keeps its recorded attempt, and the lease holder sends it again once its wait has passed; when that attempt was the last, the delivery is failed with a reason saying its outcome is unknown. A receiver that must not act twice dedupes by the delivery id. A failed read of the due deliveries is logged as NotificationSendingFailed (1070), then at Debug while it lasts, and as NotificationSendingRecovered (1072) when it ends; a failed write of one delivery as NotificationDeliveryWriteFailed (1073), once per delivery and poll while the store refuses writes; an unexpected failure while sending, which leaves the deliveries as the store recorded them, as NotificationSendingError (1074, Error).

The counter bellhop.notifications.failed (unit {delivery}; bellhop_notifications_failed_total in Prometheus) counts the deliveries the node marked failed, tagged with bellhop.notification.rule and bellhop.notification.channel, the names of the rule and the channel. Alert on it to learn that alerts are not getting through.

'Send test' on the Notifications page creates a test delivery for a rule, which the lease holder sends through the rule's channel like any delivery, outside the rule's cooldowns. A test requested while no node holds the lease stays pending until one does, however long that takes. Pressing it again while the rule's test is pending, retries included, returns that test rather than creating another, so a test that is waiting out its backoff is not sent sooner.