Skip to content
Edit this page

Recipes

Bellhop ships no plugins for these; each is a short sample you copy into your application and own. They compile against Bellhop's public API in this repository's build, under snippets/Bellhop.Docs.Snippets/Recipes, and tests run them.

A distributed lock from a handler

Bellhop needs no lock for itself: every claim, retry and recurring decision is one atomic step in the job store, and no Bellhop package references a lock library. Your handler may still need one for a resource of its own, such as a folder other services write too. Use any IDistributedLockProvider from the DistributedLock family (MIT), for example PostgresDistributedSynchronizationProvider from DistributedLock.Postgres, registered in dependency injection:

[JobName("export-invoices")]
public sealed record ExportInvoices(DateOnly Day) : IJob;

public sealed class ExportInvoicesHandler(IDistributedLockProvider locks, IInvoiceExporter exporter) : IJobHandler<ExportInvoices>
{
    public async Task HandleAsync(ExportInvoices job, JobContext ctx, CancellationToken ct)
    {
        // The lock guards the export folder other services also write, which Bellhop itself never needs a lock for.
        // A lock not acquired in time throws TimeoutException, so the attempt fails and is retried.
        await using var handle = await locks.AcquireLockAsync("invoice-export-folder", TimeSpan.FromSeconds(30), ct);
        await exporter.ExportAsync(job.Day, ct);
    }
}

The lock makes runs that overlap wait for each other; it does not make a job run once. A job can still run twice (see at-least-once delivery), a handler on a node that lost its lease may still hold the lock, and a lock whose connection drops is lost while the handler runs, so the work inside stays idempotent.

A [Lock("name")] execution middleware

For teams that prefer to declare locks on the job, as Hangfire's [DisableConcurrentExecution] did: an attribute, and execution middleware that takes the lock around the handler.

/// <summary>Runs every job of this type while holding the named distributed lock.</summary>
/// <param name="name">The lock's name; while one job holds it, no other job that names it runs.</param>
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class LockAttribute(string name) : Attribute
{
    /// <summary>The lock's name.</summary>
    public string Name { get; } = name;

    /// <summary>How long an execution waits for the lock before its attempt fails; 30 seconds by default.</summary>
    public int TimeoutSeconds { get; init; } = 30;
}
public sealed class LockMiddleware(IDistributedLockProvider locks) : IJobMiddleware
{
    public async Task InvokeAsync(JobExecutionContext ctx, JobExecutionDelegate next)
    {
        var attribute = ctx.JobType.GetCustomAttribute<LockAttribute>();
        if (attribute is null)
        {
            await next(ctx);
            return;
        }

        await using var handle = await locks.AcquireLockAsync(
            attribute.Name, TimeSpan.FromSeconds(attribute.TimeoutSeconds), ctx.CancellationToken);
        await next(ctx);
    }
}

Register it for the job types that carry the attribute only, so no other job pays for it:

// Register an IDistributedLockProvider from the DistributedLock family, such as DistributedLock.Postgres, too.
builder.Services.AddBellhop(bellhop => bellhop.UseMiddleware<LockMiddleware>(jobType => jobType.IsDefined(typeof(LockAttribute), inherit: false)));
[JobName("rebuild-reports")]
[Lock("reports")]
public sealed record RebuildReports : IJob;

A run that cannot take the lock within its timeout fails with TimeoutException and is retried with the job's backoff, so the wait counts against the job's own timeout and attempts.

A Mediator bridge

Run Mediator requests as background jobs: the request is the job, and its Mediator handler does the work. The bridge is execution middleware that sends the job through Mediator and ends the execution there.

This compiles against Mediator 3.0.2, which is MIT-licensed. If you use MediatR, the bridge is the same against MediatR's ISender and IBaseRequest; MediatR 13 and later need a commercial licence for many uses.

[JobName("send-invoice")]
public sealed record SendInvoice(Guid InvoiceId) : IJob, IRequest;

public sealed class SendInvoiceHandler(IInvoiceMailer mailer) : IRequestHandler<SendInvoice>
{
    public async ValueTask<Unit> Handle(SendInvoice request, CancellationToken cancellationToken)
    {
        await mailer.SendAsync(request.InvoiceId, cancellationToken);
        return Unit.Value;
    }
}
public sealed class MediatorBridge(ISender sender) : IJobMiddleware
{
    public async Task InvokeAsync(JobExecutionContext ctx, JobExecutionDelegate next)
    {
        // Not calling next ends the execution and the job succeeds: the request's Mediator handler is the job's work.
        await sender.Send(ctx.Job, ctx.CancellationToken);
    }
}

// Bellhop registers a job type only with a handler; the bridge ends every execution before it is reached.
public sealed class SentThroughMediator<TRequest> : IJobHandler<TRequest>
    where TRequest : IJob, IBaseRequest
{
    public Task HandleAsync(TRequest job, JobContext ctx, CancellationToken ct) =>
        throw new InvalidOperationException(
            $"{typeof(TRequest).Name} is sent through Mediator; add the {nameof(MediatorBridge)} middleware for it.");
}

Mediator generates AddMediator at compile time: reference Mediator.SourceGenerator from the application project only, and Mediator.Abstractions from every project that declares requests or handlers.

builder.Services.AddMediator();
builder.Services.AddBellhop(bellhop => bellhop
    .AddJob<SendInvoice, SentThroughMediator<SendInvoice>>()
    .UseMiddleware<MediatorBridge>(jobType => typeof(IBaseRequest).IsAssignableFrom(jobType))
    .AddWorker());

Enqueue the request like any job, jobs.EnqueueAsync(new SendInvoice(invoiceId)), from code that has IJobClient. An exception from the Mediator handler fails the attempt, which is retried as usual.

  • Add the bridge after every other middleware: it ends the pipeline, so middleware added after it never runs for the requests it sends.
  • Authorize before you enqueue. The request runs in the background with no signed-in user, so a Mediator pipeline behavior that checks the current user sees none.

Carbon-aware scheduling

Run flexible work when the grid is cleanest, with an ISchedule of your own. A schedule must give every node the same instants, so it may not read the clock or call a forecast service while it computes; this one reads a fixed daily profile instead, the typical carbon intensity of each local hour that grid operators publish, and runs once a day at the cleanest hour of a window:

/// <summary>
/// Occurs once a day, at the start of the hour from <c>earliest</c> to <c>latest</c> whose typical carbon intensity is
/// lowest (the earliest such hour on a tie), on the recurring job's local clock.
/// </summary>
public sealed class CarbonAwareSchedule : ISchedule
{
    private readonly int[] _hoursBestFirst;
    private readonly string _label;

    /// <param name="earliest">The earliest whole hour to start at.</param>
    /// <param name="latest">The latest whole hour to start at.</param>
    /// <param name="hourlyIntensity">The typical intensity of each local hour 0 to 23, such as the grid operator's gCO2/kWh.</param>
    public CarbonAwareSchedule(TimeOnly earliest, TimeOnly latest, IReadOnlyList<double> hourlyIntensity)
    {
        ArgumentNullException.ThrowIfNull(hourlyIntensity);
        if (earliest.Ticks % TimeSpan.TicksPerHour != 0 || latest.Ticks % TimeSpan.TicksPerHour != 0 || earliest > latest)
        {
            throw new ArgumentException("The window must run from a whole hour to the same or a later whole hour.", nameof(latest));
        }

        if (hourlyIntensity.Count != 24 || hourlyIntensity.Any(value => !double.IsFinite(value) || value < 0))
        {
            throw new ArgumentException("Give 24 finite, non-negative intensities, one per local hour.", nameof(hourlyIntensity));
        }

        _hoursBestFirst = [.. Enumerable.Range(earliest.Hour, latest.Hour - earliest.Hour + 1)
            .OrderBy(hour => hourlyIntensity[hour]).ThenBy(hour => hour)];
        var values = string.Join(",", hourlyIntensity.Select(value => value.ToString(CultureInfo.InvariantCulture)));
        _label = string.Create(CultureInfo.InvariantCulture, $"carbon-aware {earliest:HH:mm}-{latest:HH:mm} [{values}]");
    }

    public DateTimeOffset? GetNextOccurrence(DateTimeOffset after, TimeZoneInfo timeZone)
    {
        ArgumentNullException.ThrowIfNull(timeZone);
        var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(after, timeZone).DateTime);

        // Today's occurrence may have passed, and a clock change or a skipped date can leave tomorrow without one. Zones
        // do not lose two dates in a row, so the day after has one; the fourth date is a spare.
        for (var day = today; day <= today.AddDays(3); day = day.AddDays(1))
        {
            if (OccurrenceOn(day, timeZone) is { } occurrence && occurrence > after)
            {
                return occurrence;
            }
        }

        return null;
    }

    // The stored label: it changes whenever the window or the profile, and so the occurrences, do.
    public override string ToString() => _label;

    private DateTimeOffset? OccurrenceOn(DateOnly day, TimeZoneInfo timeZone)
    {
        foreach (var hour in _hoursBestFirst)
        {
            var local = day.ToDateTime(new TimeOnly(hour, 0));
            if (timeZone.IsInvalidTime(local))
            {
                continue; // skipped when the clocks go forward: the next best hour that day runs instead
            }

            // An hour the clocks go back over happens twice; its first instance has the larger offset.
            var offset = timeZone.IsAmbiguousTime(local) ? timeZone.GetAmbiguousTimeOffsets(local).Max() : timeZone.GetUtcOffset(local);
            return new DateTimeOffset(local, offset).ToUniversalTime();
        }

        return null;
    }
}
bellhop.AddRecurring<RecalculateRecommendations>(
    "recalculate-recommendations",
    new CarbonAwareSchedule(new TimeOnly(1, 0), new TimeOnly(5, 0), profile),
    options: new RecurringJobOptions { TimeMode = TimeMode.Local, TimeZone = "Europe/Berlin" });

The stored definition records the schedule by its ToString(), which includes the profile, so a node that starts with a new profile updates the recurring job. To follow a live forecast, load a new profile when the application starts or redeploys; the schedule itself stays deterministic. While a rolling deploy changes the profile, nodes on the old and the new profile can pick different hours, so that day the job may run at both: change the profile away from the window, or accept the extra run, which an idempotent handler makes harmless.