Skip to main content

Masterly.NightShift documentation

Masterly.NightShift runs background jobs in .NET applications: fire-and-forget, delayed, recurring and continuation jobs. Jobs are stored in a database you already run (SQL Server ships in the box), so they survive restarts and deploys, and a built-in dashboard shows what is happening.

New here? Read Core concepts, then follow the ASP.NET Core quick start or the console and Worker Service quick start. You'll have a job running and visible in the dashboard in a few minutes.

Coming from Hangfire? Start with Migrating from Hangfire. Your existing SQL Server data keeps working.

A first look​

using Masterly.NightShift;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("NightShift")
?? throw new InvalidOperationException("Connection string 'NightShift' is missing.");

builder.Services.AddNightShift(config => config
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(connectionString));
builder.Services.AddNightShiftServer();

var app = builder.Build();

app.MapNightShiftDashboard(); // served at /nightshift

app.MapPost("/users/{id:int}/welcome", (int id, IBackgroundJobClient jobs) =>
{
jobs.Enqueue<EmailService>(email => email.SendWelcome(id));
return Results.Accepted();
});

app.Run();

AddNightShift configures the storage, AddNightShiftServer starts the workers that run jobs, and Enqueue stores a call to EmailService.SendWelcome(id) that a worker runs as soon as it is free. If it throws, it is retried automatically.

Remastered from Hangfire​

Masterly.NightShift is a remastered fork of Hangfire 1.8.25. It keeps Hangfire's programming model and reads your existing Hangfire SQL Server data. It was refactored for .NET 8 and later, and a source generator writes direct calls to your job methods instead of calling them through reflection. It is an independent project, not affiliated with or endorsed by Hangfire OÜ.

Hangfire 1.8.25NightShift 1.0
Platforms.NET Framework 4.5.1 and later, .NET Standard.NET 8 and later only
Calling your job methodMethodInfo.InvokeSource-generated direct call, with compiled and reflection fallbacks
JSONNewtonsoft.JsonSystem.Text.Json
Batches and fan-inPaid (Hangfire Pro)Included
Semaphores and rate limitsPaid (Hangfire Ace)Included
Circuit breaker, duplicate preventionNot includedIncluded
Timeouts, deadlines, run windows[LatencyTimeout] onlyIncluded
Progress, console, resume after failureCommunity packagesIncluded
OpenTelemetry, Prometheus, health checks, alertsCommunity packagesIncluded
StorageSQL Server, paid Redis, many community storagesSQL Server, Entity Framework Core (PostgreSQL, MySQL, SQLite...), Redis, MongoDB and in memory, all passing one conformance suite
Support and track recordPaid support available; more than a decade in productionCommunity support through GitHub; 1.0 is the first release

NightShift compared with Hangfire has the full comparison and when to stay on Hangfire.

Benchmarks​

Measured on .NET 10 against Hangfire 1.8.25. The SQL Server rows used SQL Server 2022 in a container.

OperationHangfireNightShift
Call the job method17.0 ns3.5 ns
Serialize a job2.38 µs, 10.97 KB1.59 µs, 1.84 KB
Deserialize a job3.34 µs, 17.32 KB3.04 µs, 2.08 KB
Run an empty job through all filters0.58 µs, 1.62 KB0.27 µs, 0.63 KB
Enqueue in a loop, SQL Server174 jobs/s218 jobs/s
Enqueue from 64 callers at once1,523 jobs/s3,179 jobs/s
Create many jobs at onceNo bulk API4,116 jobs/s with EnqueueMany
Process from SQL Server562 to 648 jobs/s606 to 794 jobs/s; 974 to 1,000 with AllowDelayedDurability

NightShift needs half the round trips to create a job, shares them between concurrent callers, and creates many jobs at once with EnqueueMany. A loop of single Enqueue calls gains the least, because each call waits for the database to store its job. Running a job allocates about 60% less memory, and serializing one over 80% less. Benchmarks has the .NET 8 numbers, what they mean, and how to run them yourself.

Find what you need​

Getting started​

PageWhat it covers
InstallationPackages, target frameworks, which packages your app needs
Quick start: ASP.NET CoreFrom an empty web app to a job in the dashboard
Quick start: console and Worker ServiceGeneric Host apps, and plain console apps without DI
Core conceptsJobs, states, storage, servers, workers, queues, filters: the mental model

Jobs​

PageWhat it covers
Fire-and-forget jobsRun something now, in the background
Delayed jobsRun something later, including plain-English times like "tomorrow at 9am"
ContinuationsRun a job after another one finishes, and pass its result along
Fan-in and batchesWait for a whole set of jobs; create jobs as a group
Job argumentsWhat you can pass, how it's serialized, how the job's class is created
CancellationCancellation tokens, shutdown, deleting a running job
Progress, console and checkpointsShow a job's progress and log lines live; resume after a failure
Tags and notesLabel jobs so you can find them; attach notes
Job catalogLet operators start chosen jobs from the dashboard
Managing jobsDelete, requeue, reschedule, change state, query jobs
Source-generated invokersHow job methods are called without reflection
TestingUnit tests for code that creates jobs, job classes and filters; integration tests against LocalDB

Recurring jobs​

PageWhat it covers
Creating recurring jobsAddOrUpdate, options, triggering and removing
CRON and schedulesCRON expressions, the Cron helpers, CronBuilder, plain-English schedules
Pausing and updatingPause, resume and change a schedule without redeploying
Time zones and misfiresDaylight saving changes, downtime, missed runs
Recurring job manifestExport and import recurring jobs as JSON

Filters​

PageWhat it covers
RetriesAutomatic retries, retry-later, in-process retries, circuit breakers
ConcurrencyOne at a time, throttling, rate limits, duplicate prevention
TimingTimeouts, deadlines, run windows and blackouts, how long data is kept
BehaviorQueues, display names, culture, invocation logging, hiding secrets
Custom filtersWriting your own filters, interceptors and state handlers

Server​

PageWhat it covers
Server optionsEvery BackgroundJobServerOptions property
Queues and workersWorker counts, queues, several servers, graceful shutdown
Drain modeStop starting new jobs, for the whole system, a queue or a server
Keep-aliveKeep IIS-hosted servers from being shut down when idle
Dependency injectionWhat AddNightShift and AddNightShiftServer register; job activation and scopes
Background processesYour own code running in a loop on every server, such as an outbox relay or a cache warmer

Storage​

PageWhat it covers
SQL Server storageSetup, connection strings and factories, permissions
SQL Server optionsEvery SqlServerStorageOptions property and when to change it
Schema and upgradesTables, schema versions, automatic and manual install, purging
Entity Framework Core storageAny EF Core provider; staging jobs so they commit with SaveChanges
Redis storageKey layout, Lua transactions, pub/sub wake-ups, clusters
MongoDB storageReplica sets, collections, TTL indexes
In-memory storageFor development and tests
Custom storageWriting a storage for another database

Dashboard​

PageWhat it covers
SetupAdding the dashboard to your app; every DashboardOptions property
AuthorizationWho may see the dashboard, read-only access, a production checklist
PagesEvery page and what you can do on it
CustomizationYour own pages, menu items, metrics, styles and languages

Monitoring​

PageWhat it covers
OpenTelemetryTraces and metrics through UseTelemetry()
Alerts and webhooksAlerts for failures and missed deadlines, sent to Slack, Teams or any URL
Audit log and activity feedWho did what in the dashboard; what happened recently
InsightsPer-method and per-queue statistics, history, the Prometheus endpoint
Health checks and probesASP.NET Core health checks, /health and /metrics for probes and scrapers
LoggingHow the library logs, and how to control it

Configuration​

PageWhat it covers
Global configurationEvery Use* and Set* configuration method
SerializationHow arguments and state are stored as JSON with System.Text.Json
Compatibility levelsStorage formats, and upgrading servers one at a time

Help and reference​

PageWhat it covers
TroubleshootingCommon problems, their causes and fixes
NightShift compared with HangfireDifferences, benefits, when to stay on Hangfire
BenchmarksSpeed and memory use next to Hangfire, and how to measure them yourself
Migrating from HangfirePackage and API mapping, what changed, a step-by-step checklist
What's newFeatures added on top of Hangfire, with examples
Changes from HangfireEverything that behaves differently, and why
RoadmapPlanned work that isn't in 1.0 yet

Working on the library​

PageWhat it covers
ContributingBuilding, testing, conventions, releasing
ArchitectureHow the source is organized and how a job flows through the code
Architecture blueprintThe design behind the features added on top of Hangfire
Dashboard Razor planHow the dashboard pages are compiled