• 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 provider for Hangfire via the NCache.Hangfire (Enterprise) and NCache.OSS.Hangfire (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.8 and onwards in NCache and 5.3.6.2 and onwards in NCache OpenSource.

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

Prerequisites

  • .NET
  • Install the following NuGet packages in your application, based on your NCache edition:
    • Enterprise: NCache.Hangfire
    • OpenSource: NCache.OSS.Hangfire
  • Include the following namespaces in Program.cs, as appropriate:
    • NCache.Hangfire
    • 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",
      "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 Enterprise, 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 (Enterprise only) The duration an exclusive queue topic subscription holds undelivered messages in NCache if a worker process goes offline. (Default: 1 hour)
TerminalListTrimInterval (Enterprise 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:

var builder = WebApplication.CreateBuilder(args);

var options = new NCacheStorageOptions
{
    CacheName = "demoCache",
    EnablePubSubNotifications = true,
    QueuePollInterval = TimeSpan.FromSeconds(10),
    InvisibilityTimeout = TimeSpan.FromMinutes(10),
    DistributedLockTimeout = TimeSpan.FromSeconds(30),

    // Enterprise-specific options
    DurableSubscriptionExpiry = TimeSpan.FromHours(1),
    TerminalListTrimInterval = TimeSpan.FromMinutes(5),

    // OpenSource-specific option (omitted in Enterprise)
    // LockAcquireMaxWait = TimeSpan.FromSeconds(15),

    SucceededListSize = 10000,
    FailedListSize = 1000,
    DeletedListSize = 1000
};

builder.Services.AddHangfire(config =>
    config.UseNCacheStorage("demoCache", 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 (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
{
    CacheName = "demoCache",
    EnablePubSubNotifications = true,
    QueuePollInterval = TimeSpan.FromSeconds(10),
    InvisibilityTimeout = TimeSpan.FromMinutes(10),
    DistributedLockTimeout = TimeSpan.FromSeconds(30),

    // Enterprise-specific options
    DurableSubscriptionExpiry = TimeSpan.FromHours(1),
    TerminalListTrimInterval = TimeSpan.FromMinutes(5),

    // OpenSource-specific option
    // LockAcquireMaxWait = TimeSpan.FromSeconds(15),

    SucceededListSize = 10000,
    FailedListSize = 1000,
    DeletedListSize = 1000
};

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

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

Enterprise Dashboard Metrics

When using the Enterprise 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 (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