• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

NCache as Hangfire Storage Provider

NCache provides a dedicated storage engine for Hangfire via the NCache.OSS.Hangfire package. 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.

Note

This feature is currently supported in the NCache OpenSource edition.

Important

Hangfire is supported in NCache 5.3.6.2 and onwards.

Before configuring NCache as a Hangfire storage provider, ensure that the following prerequisites are fulfilled:

Prerequisites

  • .NET
  • Install the following NuGet package in your application:
    • OpenSource: NCache.OSS.Hangfire
  • Include the following namespaces in Program.cs:
    • NCache.OSS.Hangfire
    • Hangfire
    • Hangfire.AspNetCore
  • Ensure the target cache is created and running in the NCache cluster.

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 NCacheStorageOptions in 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. First, define the configuration section in appsettings.json of your project.

{
  "Hangfire": {
    "NCache": {
      "CacheName": "demoCache",
      "QueuePollInterval": "00:00:15",
      "InvisibilityTimeout": "00:05:00",
      "DistributedLockTimeout": "00:00:03",
      "LockAcquireMaxWait": "00:00:05",
      "EnablePubSubNotifications": true,
      "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 into UseNCacheStorage 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 time interval at which workers query NCache queues for available jobs. Used only when EnablePubSubNotifications is false; ignored in Pub/Sub mode. (Default: 60 seconds)
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 and requeued at the front of the queue. (Default: 10 minutes)
DistributedLockTimeout The duration an acquired distributed lock remains valid before it expires in NCache. (Default: 30 seconds)
LockAcquireMaxWait The maximum time a worker will wait and retry while attempting to acquire an NCache distributed lock. (Default: 15 seconds)
SucceededListSize Maximum number of completed jobs stored in the dashboard's Succeeded list before older records are deleted. (Default: 10000)
FailedListSize Maximum number of failed jobs stored in the dashboard's Failed list before older records are deleted. (Default: 1000)
DeletedListSize Maximum number of cancelled jobs stored in the dashboard's Deleted list before older records are deleted. (Default: 1000)

Method 2: Using NCacheStorageOptions in Program.cs

Configure options programmatically in Program.cs by constructing an NCacheStorageOptions instance directly:

var builder = WebApplication.CreateBuilder(args);

var options = new NCacheStorageOptions
{
    QueuePollInterval = TimeSpan.FromSeconds(15),
    InvisibilityTimeout = TimeSpan.FromMinutes(5),
    DistributedLockTimeout = TimeSpan.FromSeconds(30),
    LockAcquireMaxWait = TimeSpan.FromSeconds(15),
    EnablePubSubNotifications = true,
    SucceededListSize = 10000,
    FailedListSize = 1000,
    DeletedListSize = 1000
};

// Configure NCache storage with explicit options
builder.Services.AddHangfire(config =>
    config.UseNCacheStorage("demoCache", options));

// Start the Hangfire worker server
builder.Services.AddHangfireServer();

// To use default storage settings, omit the options parameter:
// builder.Services.AddHangfire(config => config.UseNCacheStorage("demoCache"));

var app = builder.Build();

// Enable the Hangfire Dashboard UI
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 (demoCache).

Important
  • Leave EnablePubSubNotifications set to true to get faster job start times and avoid unnecessary polling traffic on your cache.
  • Set SucceededListSize, FailedListSize, and DeletedListSize to 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.

var options = new NCacheStorageOptions
{
    QueuePollInterval = TimeSpan.FromSeconds(15),
    InvisibilityTimeout = TimeSpan.FromMinutes(5),
    DistributedLockTimeout = TimeSpan.FromSeconds(30),
    LockAcquireMaxWait = TimeSpan.FromSeconds(15),
    EnablePubSubNotifications = true,
    SucceededListSize = 10000,
    FailedListSize = 1000,
    DeletedListSize = 1000
};

// Initialize NCache storage globally with options
GlobalConfiguration.Configuration.UseNCacheStorage("demoCache", options);

// Or initialize with default options:
// GlobalConfiguration.Configuration.UseNCacheStorage("demoCache");

// Enqueue background tasks anywhere in your application
BackgroundJob.Enqueue(() => EmailService.Send(userId));

Logging in Hangfire

NCache.OSS.Hangfire emits internal diagnostics, lock warnings, and background process events through Hangfire's logging subsystem (ILog). To route these diagnostics into ASP.NET Core logging providers (such as Console or Debug), register a logging bridge in Program.cs after building the application:

var app = builder.Build();

// Route Hangfire and NCache storage logs into Microsoft.Extensions.Logging
GlobalConfiguration.Configuration.UseLogProvider(
    new MicrosoftLoggingProvider(app.Services.GetRequiredService<ILoggerFactory>()));

app.UseHangfireDashboard();
app.Run();

See Also

.NET Integrations
IDistributedCache

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top