NCache as Hangfire Storage Provider
NCache provides a dedicated storage provider for Hangfire via the NCache.Hangfire (NCache) and NCache.OSS.Hangfire (NCache Open Source) packages. By replacing traditional Hangfire storage backends, such as SQL Server or Redis, with NCache, all Hangfire job states, queues, recurring schedules, server registrations, and distributed locks are managed in an in-memory distributed cache cluster.
Important
Hangfire is supported in NCache 5.3.800 and onwards in NCache and 5.3.603 and onwards in NCache Open Source.
Before configuring NCache as a Hangfire storage provider, ensure that the following prerequisites are fulfilled:
Prerequisites
- Install the following NuGet packages in your application, based on your NCache edition:
- NCache:
NCache.Hangfire - NCache Open Source: NCache.OSS.Hangfire
- NCache:
- Include the following namespaces in Program.cs, as appropriate:
NCache.Hangfire(forNCacheStorageOptions)NCache.Hangfire.Extensions(required forUseNCacheStorageextension methods)NCache.OSS.HangfireHangfireHangfire.AspNetCore
- Ensure the target cache is created and running in the NCache cluster.
Important
For ASP.NET Core Users: Since the provider packages depend only on Hangfire.Core, you must install Hangfire.AspNetCore to access vital extension methods including AddHangfire, AddHangfireServer, and UseHangfireDashboard.
Configure NCache as Hangfire Storage
To use NCache with Hangfire, configure your cache settings and pass them to UseNCacheStorage during application startup.
There are two ways to configure NCache as a Hangfire Storage provider in ASP.NET Core depending on your environment and deployment needs:
- Using appsettings.json (Recommended for Production)
- Using
NCacheStorageOptionsin Program.cs
Method 1: Using appsettings.json
This is the recommended approach to manage your cache settings as it allows configuration changes without needing to recompile the application.
Configuring NCache for Hangfire requires two distinct layers. The Hangfire:NCache:CacheName property selects which cache to use for Hangfire jobs, but it does not replace the NCache client’s server-connection configuration. To successfully locate and connect to the cache in clean environments, you must ensure the NCache client is configured to reach the server hosting your cache:
For NCache (Version 5.3.800+): Configure the server nodes and client connectivity using the application's native NCache configuration section in appsettings.json.
For NCache Open Source: Ensure a properly deployed
client.ncconfor supported machine-level client configuration exists so the client knows which server hosts the cache.
First, define your configuration settings in appsettings.json of your project:
{
"Hangfire": {
"NCache": {
"CacheName": "defaultCache",
"EnablePubSubNotifications": true,
"QueuePollInterval": "00:00:10",
"InvisibilityTimeout": "00:10:00",
"DistributedLockTimeout": "00:00:30",
"DurableSubscriptionExpiry": "01:00:00",
"TerminalListTrimInterval": "00:05:00",
"SucceededListSize": 10000,
"FailedListSize": 1000,
"DeletedListSize": 1000
}
}
}
In Program.cs, pass the configuration section directly to UseNCacheStorage:
var builder = WebApplication.CreateBuilder(args);
// Register NCache as the Hangfire storage backend from configuration
builder.Services.AddHangfire(config =>
config.UseNCacheStorage(
builder.Configuration.GetSection("Hangfire:NCache")));
// Start the Hangfire worker server as a hosted service
builder.Services.AddHangfireServer();
var app = builder.Build();
// Enable the Hangfire Dashboard UI
app.UseHangfireDashboard();
app.Run();
UseNCacheStorage binds directly to the configuration section, automatically reading CacheName along with all optional settings. AddHangfireServer starts the background worker threads and storage background processes as an IHostedService, while UseHangfireDashboard exposes the web dashboard backed by NCache storage.
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The parameter breakdown for appsettings.json is as follows:
Note
The parameters with asterisk (*) on their names are the required parameters and the rest are optional.
| Property | Description |
|---|---|
CacheName* |
The name of the target NCache cluster instance to connect to. Set automatically via appsettings.json or passed directly in code. |
EnablePubSubNotifications |
When true, workers receive a wake-up signal through NCache Pub/Sub when a new job is available, then attempt to dequeue the job. When false, workers periodically check the queues for available jobs instead. (Default: true) |
QueuePollInterval |
The interval at which workers or backlog watchers check queues for available jobs. In NCache edition, this defaults to 10 seconds and configures QueueBacklogWatcher as well as the fallback wait when Pub/Sub is disabled. In Open Source, this defaults to 60 seconds and is used only when EnablePubSubNotifications is false. |
InvisibilityTimeout |
The timeout used to determine when an in-flight job becomes stale if its fetched-job heartbeat is no longer renewed, after which it can be recovered by FetchedJobsWatcher and requeued. (Default: 10 minutes) |
DistributedLockTimeout |
The duration an acquired distributed lock remains valid before it expires in NCache. (Default: 30 seconds) |
DurableSubscriptionExpiry (NCache only) |
The duration an exclusive queue topic subscription holds undelivered messages in NCache if a worker process goes offline. (Default: 1 hour) |
TerminalListTrimInterval (NCache only) |
The time interval at which TerminalListTrimmer runs to clean up and trim terminal state lists. (Default: 5 minutes) |
LockAcquireMaxWait (Open Source only) |
The maximum duration a worker will wait and retry while attempting to acquire an internal NCacheLockGuard distributed lock before timing out. (Default: 15 seconds) |
SucceededListSize |
Maximum number of completed jobs stored in the dashboard's Succeeded list before older records are removed. (Default: 10000) |
FailedListSize |
Maximum number of failed jobs stored in the dashboard's Failed list before older records are removed. (Default: 1000) |
DeletedListSize |
Maximum number of cancelled jobs stored in the dashboard's Deleted list before older records are removed. (Default: 1000) |
Method 2: Using NCacheStorageOptions in Program.cs
Configure options programmatically in Program.cs by constructing an NCacheStorageOptions instance directly:
For NCache:
var builder = WebApplication.CreateBuilder(args);
var options = new NCacheStorageOptions
{
CacheName = "defaultCache",
QueuePollInterval = TimeSpan.FromSeconds(10),
InvisibilityTimeout = TimeSpan.FromMinutes(10),
DistributedLockTimeout = TimeSpan.FromSeconds(30),
DurableSubscriptionExpiry = TimeSpan.FromHours(1),
TerminalListTrimInterval = TimeSpan.FromMinutes(5),
EnablePubSubNotifications = true,
SucceededListSize = 10000,
FailedListSize = 1000,
DeletedListSize = 1000
};
builder.Services.AddHangfire(config =>
config.UseNCacheStorage("defaultCache", options));
builder.Services.AddHangfireServer();
var app = builder.Build();
app.UseHangfireDashboard();
app.Run();
For NCache Open Source:
var builder = WebApplication.CreateBuilder(args);
var options = new NCacheStorageOptions
{
CacheName = "defaultCache",
QueuePollInterval = TimeSpan.FromMinutes(1),
InvisibilityTimeout = TimeSpan.FromMinutes(10),
DistributedLockTimeout = TimeSpan.FromSeconds(30),
LockAcquireMaxWait = TimeSpan.FromSeconds(15),
EnablePubSubNotifications = true,
SucceededListSize = 10000,
FailedListSize = 1000,
DeletedListSize = 1000
};
builder.Services.AddHangfire(config =>
config.UseNCacheStorage("defaultCache", options));
builder.Services.AddHangfireServer();
var app = builder.Build();
app.UseHangfireDashboard();
app.Run();
AddHangfire registers NCacheStorage as Hangfire's active storage engine for background task dispatch and job tracking against the specified cache name (defaultCache).
Important
- Leave
EnablePubSubNotificationsset totrueto get faster job start times and avoid unnecessary polling traffic on your cache. - Set
SucceededListSize,FailedListSize, andDeletedListSizeto match the amount of history you actually need, keeping memory usage clean and efficient.
Global Configuration
For non-web applications, console workers, or services that do not use Dependency Injection, configure NCache storage using GlobalConfiguration, as follows.
For NCache:
var options = new NCacheStorageOptions
{
CacheName = "defaultCache",
QueuePollInterval = TimeSpan.FromSeconds(10),
InvisibilityTimeout = TimeSpan.FromMinutes(10),
DistributedLockTimeout = TimeSpan.FromSeconds(30),
DurableSubscriptionExpiry = TimeSpan.FromHours(1),
TerminalListTrimInterval = TimeSpan.FromMinutes(5),
EnablePubSubNotifications = true,
SucceededListSize = 10000,
FailedListSize = 1000,
DeletedListSize = 1000
};
GlobalConfiguration.Configuration.UseNCacheStorage("defaultCache", options);
// Enqueue background tasks anywhere in your application
BackgroundJob.Enqueue(() => EmailService.Send(userId));
For NCache Open Source:
var options = new NCacheStorageOptions
{
CacheName = "defaultCache",
QueuePollInterval = TimeSpan.FromMinutes(1),
InvisibilityTimeout = TimeSpan.FromMinutes(10),
DistributedLockTimeout = TimeSpan.FromSeconds(30),
LockAcquireMaxWait = TimeSpan.FromSeconds(15),
EnablePubSubNotifications = true,
SucceededListSize = 10000,
FailedListSize = 1000,
DeletedListSize = 1000
};
GlobalConfiguration.Configuration.UseNCacheStorage("defaultCache", options);
// Enqueue background tasks anywhere in your application
BackgroundJob.Enqueue(() => EmailService.Send(userId));
NCache Dashboard Metrics
When using the NCache package (NCache.Hangfire), UseNCacheDashboardMetrics runs automatically during startup. This adds 5 real-time monitoring tiles directly to the top of your Hangfire Dashboard (Overview tab):
- Cache Name: The connected NCache cluster instance.
- Active Servers: Current count of active Hangfire processing nodes.
- Registered Queues: All queues recognized across the cluster.
- Item Count: Total live jobs and tracking items in the cache.
- Connected Clients: Active client connections communicating with the cluster.
Logging in Hangfire
The NCache storage provider packages (NCache.Hangfire and NCache.OSS.Hangfire) emit internal diagnostics, lock warnings, and background process events through Hangfire's logging subsystem. In ASP.NET Core applications, logging integration is handled automatically through the standard application logging infrastructure provided by Hangfire.AspNetCore, eliminating the need for manual log provider configuration.