Skip to content
Edit this page

Concepts

What Bellhop guarantees, and what it leaves to your handlers. Each section names the tests that prove the behaviour it describes, under tests/unit/Bellhop.Unit.Tests and tests/integration/Bellhop.Integration.Tests.

At-least-once delivery

Bellhop runs every job at least once, and sometimes more than once. A job's handler can start again when:

  • the node running it crashed or lost the store, and another worker recovers the job once its lease has expired (see Leases);
  • the handler threw, or ran past its timeout, and the job is retried;
  • the host shut down while the handler was still running after ShutdownTimeout (30 seconds), and the job was handed back for another node to run.

So write handlers that are idempotent: running one twice for the same job must do no more harm than running it once. Give side effects a key derived from the job, and let the system you call refuse the second attempt:

[JobName("charge-order")]
public sealed record ChargeOrder(Guid OrderId) : IJob;

public sealed class ChargeOrderHandler(IPayments payments) : IJobHandler<ChargeOrder>
{
    public Task HandleAsync(ChargeOrder job, JobContext ctx, CancellationToken ct)
    {
        // The idempotency key makes a second run of the same job charge nothing twice.
        return payments.ChargeOnceAsync(job.OrderId, idempotencyKey: $"charge-order:{job.OrderId}", ct);
    }
}

A node that has lost a job's lease does not stop its handler: the handler's token is not signalled for it. Whatever that run then reports is refused by the store and discarded (event 2034, JobCompletionRefused), so the job's outcome is the other run's, but its side effects still happen. Idempotent handlers are the only defence against that.

Proved by LeaseRecoveryTests.JobOfANodeCutOffFromTheStore_RunsAgainOnAnotherNode_NoEarlierThanItsLeaseEnd_AndTheFirstRunCannotEndIt, DetachmentTests.HandlerWhoseRenewalIsRefused_WhileItStillRuns_IsWarnedAboutAndRecordedAsLeaseLost_AndItsSlotComesBackAtOnce and ShutdownReleaseTests.ShutdownHandsAnUnfinishedJobToAnotherNode_WhichRunsItAsAttemptOne_WhileTheOldHandlersResultChangesNothing.

Leases and the duplicate window

A worker that claims a job holds a lease on it for LeaseDuration, 60 seconds by default, and renews it every third of that, every 20 seconds, for as long as the handler runs. A long job never loses its lease while its node is alive and reaches the store.

When a node stops renewing, because it crashed or cannot reach the store, any worker node recovers the job once the lease has expired by the store's clock, within one PollInterval (1 second) after that. The job goes back to enqueued at once, with no retry wait, and the interrupted run counts as one of its attempts; at its last attempt it is dead-lettered instead.

The duplicate window is the lease length, 60 seconds by default: a job whose node is lost can start again on another node as soon as its lease has run out, so two runs of one job can begin up to LeaseDuration apart. A shorter lease recovers crashed jobs sooner but renews more often; set it with Bellhop:LeaseDuration (from 1 second to 1 day).

Proved by ClaimStoreTests.LeaseDuration_DefaultsToSixtySeconds_AndBindsFromConfiguration, ClaimAndRunTests.LongRunningHandler_HasItsLeaseRenewedEveryThirdOfTheLease_AndItNeverExpires and LeaseRecoveryTests.JobAtItsLastAttempt_OfANodeCutOffFromTheStore_IsDeadLetteredByAnotherNode_WhichAloneRaisesTheEvent.

Unique keys

A unique key stops the same work from being created twice. While a job holding a key is active (scheduled, enqueued, processing, awaiting, failed and waiting for its retry, or unroutable), a call with that key creates nothing, whatever the job's name or queue:

var result = await jobs.EnqueueAsync(new ChargeOrder(orderId), new EnqueueOptions { UniqueKey = $"charge-order:{orderId}" }, ct);
// result.WasDuplicate is true when an active job already held the key; result.JobId is then that job's id.

The duplicate policy says what such a call does instead: Ignore, the default, returns the active job's id; Error throws DuplicateJobException; ReplaceSchedule moves a scheduled holder to the new time. Set it per call, with ConfigureJob, or with [Unique(Policy = ...)], which sets only the policy: the key always comes with the call. The key is free again once its job has succeeded, been dead-lettered or been cancelled.

A unique key guards against a second job, not a second run: a retry or a recovered job is the same job, still holds its key, and runs again. Use unique keys and idempotent handlers together.

Proved by UniqueKeyTests.Enqueue_WithAKeyAnActiveJobHolds_AndNoPolicy_CreatesNothing_AndReturnsTheHoldersId, UniqueKeyTests.DuplicatePolicy_IsTheCallsThenTheFluentThenTheAttributesThenIgnore and UniqueKeyClusterTests.ManyCallsWithAFreeKeyFromTwoNodes_CreateExactlyOneJob_AndEveryOtherCallReturnsItOrFails.

Continuations and chains

A continuation is a job that waits for another job, its parent, to finish. ContinueWithAsync stores it awaiting, and no worker runs it until the parent's outcome releases it:

var charge = await jobs.EnqueueAsync(new ChargeOrder(orderId), ct: ct);
// Awaits the charge: enqueued once it has succeeded, cancelled if it is cancelled.
var receipt = await jobs.ContinueWithAsync(charge.JobId, new SendReceipt(orderId), ContinuationCondition.OnSuccess, ct: ct);

The condition says which outcome releases it: OnSuccess the parent's success, OnFailure its dead-lettering, OnCompletion either. A failed attempt that will be retried is no outcome, so a continuation waits through its parent's retries. An OnFailure continuation of a parent that succeeds is cancelled, with reason ConditionNotMet; an OnSuccess continuation of a dead-lettered parent keeps awaiting, since the parent can still be requeued and succeed. Cancelling a parent cancels every continuation below it, whatever the condition. The continuation is decided in the same store write as the parent's outcome, so no one sees the parent finished while the continuation still awaits, and one added to a parent that has already finished is decided at once. Adding one to a parent id that no stored job has, because it never existed or was deleted or removed by retention, throws ParentJobNotFoundException, a JobNotFoundException whose JobId is the parent's, and stores nothing.

ChainAsync stores a run of jobs in one step: the first is enqueued, and each later one is an OnSuccess continuation of the one before it, so either the whole chain exists or none of it does. A dead-lettered step holds the rest of the chain until it is requeued and succeeds; a cancelled step cancels the rest.

A parent that is requeued and finishes again releases nothing a second time, and does not bring back the continuations cancelled with it: create those again.

Proved by ContinuationConformance.AParentsOutcome_ResolvesItsAwaitingContinuation_InTheSameWrite_ByItsCondition, ContinuationConformance.AContinuationOfAFinishedParent_IsResolvedAtOnce_AsIfTheParentHadJustFinished, ContinuationTests.Scn123_AContinuationOfAParentRemovedByRetention_IsRefused_NamingTheParent_AndNothingIsStored, ChainTests.Scn121_RequeuingADeadLetteredChainStep_RevivesTheChain_WithoutTheOperatorTouchingTheNextStep, ContinuationPropertyTests.AfterEveryStepOfARandomRun_NoContinuationAwaitsAParentWhoseOutcomeDecidedIt_AndEachMoveFollowsItsParentsOutcome and ContinuationsTests.TheReceipt_AwaitsTheCharge_AndRunsOnceTheChargeHasSucceeded.

Batches

A batch is a named group of jobs that CreateBatchAsync stores in one step, together with its batch continuations, jobs that wait for the whole group rather than for one job:

// Stored in one step: the quotes, and the charge that awaits all of them.
var batch = await jobs.CreateBatchAsync(
    $"quotes of order {orderId}",
    [.. parcelsPerShipment.Select(parcels => new BatchJob(new QuoteShipping(parcels)))],
    [new BatchContinuation(new ChargeOrder(orderId), ContinuationCondition.OnBatchSucceeded)],
    ct);

Either the batch, every member and every continuation are stored, or none of them is, and no worker claims a member before the rest is stored. A batch is complete at creation: no job can be added to it later, and neither can a continuation. Its members are enqueued at once; each one's JobContext.BatchId, and its JobInfo.BatchId, name the batch, and so do its continuations'. GetBatchAsync reads the batch's state. A name is a label, not a key: two batches may share one. A batch with no jobs is refused with ArgumentException.

States. A batch is Open until every member has finished. It becomes Succeeded when every member has succeeded, and Completed when every member has succeeded, been dead-lettered, been cancelled or been deleted, and at least one did not succeed; a deleted member counts as finished and not succeeded. A failed attempt that will be retried is no finish. Completed is not final: when the members that did not succeed are requeued and succeed, the batch is upgraded to Succeeded. Succeeded is final: a member requeued and finishing again changes nothing. The batch moves in the same store write as the member's outcome that decides it, so two members finishing at once on two nodes move it once.

Continuations. An OnBatchSucceeded continuation is enqueued when its batch succeeds, from open or by an upgrade; while the batch stays completed it keeps awaiting, since the batch can still succeed, and an operator can cancel it. An OnBatchCompleted continuation is enqueued when its batch completes or succeeds, whichever comes first. Each is enqueued at most once, and one an operator cancelled stays cancelled. ContinueWithAsync does not take the batch conditions.

Duplicates. A job of a batch whose unique key an active job holds makes the whole call fail with DuplicateJobException under Error, storing nothing. Under any other policy it is not created and is no member: its result is the holder's id with WasDuplicate set, and the batch waits only for the members it created. A batch none of whose members was created is stored succeeded, and its continuations enqueued.

Deleting and retention. Deleting a job, or removing it by retention, cancels every continuation still awaiting it, with reason ParentRemoved, and the ones below those with ParentCancelled. Retention keeps every member of a batch that is open or completed, so the batch can still finish or be upgraded. Once a batch is completed or succeeded and every member still stored is past its state's retention, measured from when it last finished, the batch is removed together with those members, in one step, and its awaiting continuations are cancelled with reason BatchRemoved. Requeuing a member postpones the removal; a deleted member does not hold it back.

Under inline execution the call that creates a batch runs its members, then the batch continuations the last of them releases. On PostgreSQL, upgrade every node before creating batches (see production).

Proved by BatchTests.Scn114_ABatchWhoseMembersAllSucceed_IsSucceeded_AndItsOnBatchSucceededContinuationIsEnqueuedExactlyOnce, BatchTests.Scn119_ACompletedBatch_IsUpgradedToSucceeded_OnceItsDeadLetteredMemberIsRequeuedAndSucceeds_AndItsContinuationIsEnqueuedOnce, BatchTests.ABatchJobWhoseKeyIsHeld_UnderError_FailsTheCall_StoresNothingOfTheBatch_AndRaisesNoEvent, BatchPropertyConformance.AfterEveryStepOfARandomRun_EachBatchMovesOnlyByItsMembers_EachContinuationIsReleasedOnce_AndNothingAwaitsWhatIsGone, BatchRaceTests.TheLastTwoMembersFinishingAtOnceOnTwoNodes_MoveTheBatchOnce_AndReleaseEachContinuationOnce, BatchRetentionCleanupTests.WithDefaultRetention_ASucceededBatchGoesSevenDaysAfterItsMembers_AndACompletedOneOnceItsDeadLetterIsThirtyDaysOld and BatchesTests.TheCharge_AwaitsEveryQuote_AndRunsOnceAllOfThemHaveSucceeded.

Enqueueing inside the application's transaction

A job can be created inside the application's own database transaction, so it exists exactly when the data saved with it does. On the PostgreSQL store, pass the open transaction as EnqueueOptions.Transaction to EnqueueAsync or ScheduleAsync; with the Bellhop.EntityFrameworkCore package, dbContext.EnqueueAsync(job) uses the context's current transaction. The job and its history are written in that transaction: no worker sees or claims the job until it commits, and a rollback leaves nothing. Bellhop never commits, rolls back or disposes the transaction.

The transaction must be on the store's own database. A transaction of another provider, one that has completed or one on another database is refused with ArgumentException, nothing is written and it stays usable; a store without transactional enqueue, such as the in-memory store, refuses with NotSupportedException. A context with no current transaction is refused too, rather than enqueueing outside it; that includes a context enlisted in a TransactionScope, which has no current transaction. ContinueWithAsync, ChainAsync and, under inline execution, an enqueue refuse a transaction.

Bellhop cannot see the commit, so a job created this way raises no OnEnqueued and is not counted in bellhop.jobs.enqueued; it is logged at Debug instead, with event 2220. Any database error inside the transaction aborts it, as PostgreSQL does, and the application rolls it back. The application's database role needs USAGE on the Bellhop schema, SELECT, INSERT and UPDATE on its jobs and job_transitions tables and USAGE on its sequences, or the write fails and aborts the transaction. The job wakes workers with a NOTIFY sent on commit, so the transaction cannot be prepared for two-phase commit. A unique key's holder is not locked while the transaction is open, but ReplaceSchedule moving a scheduled holder's time holds that job's row until the transaction ends.

Proved by TransactionalEnqueueStoreTests.AJobCreatedInTheTransaction_IsInvisible_AndUnclaimable_AndUnannounced_UntilTheApplicationCommits, TransactionalEnqueueStoreTests.ATransactionOnAnotherDatabase_IsRefused_NothingIsWrittenToEither_AndTheTransactionStaysUsable, TransactionalEnqueueNodeTests.Scn113_AJobEnqueuedInATransactionThatRollsBack_IsNeverClaimed_WhileTheWorkerRunsTheJobsAfterIt, ApplicationTransactionTests.AJobCreatedInTheTransaction_RaisesNoOnEnqueued_IsNotCounted_AndIsLoggedAsCreatedInTheTransaction, ApplicationTransactionTests.AContinuationOrChainWithATransaction_IsRejected_OnAStoreThatHasTheCapability_AndNothingIsStored, BellhopDbContextExtensionsTests.AnEntityAndAJobSavedInTheContextsTransaction_AreUnclaimedWhileItIsOpen_AndBothStoredAndTheJobRun_OnceItCommits and BellhopDbContextExtensionsTests.AContextWithNoCurrentTransaction_IsRejected_AndNothingIsStored.

Throttles

Throttles hold a job back at claim time, on every node at once, without failing it. A held-back job stays enqueued with its attempt number unchanged, and the worker claims the next job it is allowed to run, so it never stalls the queue.

  • Concurrency keys. A job with a concurrency key, from [Concurrency("smtp")], .Concurrency("smtp") in AddJob or EnqueueOptions.ConcurrencyKey, runs only while fewer jobs with that key are processing, across all nodes, than the key's Max. A key has a Max of 1, a mutex, until an operator sets another with IThrottleManager.SetConcurrencyKeyMaxAsync or on the dashboard's Throttles page. A key such as tenant:{TenantId} is a template, filled from the job's property of that name when it is enqueued; an enqueue whose job lacks the property, or has it null, fails and stores nothing.
  • Rate limits. A job with a rate-limit key, from [RateLimit("mail-api")] or .RateLimit("mail-api"), starts only while fewer than N jobs with that key have started in the current window, across all nodes. IThrottleManager.SetRateLimitAsync, or the dashboard's Throttles page, sets N and the window, fixed (aligned to the store's clock) or sliding. Every start counts, retries and recovered runs included.
  • LongRunning. A job marked [LongRunning] or .LongRunning() counts against the worker's LongRunningLimit as well as its concurrency, so long jobs cannot take every slot of a node.

A Max or a rate limit lives in the store, so it holds for the whole cluster, applies to the next claim on every node without a redeploy, and survives restarts. Lowering one stops no running job: the next claim with the key waits until the jobs already running fall below it. A job counts towards its key while it is processing, until its run ends or its expired lease is recovered.

By default a worker drains its queues in strict order. Give it QueueWeights to claim from them in proportion to their weights instead; a queue with nothing to claim gives its turns to the others.

Proved by ConcurrencyKeyTests.TwoJobsWithAMutexKey_OnTwoFreeWorkers_RunOneAfterTheOther, ConcurrencyKeyTests.AMaxLoweredBelowTwoHoldersOnTwoNodes_StopsNeither_AndAdmitsNoClaimUntilNoneHoldsTheKey, RateLimitClaimTests.NStartsInAFixedWindow_StopEveryNodesStarts_UntilTheNextWindowOnTheStoresClock, LongRunningTests.ANodesLongRunningLimitBelowItsConcurrency_RunsAtMostThatMany_AndItsOtherSlotsClaimOtherJobs and WeightedQueueTests.AWeightedWorker_ClaimsEachQueueInProportionToItsWeight_FromLaterQueuesWhileEarlierOnesHaveJobs.

Bulk enqueue, results and waiting

EnqueueManyAsync stores many jobs in one call, each with the settings its options give it:

// One round-trip: every quote is stored, or none is.
var quotes = await jobs.EnqueueManyAsync(parcelsPerOrder.Select(parcels => new QuoteShipping(parcels)), ct: ct);

All or none, in one round-trip. Every job is checked and serialized before the store is reached, so one that EnqueueAsync would refuse, such as a payload over PayloadHardLimit, fails the whole call with nothing stored. The store then writes every job in one step: no reader or worker sees part of a call, and jobs of equal priority are claimed in the call's order. A call that fails because the store failed or did not answer may have stored all of its jobs, never only some. A store may limit one call's size (PostgreSQL takes at most 1 GB of payloads in one statement), so split very large sets into several calls.

Duplicates. A job whose unique key an active job holds is not created under Ignore, or ReplaceSchedule, which has nothing to move as nothing is scheduled: its result is the holder's id with WasDuplicate set, and the rest of the call is stored. Under Error the whole call is refused with DuplicateJobException and stores none of its jobs. Two jobs of one call may not have the same key. Under inline execution the call runs every job it created, in its order.

Results. A job declared as IJob<TResult> keeps what its handler returns: the result is serialized when the job succeeds and stored in the same write, so GetResultAsync<T> reads it on any node from the moment the job reads as succeeded. A result larger than ResultSizeLimit, 1 MB (1,048,576 bytes of its UTF-8 JSON) by default, is not stored: the job still succeeds, keeps only the mark that its result was dropped, and a warning (event 2201, JobResultDroppedForSize) gives the size and the limit. A result is part of its job: it goes when the job is deleted or removed by retention, a requeue clears it, and the next success replaces it. When there is no result to read, GetResultAsync says why with its exception: JobNotFoundException when no job has the id, JobNotFinishedException, with the job's State, when it has not succeeded, and JobResultNotStoredException when it succeeded without a stored result, with the Size and the Limit when the result was dropped. All three are InvalidOperationExceptions, so one catch takes them all; on a store that keeps no results it throws NotSupportedException.

Waiting. WaitForCompletionAsync returns the job once it has succeeded, been dead-lettered or been cancelled, or as it reads when the timeout passes, so its State tells a finish from a timeout; null means no job has the id. A failed attempt that will be retried does not end the wait. A job that finishes on the waiting node ends it at once; one that finishes on another node is seen within one PollInterval:

// Returns as soon as the quote has finished, on this node or another, or once a minute has passed.
var job = await jobs.WaitForCompletionAsync(quote.JobId, TimeSpan.FromMinutes(1), ct);
decimal? price = job?.State == JobState.Succeeded ? await jobs.GetResultAsync<decimal>(quote.JobId, ct) : null;

Proved by EnqueueManyTests.ABulkCall_StoresEveryJobEnqueued_InOneStoreCall_AndReturnsTheirIdsInTheCallsOrder, BulkEnqueueTests.WorkersOnTwoNodesClaimingWhileBulkCallsLand_AndAReaderPollingTheTable_NeverSeePartOfACall, BulkRoundTripTests.ABulkEnqueue_IsExactlyOneStatement_WhateverItsSize, EnqueueManyKeyTests.ABulkCallWithAHeldKey_AnswersTheHolderForThatJob_AndStoresTheRest, EnqueueManyKeyTests.ABulkCallWithAKeyHeldUnderError_StoresNoneOfItsJobs_AndFailsNamingTheHolder, JobResultTests.AResultOneByteOverTheLimit_IsDropped_TheJobSucceeds_AndOneWarningGivesTheSizeAndTheLimit, GetResultTests.AJobThatHasNotSucceeded_IsAnErrorNamingItsState, GetResultTests.EveryReasonThereIsNoResultToRead_IsAnInvalidOperationException_SoOneCatchTakesThemAll, WaitForCompletionTests.AJobFinishedOnTheWaitingNode_EndsTheWaitAtItsOutcome_WithoutTheClockMoving, WaitForCompletionTests.AJobFinishedByASecondNode_IsSeenByTheWaitingNodesNextRead and ShippingQuotesTests.TheQuotes_AreEnqueuedInOneCall_AndEachPriceIsReadOnceItsQuoteHasSucceeded.

Tags and correlation ids

A tag files a job so it can be found later: by the dashboard's tag filter, or by a bulk requeue of dead letters with that tag. A tag is one string, key or key:value, such as billing or tenant:acme, and a query matches the exact string, so tenant does not find tenant:acme. A job gets its tags from four places, all kept: EnqueueOptions.Tags, [Tag("...")] on the job type (once per tag), an IEnqueueMiddleware registered in dependency injection, which runs for every job created through IJobClient and can also set typed parameters such as a tenant id, and the running handler, through ctx.AddTagAsync. A tag given twice is kept once, and a job carries at most 20. A tag that is empty, has more than one :, an empty key or value, white space at either end or next to the :, or a control character fails the call with ArgumentException, and nothing is stored. A handler's tag is stored and indexed at once and kept whatever the attempt's outcome. A job's tags are stored and indexed in the same write as the job, kept by a requeue, and removed with the job. Enqueue middleware does not run for jobs Bellhop creates itself, such as recurring occurrences, which carry their job type's [Tag] tags only; continuations, chain steps and batch jobs get only their own tags, never their parent's.

A correlation id ties together the jobs of one flow. A job created during a job's execution, and every continuation and chain step, carries its parent's correlation id; a batch continuation carries that of the call that created the batch. Any other job captures one when it is created, from the first source that has one: the application's ICorrelationIdAccessor, the request header that Bellhop:CorrelationIdHeader names, read through the application's IRequestHeaders (an ASP.NET Core application adapts IHttpContextAccessor in a few lines), the trace id of the caller's current Activity, or else a new random id of the same shape. Every job of one EnqueueManyAsync, ChainAsync or CreateBatchAsync call shares one. A source that gives a value that is too long, padded or holds a control character is skipped with warning 2280, which never logs the value. Nothing can change a job's correlation id after it is created, so a handler cannot rewrite it: it is a field of the job, not a parameter. The handler reads it as ctx.CorrelationId, and the dashboard's jobs list filters by it.

Proved by TagTests.ATagFromOneSourceOnItsOwn_IsCarriedByTheJob_AndAQueryOfTheIndexByItReturnsTheJob, TagTests.AKeyTagAndAKeyValueTag_AreBothCarried_AndAQueryForEachReturnsTheJob_ButAKeyMatchesOnlyItself, TagTests.AHandlersTag_IsStoredAndFiledAtOnce_WhileTheJobRuns_AndKeptWhenTheAttemptFails, TagTests.AMalformedTagInTheOptions_FailsEveryCreatingCall_WithAMessageThatNeverQuotesIt_AndStoresNothing, TagPropertyTests.OverRandomJobsAndTagSources_AQueryByATag_AndItsCount_GiveExactlyTheJobsCarryingIt, EnqueueMiddlewareTests.MiddlewareInDependencyInjection_StampsATagAndATenantId_OnEveryJobOfEveryCreatingMethod_AndFromAHandler, EnqueueMiddlewareTests.ARecurringOccurrence_IsNotStamped_AndCarriesItsTypesTags_AndACapturedCorrelationId, CorrelationIdTests.TheAccessor_WinsOverTheHeaderAndTheCurrentActivity, CorrelationIdTests.ASourceThatGivesAnInvalidValue_FallsThroughToTheNext_WithAWarningThatNeverQuotesTheValue, CorrelationIdTests.EveryJobOfOneCall_SharesOneCapture_AndEachCallCapturesOnce, CorrelationInheritanceTests.HandlersWithDifferentCorrelationIdsRunningAtOnce_GiveEveryChildItsOwnParentsId, CorrelationPropertyTests.OverRandomTreesOfJobs_EveryJobWithAParentCarriesItsParentsCorrelationId and DashboardTagAndCorrelationTests.TheTagAndCorrelationIdFilters_ListTheJobsTaggedAndCorrelatedThroughTheClientAndTheHandler.

Captured logs and progress

Every line written during a handler's run through the application's logger factory, whether through ctx.Logger or an ILogger<T> injected into the handler or its services, is kept with the job when its level is at least CapturedLogLevel (Information by default) and the application's filter rules let it through. A line keeps its time, level, category, message, structured properties, exception and attempt; ctx.Logger's category is the handler type's full name. Lines are stored as the run writes them, and all of them before the attempt's outcome is. Turn capture off for one job type with [CaptureLogs(false)] or ConfigureJob<T>(j => j.CaptureLogs(false)), and for every job with CapturedLogLevel = None. A job's log is one across its attempts and holds at most CapturedLogLimit bytes (256 KB by default): the first lines are kept, and the first line that does not fit ends the log with a truncation mark; each attempt that finds the log full logs event 2292 once. A line that cannot be read, as its formatter or a value's ToString throws, is kept in its place as a line that names only the exception's type. Lines are taken until the run has disposed its services, so a task the handler leaves running is captured only until then. The lines still reach every other logging provider.

Every line written during a handler carries the scope properties JobId, JobName, Attempt, Queue and CorrelationId (null when the job has none), so any provider that reads scopes can attach them. Work the handler starts that outlives the run, such as a timer or a background loop, keeps these properties on its lines, but its lines are no longer captured. Capture is the logging provider with the alias BellhopJobLogs, so ordinary filter rules apply to it alone, such as Logging:BellhopJobLogs:LogLevel:System.Net.Http = Warning. It reads the job from the logger factory's scopes: an application that replaces the logger factory, such as Serilog's UseSerilog or AddSerilog without writeToProviders, or turns scopes off, captures nothing.

A handler reports progress with ctx.ReportProgressAsync(fraction, message), and the job stores the latest report. Once the handler has returned, a report it did not await that is still waiting to be written is dropped, so it never lands after the attempt's outcome.

The dashboard's job detail page shows the job's log, grouped by attempt and with a notice where it was cut, and its latest progress; its JSON API gives them as the job's log and progress. While the page is open it streams new lines and progress as they are stored, and searches the log; the jobs list shows each job's progress bar. See The job page.

Proved by LogCaptureTests.LinesWrittenThroughTheContextsLogger_AreStoredWithTheirTimeLevelCategoryMessagePropertiesAndAttempt_BeforeTheJobsSuccessIsWritten, LogCaptureTests.LinesOfAnInjectedLoggerAndOfATaskTheHandlerStarts_AreStored_WhileALineWrittenOutsideTheRunMeanwhile_IsNot, LogCaptureTests.CaptureTurnedOffGloballyOrForAType_StoresNoLineOfThatTypesJobs_AndMakesNoAppend_WhileOtherTypesStillCapture, LogCaptureLimitTests.AttemptsTogetherWritingMoreThanTheLimit_StoreAnUnbrokenRunAcrossThem_WithinTheLimit_AndALaterAttemptAddsNothing, CaptureProviderTests.AFilterRuleForTheCapturesAlias_KeepsLinesBelowItsLevelOutOfTheJobsLog_WhileTheOtherProviderStillReceivesThem, JobLogScopeTests.EveryLineWrittenDuringAHandler_OfJobsRunningAtOnce_CarriesJobIdJobNameAttemptQueueAndCorrelationIdOfItsJob_OnceEach, CaptureOptionsTests.CaptureOptions_DefaultToInformationAndAbove_And256KBPerJob, ProgressTests.WhileTheJobIsProcessing_ItsLatestReportIsItsProgress_AReportWithoutAMessageLeavesNone_AndTheProgressOutlivesTheRun, InlineCaptureTests.EveryLineOfAnInlineRun_ItsHandlersAndItsClaimAndOutcomeLines_CarriesTheJobsIdentity_OnceEach, UnreadableLineTests.ALineWhoseValueCannotBePrinted_IsKeptAsALineNamingTheExceptionsType_WithItsTimeLevelCategoryAndAttempt_AndTheLaterLinesAreKept, UnreadableLineTests.TheKeptLine_CountsAgainstTheLimit_SoTheFirstLineThatDoesNotFitAfterIt_OrItself_EndsTheLogWithTheMark, CaptureReleaseTests.ALineWrittenAfterTheRunByWorkTheHandlerLeftRunning_CarriesTheJobsScopeProperties_ButIsNotStored, ProgressCloseTests.AHandlerReturningWithoutAwaitingItsReports_HasTheWriteInFlightEndBeforeItsOutcome_TheWaitingReportDropped_AndLaterReportsReachNoStore, JobLogLockTests.WhileAnAppendHoldsTheJobsRow_AnotherSessionInsertsARowReferencingTheJob_WithoutWaiting, DashboardJobsTests.TheDetail_ShowsEveryAttemptsLogLinesInOrder_TheTruncationMark_AndTheLatestProgress, JobPageBrowserTests.WhileThePageIsOpen_ALineWrittenAndAProgressReported_ShowWithoutAReload, JobPageBrowserTests.TheSearch_ShowsOnlyTheLinesContainingTheText_WithoutCase_InTheirMessageCategoryPropertiesOrException_AndSaysHowMany and JobsPageBrowserTests.AJobWithProgress_ShowsABarAtItsFractionWithThePercentage_AndAJobWithoutShowsNone.

Sensitive payload members

Mark a payload member [Sensitive] (from Bellhop.Attributes) and Bellhop masks its value with *** wherever it shows the job: in the dashboard's payload, and in the job's captured log lines. The handler still receives the value as it was enqueued, and Bellhop's spans never carry a payload, a parameter or an exception's message. On a positional record the attribute works with or without property:. Any JSON value of the member is masked, an object or array whole; a null stays null. Members of nested types, of collection elements, of dictionary values (never their keys) and of the derived types a polymorphic member declares with [JsonDerivedType] are covered too, matched by their JSON name in any letter case.

Elsewhere than in the payload, a value is recognised by its text as stored in the payload: a string as it reads or as it is escaped in the JSON, a number as written. So the value is masked where a captured line logs the payload object or the value as a plain argument, or an exception quotes it, and in the dashboard's job detail wherever it shows text: the log, the attempts' failures, the progress message and the parameters. A value the handler formats or transforms otherwise, such as a date in another format, is not. A short value is masked wherever its text appears, even inside unrelated words or numbers. Captured lines are masked as they are stored; the application's other logging providers receive its lines as written. A failed attempt's exception message and text, and a progress message, are masked too when they are stored, before they are cut to the store's limit, so a value cut at the end leaves no part of it behind; the job's events and the other logging providers still receive the application's exception as thrown.

The marked members are read from the System.Text.Json metadata of the job type: that of the registered SystemTextJsonJobSerializer, including a JsonSerializerContext's, or, for another serializer, reflection-based metadata when reflection-based System.Text.Json is enabled. Without either, nothing is masked. A member written by a custom converter, or declared as object, is masked only when it is marked itself. When the metadata of a type the payload reaches cannot be read, or such a type marks its [JsonExtensionData] member, whose entries are written as the type's own members and so cannot be told apart by name, the dashboard shows a notice instead of the payload, as it does for a payload with marked members that is not valid JSON. For such a job it also shows a notice in place of each of its other texts, the parameters' values, the attempts' failures, the progress message and the log lines, as no value could be told apart to mask them. The dashboard knows a job's type from its own registrations, by name or alias, so the node that serves it should register the job types it shows: a job whose name it does not register is shown as stored.

Proved by PayloadMaskTests.SensitiveMembersOfNestedObjects_CollectionElements_AndDictionaryValues_AreMasked_WhileDictionaryKeysAreKept, PayloadMaskTests.AMemberOfADerivedTypeDeclaredWithJsonDerivedType_IsMasked_InAMemberAndInACollection, PayloadMaskTests.ASensitiveValueOfAnyJsonType_BecomesTheMask_AnObjectOrArrayWhole_WhileANullStaysNull, PayloadMaskTests.APositionalRecordsParameter_IsMasked_MarkedWithOrWithoutThePropertyTarget_AndTheOtherMembersAreShown, PayloadMaskTests.AJobTypeTheContextDoesNotInclude_IsUnreadable_SoItsPayloadIsNotShown_AndNoValueIsMaskedElsewhere, SensitiveCaptureTests.AHandlerLoggingThePayloadAndItsSecrets_AndFailingWithOne_LeavesNoSecretInAnyCapturedLine_ButKeepsTheOtherValues, SensitiveTraceTests.TheSpansOfAJobWithSensitiveMembers_EnqueuedRunFailedAndRetried_HoldNoneOfItsValues, DashboardSensitivePayloadTests.AJobWithSensitiveMembers_RunAndDeadLettered_ShowsTheMaskInItsPayload_AndItsValuesOnNoPageOrApiResponse, DashboardSensitivePayloadTests.TheDetailsParametersFailureProgressAndLog_StoredHoldingTheValues_ShowTheMaskInTheirPlace_AndKeepTheRestOfTheirText, DashboardSensitivePayloadTests.AStoredPayload_IsMaskedByTheTypeTheDashboardNodeRegistersForItsNameOrAlias_AndShownAsStoredUnderAnUnregisteredName, DashboardUnmaskableTextTests.AJobWhoseSensitiveValuesCannotBeToldApart_ShowsTheNoticeInPlaceOfEachFreeText_AndKeepsNullsEmptiesAndTheRestOfTheDetail, PayloadMaskTryGetMaskerTests.APayloadWhoseValuesCannotBeToldApart_GivesFalse_AndNoMasker, SensitiveStoredTextTests.AFailureQuotingAValueAtTheStoresLimit_IsStoredWithTheMask_AndNoPartOfTheValue, SensitiveStoredTextTests.AHandlerThrowingOperationCanceledQuotingAValueAfterItsTimeout_IsStoredAsTheTimeout_WithTheValueMasked, SensitiveStoredTextTests.AProgressMessageTheMaskLengthens_IsStoredCutToTheLimit_NeverBetweenTheHalvesOfAPair, ExtensionDataMaskTests.AJobTypeThatMarksItsExtensionDataMember_IsUnreadable_SoTheDashboardShowsTheNotice_AndNoOtherTextCanBeMasked, ExtensionDataMaskTests.AnUnmarkedExtensionDataMember_KeepsTheTypesMask_ItsMarkedMembersMasked_AndTheEntriesShown, InlineCaptureTests.AJobRunInlineInsideAnotherJobsHandler_FilesNoneOfItsClaimOrFailureLinesToTheOuterJobsLog_AndItsHandlersLinesToItsOwn, CaptureReleaseTests.AClosedCapture_NoLongerHoldsTheMasker_SoTheJobsValuesAreNotKeptAliveByIt and SensitivePayloadPropertyTests.OverRandomPayloadsAndValues_NoSensitiveValueAppearsInTheDashboardTheCapturedLogOrTheSpans_AndTheHandlerReceivesEvery.

Retries

A job has 5 attempts by default, the first included. After a handler throws, the job waits 10 seconds, 1 minute, 5 minutes and 30 minutes before its next attempts, each wait varied by up to 20%, and is dead-lettered after its last. Throw PermanentJobFailureException to dead-letter it at once. Failures, timeouts and recovered runs all use up the same attempts. Set MaxAttempts and RetryDelays per call, with ConfigureJob, with [Retry] or globally.

Proved by RetryTests.NothingConfigured_AnAlwaysFailingJob_RunsFiveAttempts_WaitingRoughly10s1m5m30m_ThenIsDeadLetteredForGood and RetryTests.PermanentJobFailure_DeadLettersAtOnce_WithNoRetryAt_WithoutAskingThePolicy.

Timeouts

Every job has a timeout of 5 minutes unless you give it another. A job that ran for an hour under another library times out here after 5 minutes and is retried. Give long jobs their own timeout.

When the timeout passes, the handler's cancellation token is signalled. A handler that honours it fails the attempt with reason Timeout, and the job is retried or dead-lettered like any failure. A handler that ignores its token is abandoned after TimeoutGracePeriod, 30 seconds: the attempt fails the same way and its worker slot is freed, but the handler keeps running in the process and whatever it does later is ignored. So pass ct on to everything a handler awaits.

Set a job type's timeout with an attribute, in seconds:

[JobName("rebuild-search-index")]
[Timeout(3600)]
public sealed record RebuildSearchIndex : IJob;

or for one job when you create it:

await jobs.EnqueueAsync(new RebuildSearchIndex(), new EnqueueOptions { Timeout = TimeSpan.FromHours(2) }, ct);

or for every job that sets none:

builder.Services.AddBellhop(bellhop => bellhop.Configure(options => options.DefaultJobTimeout = TimeSpan.FromMinutes(30)));

The call's timeout wins over ConfigureJob, which wins over the attribute, which wins over DefaultJobTimeout; the result is stored with the job when it is created.

Proved by TimeoutSettingsTests.NothingConfigured_StoresAFiveMinuteTimeoutWithTheJob_AndGivesAThirtySecondGracePeriod, TimeoutTests.TimeoutSetByAttribute_Fluently_OrPerEnqueue_IsTheOneTheRunIsSignalledAfter and TimeoutTests.AttemptOneOfFive_WhoseHandlerIgnoresItsToken_IsAbandoned_AndFailedWithReasonTimeout_WithRetryAtFromTheBackoff.

Misfire

A recurring job misfires when its due instants pass while no worker could trigger it: every node was down, or busy past the instant. An instant the trigger reaches no more than MisfireThreshold (60 seconds) after it is on time and runs, whatever the policy and however many other instants are due with it; one reached later is missed. A worker wakes for each instant of a job it triggers, even one sooner than PollInterval, so on a frequent schedule each pass usually finds one instant due. There is no limit on how far back the trigger looks: after downtime of any length, the first trigger catches up according to the job's MisfirePolicy:

  • RunOnce, the default: one run stands in for all the missed ones, the first on-time run or, when none is on time, a run for the newest due instant.
  • Skip: missed instants are dropped; only on-time instants run.
  • RunAll: one run for each of the newest due instants, up to MaxRunAllOccurrences, 1 by default, up to 1000. On-time instants count toward it, and all run even beyond it.

RunAll with the default maximum of 1 runs only once, and its catch-up runs overlap each other, so the default overlap policy (Skip, below) would skip all but the first. For one run per missed hour, raise both limits:

[JobName("hourly-rollup")]
[Recurring("hourly-rollup", "0 * * * *", MisfirePolicy = MisfirePolicy.RunAll, MaxRunAllOccurrences = 24, OverlapPolicy = OverlapPolicy.Queue, MaxQueuedOccurrences = 24)]
public sealed record HourlyRollup : IJob;

Every miss is recorded, with the instants missed and dropped, logged (events 2127 to 2130) and raised as IJobEvents.OnRecurringMissed.

Proved by MisfireTests.RunOnce_CatchesUpOnceAfterDowntime_LogsWhy_RaisesTheEventOnce_AndRecordsTheMiss, MisfireTests.Skip_AfterDowntime_CreatesNothing_DropsTheMissedInstants_AndSaysSo, MisfireTests.RunAll_KeepsTheMostRecentInstantsUpToItsMaximum_OldestFirst_AndLogsTheOlderOnesItDropped and MisfireTests.OnAScheduleMoreFrequentThanTheThreshold_EveryDueInstantWithinTheThresholdIsOnTime_AndNoneIsMissed.

Overlap

A recurring job overlaps when an occurrence falls due while an earlier one has not finished: its job is still scheduled, enqueued, processing, or failed and waiting for a retry. The OverlapPolicy decides:

  • Skip, the default: the new occurrence starts nothing and is recorded as skipped.
  • Queue: the new occurrence waits for the earlier one, up to MaxQueuedOccurrences waiting at once (1 by default); one more is skipped as QueueFull.
  • Allow: the new occurrence runs beside the earlier one.
  • CancelPrevious: the earlier job is cancelled, or its handler's token signalled if it is running, and the new occurrence starts. Until the earlier handler honours its token, both run.

Every decision is one atomic step in the store, so it holds however many nodes trigger at once.

Proved by ScheduledOverlapTests.UnderSkip_AMinutesTriggerWhileTheEarlierRunProcesses_IsSkipped_AndEnqueuesNothing, ScheduledOverlapTests.UnderQueue_OneOccurrenceWaits_AndTheNextIsSkippedAsQueueFull_WhileTheEarlierRunProcesses and RecurringOverlapWorkerTests.UnderCancelPrevious_TheEarlierRunsHandlerIsSignalled_AndBothRunUntilItHonoursItsToken.

Time zones

A recurring schedule runs in UTC unless you ask for local time: TimeMode.Local with an IANA time zone id, such as Europe/Berlin. The machine's own time zone is never used, so every node computes the same instants. Windows ids such as W. Europe Standard Time are refused on every platform, as is a zone given in UTC mode, so a forgotten TimeMode.Local cannot silently run in UTC. In code:

bellhop.AddRecurring<NightlyReport>("nightly-report", "0 2 * * *", options: new RecurringJobOptions { TimeMode = TimeMode.Local, TimeZone = "Europe/Berlin" });

When the clocks change, a cron schedule in local time behaves like this:

  • A time the clocks skip over runs once, at the first moment after the gap: a 02:30 job runs at 03:00 on the night the clocks go forward, and several skipped times in one gap give one run.
  • A time the clocks pass twice runs once, at its first instance: an hourly job does not run again in the repeated hour.

An interval schedule (@every 01:00:00) ignores time zones and clock changes: it runs at whole multiples of the interval counted from 1970-01-01 00:00 UTC, so an hourly interval does run twice in the repeated local hour.

Proved by DaylightSavingTests.SkippedTime_OccursOnceAtTheEndOfTheGap_AndTheNextDayAsUsual, DaylightSavingTests.HourlyCron_RunsTheRepeatedHourOnce_ButAnHourlyIntervalRunsItTwice, ScheduleTimeZoneTests.WindowsZoneId_IsRejectedOnEveryPlatform, ScheduleTimeZoneTests.UtcModeWithAZone_IsRejected_SoAForgottenLocalModeIsNotSilentlyUtc and CronScheduleTests.Every_IsAnchoredToAFixedGrid_NotToWhenItIsEvaluated.

Validity windows

A recurring job can be limited to a validity window: ActiveFrom and ActiveUntil, instants in whole seconds, both included, either of them optional. Outside the window the schedule's instants are not occurrences of the job at all: none is created on schedule, none is recorded as missed, and the job's next run is its first instant in the window, or none once the window has ended. The job itself stays as it is, and widening the window later brings it back. In code:

bellhop.AddRecurring<NightlyReport>("year-end-report", "0 2 * * *", options: new RecurringJobOptions
{
    ActiveFrom = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero),
    ActiveUntil = new DateTimeOffset(2026, 12, 31, 23, 59, 59, TimeSpan.Zero),
});

The same options set a window through IRecurringJobManager, and configuration sets one too (below). An instant is in the window by its due time, so an instant inside it that a late trigger reaches after the window has ended is caught up as the misfire policy says; use Skip for no run after ActiveUntil at all. Triggering a job now is never limited by its window. Changing a window counts as changing the schedule: the next run is computed again from now.

Proved by ValidityWindowTriggerTests.AJobWithAWindow_TriggeredOnTimeAtEveryInstant_GetsOccurrencesOnlyForTheInstantsInTheWindow_AndNoNextRunOnceItEnds, ValidityWindowProperties.TwoNodesTriggeringOnTime_NeverCreateAnOccurrenceOnScheduleBeforeActiveFromOrAfterActiveUntil_OrWhilePaused, ValidityWindowTriggerTests.AnInstantInTheWindow_FoundLateAfterTheWindowEnded_FollowsTheMisfirePolicy_AndNoInstantAfterTheEndIsMissed and ValidityWindowTriggerTests.TriggeringNow_BeforeTheWindowStartsOrAfterItEnded_StillCreatesTheOccurrence_AndLeavesTheNextRun.

Recurring jobs in configuration

Recurring jobs can also be declared in configuration section Bellhop:RecurringJobs, one entry per job, named by its key:

{
  "Bellhop": {
    "RecurringJobs": {
      "nightly-report": {
        "Job": "nightly-report",
        "Schedule": "0 2 * * *",
        "TimeMode": "Local",
        "TimeZone": "Europe/Berlin",
        "MisfirePolicy": "Skip",
        "ActiveFrom": "2026-12-01T00:00:00Z"
      }
    }
  }
}

Job, the job name of a registered job type, and Schedule are required. The other settings are optional and take the defaults of RecurringJobOptions: TimeMode, TimeZone, MisfirePolicy, MaxRunAllOccurrences, OverlapPolicy, MaxQueuedOccurrences, OrphanPolicy, AllowRuntimeOverride, ActiveFrom, ActiveUntil, and Payload, the job's JSON as text. Policies are written by name, and window bounds as instants with their offset. A setting Bellhop does not read is an error, so a misspelt one never silently falls back to its default.

A job in configuration is treated exactly like one in code. It is stored with origin Configuration and reconciled at start. It is orphaned, or removed under OrphanPolicy Delete, once no running worker node declares it. It cannot be removed while it is not orphaned, and its definition can be edited at runtime only when its entry sets AllowRuntimeOverride. A name is declared in code or in configuration, never both.

The section is read through IOptionsMonitor, so a reload applies without a restart, before the node's next heartbeat, at most one heartbeat interval later. A reload the store fails to take is applied at a later pass, and one that changes no recurring job, such as another setting's, does nothing. Added and changed entries are stored as a start would store them. An unchanged entry writes nothing, so a runtime edit made under AllowRuntimeOverride lasts until the entry itself changes. A reload with an invalid entry is not applied at all: the node keeps every job it declared before and logs RecurringConfigurationRefused (event 2173) once, and again only when the problems change. It tries the reload again at every pass, so one refused only because a runtime-defined job holds a name is applied once that job is removed. At start, the same invalid entry fails the start, naming the job.

Proved by ConfiguredRecurringJobTests.AnEntryAddedWhileTheNodeRuns_IsStoredWithoutARestart_ActiveWithOriginConfiguration_NextDueFromNow, ConfiguredRecurringJobTests.AScheduleChangedInConfiguration_TakesTheNewDefinitionAndHash_KeepsActiveOrPaused_AndRunsFromNow_WithNoCatchUp, ConfiguredRecurringJobTests.AReloadWithAProblem_ChangesNothing_KeepsThePreviousDeclarations_AndIsReportedOnceWhileItsProblemsStayTheSame, ConfiguredRecurringJobTests.AReloadThatTheStoreFailsToRead_IsAppliedAtALaterPass, ConfiguredRecurringStartupTests.AnEntryThatIsNotValid_FailsTheStart_NamingTheJobAndTheProblem_AndStoresNothing and ConfiguredRecurringDifferentialProperties.AJobDefinedInConfiguration_GoesThroughTheSameStatesDefinitionsAndNextRuns_AsTheSameJobDefinedInCode_OnlyItsOriginDiffers.

Namespaces

Several applications can share one store, each in a namespace of its own, named by Bellhop:Namespace (default unless set; 1 to 32 lowercase letters, digits or underscores, starting with a letter). Every node of one application sets the same namespace.

What a namespace keeps to itself:

  • Jobs. A node sees and claims only its namespace's jobs, even when another application has a handler for the same job name on the same queue, and even while that application has no node running: its jobs wait for their own nodes. Their continuations, batches, results and index entries go with them. The client and the dashboard answer another namespace's job id exactly as an id that was never created.
  • Unique keys. A key is held once per namespace, so two applications can each hold charge-order:42.
  • Recurring jobs. Only a namespace's own nodes trigger, judge and orphan its recurring jobs, and their occurrences are jobs of that namespace.
  • Nodes. Unroutable marking, MinNodesAlive and the dashboard count only the namespace's nodes.

What every namespace of the store shares, by name:

  • Queues. Pausing a queue, or limiting its concurrency, applies to that queue in every namespace, and the limit counts every namespace's processing jobs.
  • The maintenance pause, throttles and alerts. A concurrency key's Max and a rate limit count every namespace's jobs with the key. There is one notification lease and one set of rules for the store.
  • Recurring job names. They are unique across the store: adding one whose name another application's namespace holds fails, naming the job but not that namespace.

The IJobStore and IJobIndex services, and every client and manager, work in the node's namespace. Jobs stored before an application set a namespace are the default namespace's; changing an application's namespace moves it to an empty one.

Proved by NamespaceClaimRaceTests.WorkersOfTwoNamespaces_RacingOnOneQueueAndName_ClaimOnlyTheirOwnJobs_NeverOneTwiceAtOnce, NamespaceRaceTests.SlotsOfThreeNamespacesOnOneSchema_CreatingAndClaimingOneJobNameOnOneQueueAtRandom_ClaimOnlyTheirOwnNamespacesJobs_AndNoJobHasTwoUnexpiredClaims, NamespaceHostTests.WhileBHasNoRunningNode_ItsWaitingJobsAreNeverClaimedByAsIdleWorker_AndRunOnceANodeOfBStarts, NamespaceUniqueKeyStoreTests.OneKey_IsHeldByAnActiveJobInEachNamespaceAtOnce_AndADuplicateInOneAnswersThatNamespacesHolder, NamespaceSharedStateStoreTests.ClaimsOfTwoNamespacesRacingForALimitedQueue_TakeNoMoreSlotsBetweenThemThanItsLimit, NamespaceHostTests.ANodeDeclaringARecurringJobWhoseNameAnotherNamespaceHolds_FailsToStart_SayingNamesAreUniqueAcrossTheStore and DashboardNamespaceTests.AsJobDetail_OfAnIdOnlyBHolds_AnswersExactlyAsForAnIdNeverCreated.

HTTP jobs

An HTTP job sends one request when it runs, and its response decides the job. Register them with AddHttpJobs, list the hosts they may reach, and put credentials on a named HttpClient registration that you opt in with UseForBellhopHttpJobs:

builder.Services.AddBellhop(bellhop => bellhop
    .AddWorker()
    .AddHttpJobs()
    .Configure(options => options.DestinationAllowlist = ["api.partner.example", "*.hooks.example.com"]));

// Credentials live on the registration, never in a job's payload, and go only to the hosts it lists.
builder.Services.AddHttpClient("partner")
    .ConfigureHttpClient(client => client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey))
    .UseForBellhopHttpJobs("api.partner.example");

A job is an HttpRequestJob, stored under the job name Bellhop.HttpRequest:

var sync = await jobs.EnqueueAsync(new HttpRequestJob
{
    Method = "POST",
    Url = new Uri("https://api.partner.example/orders/sync"),
    ClientName = "partner",
    Body = """{"since": "2026-11-01"}""",
    ContentType = "application/json",
    Headers = new Dictionary<string, string> { ["X-Request-Source"] = "bellhop" },
    AcceptedStatusCodes = [200, 202],
    SuccessPredicate = new HttpSuccessPredicate { Path = "$.status", EqualTo = "accepted" },
    Timeout = TimeSpan.FromSeconds(10),
}, ct: ct);

The payload. Url is an absolute http or https URL and the only required property. Method is GET by default (also HEAD, POST, PUT, PATCH, DELETE and OPTIONS). Body is sent as UTF-8, as text/plain; charset=utf-8 unless ContentType says otherwise, so a ContentType with another charset is refused. Headers may not set Host, Content-Length, Transfer-Encoding, Connection, Upgrade or Content-Type, and a value holds only visible ASCII, spaces and tabs. ClientName names the registration the request goes through, Bellhop by default, which AddHttpJobs registers without credentials, redirects or cookies; a name that is not opted in fails the attempt. Timeout, 30 seconds by default and at most 1 day, covers the whole exchange, redirects and reading the body included; the HttpClient's own timeout is not used. The job's own attempt timeout (DefaultJobTimeout, or the job's, such as EnqueueOptions.Timeout) bounds the request too: when it ends first, the attempt ends with reason Timeout. In JSON the properties are camelCase whatever the serializer's naming policy: method, url, headers, sensitiveHeaders, body, contentType, clientName, timeout, acceptedStatusCodes, successPredicate and responseCaptureLimit.

The destination allowlist. DestinationAllowlist, in section Bellhop, lists the hosts Bellhop's outbound calls may reach, and is empty by default, so nothing is sent until you add hosts. An entry is a host name, an IP address (IPv6 with or without brackets), or a wildcard *.example.com, which covers every subdomain at any depth but not example.com itself; it has no scheme, port or path, letter case does not matter, and an internationalized name matches in its punycode form. Each node reads its list at start, and the check is made when the request is sent, so a host removed from the list after a job was enqueued is refused. A refused request is never sent: the job is dead-lettered at once with OutboundRequestRefusedException, whose Rule names the rule and whose message names the host, and a warning (event 2240, OutboundRequestRefused) says the same.

Private addresses. A host that only a wildcard entry covers is resolved first, and refused (rule PrivateAddress) when any of its addresses is not globally reachable: private networks, loopback, link-local (169.254.169.254, where clouds serve instance credentials, among them), carrier-grade NAT, multicast and reserved ranges, the local-use NAT64 (64:ff9b:1::/48) and discard-only (100::/64) IPv6 prefixes, and IPv6 addresses that carry one of those IPv4 addresses. A host that is itself an entry is permitted whatever it resolves to, so list an internal service by its own name. When the registration's primary handler is a SocketsHttpHandler, as for the Bellhop client and a plain AddHttpClient(name), the rule is checked again when the connection is made: the host is resolved once more, refused if any address is now private, and the connection goes only to the addresses checked, so a name that answers with a public address first and a private one when the connection is made (DNS rebinding) is refused too. With an HttpClientHandler or another primary handler, a ConnectCallback of your own on the SocketsHttpHandler, or a proxy, only the check before the request holds, and rebinding is not caught: keep the allowlist narrow, it is the main defence. A name that does not resolve fails the attempt like a refused connection.

Redirects. MaxRedirects is 0 by default, so a 3xx is the response: it succeeds the job only when the job lists it among its accepted status codes. Raised (to at most 20), a 301, 302, 303, 307 or 308 is followed only to the same scheme, host and port; any other redirect is the response. A 303, and a 301 or 302 after a POST, continue as a GET without the body. Every hop passes the allowlist again and the registration's handlers run for it. UseForBellhopHttpJobs turns off the redirects a SocketsHttpHandler or HttpClientHandler would follow itself, so a plain AddHttpClient(name) registration keeps these limits.

Credentials. A job whose payload sets an Authorization, Proxy-Authorization or Cookie header, in any letter case, or whose URL carries user information, is refused when it is created, with an error that points to named registrations, and nothing is stored. Enqueue, schedule, bulk enqueue, continuations, chains and IRecurringJobManager throw an ArgumentException; a recurring job declared with AddRecurring or in configuration is rejected when it is loaded, so it fails the start, and a configuration reload that holds it is refused (event 2173). A stored job that carries one anyway is dead-lettered without being sent (rule PayloadCredentials). Other secrets, such as an X-Api-Key header, are not detected; put them on the registration too. A payload names its URL and its registration separately, so a registration opted in without hosts can be used toward any host the allowlist permits, an attacker's subdomain under a wildcard entry included: a registration that carries credentials should always list its hosts, as UseForBellhopHttpJobs("api.partner.example") does above, in the syntax of the allowlist. A job whose URL host, or a followed redirect's, none of them covers is dead-lettered without a request to that host (rule DestinationAllowlist, with a message that names the registration); the allowlist must permit the host as well.

Masking. Name the headers whose values are secret in SensitiveHeaders: the dashboard shows the job's payload with their values replaced by ***, and the stored response masks them too, as it always masks Set-Cookie, Cookie, Authorization and Proxy-Authorization. The dashboard also shows a URL's user information as *** (https://***@host/...), which a payload written straight into the store could carry, and does not show a payload it cannot read well enough to mask, one without a url property included; the stored response masks the user information of a Location or Content-Location URL the same way. Microsoft.Extensions.Http's own logging of an opted-in registration writes no header value.

Results and failures. A response whose status is accepted (any 2xx when AcceptedStatusCodes is empty), and whose body satisfies the success predicate when one is set, succeeds the job, and an HttpJobResponse with its status, headers and body is its result: read it with GetResultAsync<HttpJobResponse>. The body is cut so that its stored UTF-8 form is at most ResponseCaptureLimit bytes, 64 KiB by default and at most 1 MiB, and BodyTruncated says so; the result then meets ResultSizeLimit like any other. Any other response fails the attempt with HttpRequestJobException, so the retry policy decides between a retry and a dead letter, and the response is kept in the job's Bellhop.FailedResponse parameter (HttpRequestJob.FailedResponseParameter), replaced by a later failed attempt's response. It is the response of the last attempt that got one, not necessarily of the last attempt: an attempt that times out after an earlier one got a 503 leaves the 503 there. A kept response whose serialized size exceeds ResultSizeLimit is kept without its body, marked BodyTruncated. A timeout fails the attempt with TimeoutException, and a refused connection, an unknown host or a failed TLS handshake with HttpRequestException; neither stores a response.

Success predicates. {"path": "$.status", "equals": "ok"} holds when the value at the path is the string "ok", or a number, true, false or null written as that text; {"path": "$.id", "exists": true} when the path is present, a JSON null included, and false when it is absent. A body that is not JSON satisfies neither. The path is $ followed by .name, ['name'] and [0] segments only, and is judged on the body as it arrived, up to 1 MiB; a longer body fails the attempt.

In configuration. A recurring HTTP job is declared like any other, with the job's JSON as its Payload:

{
  "Bellhop": {
    "DestinationAllowlist": [ "status.example.com" ],
    "RecurringJobs": {
      "status-ping": {
        "Job": "Bellhop.HttpRequest",
        "Schedule": "*/5 * * * *",
        "Payload": "{\"url\": \"https://status.example.com/ping\", \"successPredicate\": {\"path\": \"$.status\", \"equals\": \"ok\"}}"
      }
    }
  }
}

A trimmed or Native AOT application adds HttpRequestJob, HttpSuccessPredicate and HttpJobResponse to the JsonSerializerContext its job serializer is built from. A registration whose primary handler keeps cookies, as the default handler of AddHttpClient(name) does, shares them among every job that uses it.

Proved by OutboundRefusalTests.NoAllowlistConfigured_EveryHttpJob_IsDeadLetteredOnItsFirstAttempt_WithoutARequest, DestinationGuardTests.AWildcardCoveredName_ResolvingToAPrivateOrLoopbackAddress_IsRefusedByThePrivateAddressRule, DestinationGuardTests.AnIPAddress_InAnyFormAUrlWritesIt_IsNeverCoveredByAWildcard, DestinationGuardTests.OverRandomHostsAllowlistsResolutionsAndSameHostRedirectChains_EveryRequestSent_GoesToAnAllowedHost, RedirectTransportTests.MaxRedirectsThree_ARedirectToAnotherHostOfTheAllowlist_IsNotFollowed_AndIsTheResponse, HttpJobCreationTests.AJobWithACredential_IsRejectedOnEveryCreationPathFromCode_PointingToNamedRegistrations_AndNothingIsStored, HttpJobCreationTests.ARecurringJobInConfigurationWithACredential_IsRejectedWhenItIsLoaded_FailingTheStart_AndNothingIsStored, OutboundRefusalTests.AStoredPayloadThatCarriesCredentials_IsNeverSent_ButDeadLetteredByTheCredentialRule, DashboardHttpJobTests.AJobRunRetriedAndDeadLettered_NeverShowsItsSensitiveHeaderValue_OnAnyPageOrApiResponse_ButShowsItsOtherHeaders, HttpJobExecutionTests.Scn402_A503ToAJobAccepting200And204_FailsTheAttempt_SchedulesARetry_AndKeepsThe503, HttpJobResponseTests.ThePredicate_IsJudgedOnTheBodyAsItArrived_NotOnTheStoredCopyCutToTheLimit, HttpJobTimeoutTests.AServerThatDoesNotAnswerWithinTheTimeout_FailsTheAttempt_StoresNoResponse_AndARetryIsScheduled, SharedPrimaryHandlerTests.AHandlerHandedOutAgainAfterItsLifetimeEnds_ThatHasSentARequest_StillServesTheRegistration, ConnectTimeGuardTests.ANameThatResolvesPublicThenPrivate_IsRefusedWhenTheConnectionIsMade_AndDeadLettered_WithoutAConnection, UrlUserInfoMaskingTests.AUrlsUserInformation_IsReplacedByTheMask_AndTheRestShowsAsWritten, DashboardHttpJobUserInfoTests.AStoredUrlsUserInformation_IsMaskedInTheJobsDetail_AndShownOnNoPageOrApiResponse, RegistrationHostsTests.AJobForAHostTheRegistrationDoesNotList_IsRefusedNamingTheRegistration_BeforeItsHostIsResolvedOrAnythingSent, ResponseBodyBytesTests.ABodyOfUndecodableBytes_IsStoredWithinTheLimitInUtf8Bytes, HeaderValueAndCharsetTests.AJobWithSuchAValue_IsRefusedWhenItIsEnqueued_AndNothingIsStored, MaskedPayloadTextTests.AJsonBody_ShowsItsQuotesAndItsNonAsciiLettersAsWritten, DashboardHttpJobPayloadTextTests.AJsonBody_IsShownAsWrittenInTheJobsDetail_AndTheApiResponseIsValidJson and RefusalWordingTests.ARedirectHopRefusedByThePrivateAddressRule_AfterTheFirstHopWasSent_IsLoggedAndDeadLetteredAtOnce.