• Facebook
  • Twitter
  • Youtube
  • LinkedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Try NCache
  • Contact Us
Try NCache
Show / Hide Table of Contents

NCache as HybridCache Provider

The NCache HybridCache provider lets your application use Microsoft's HybridCache API with local (L1) and distributed (L2) caching.

  • NCache: L1 is an NCache client cache on the application machine. L2 is its associated distributed cache on the NCache servers. NCache handles synchronization between them.

  • NCache Open Source: L1 is an In-Proc local cache, and L2 is a shared distributed cache. The provider uses a Pub/Sub backplane to keep application instances synchronized.

Important

HybridCache is supported in NCache 5.3.800 and onwards in NCache and 5.3.6.2 and onwards in NCache Open Source.

NCache handles synchronization through its client cache feature. NCache Open Source uses the Pub/Sub backplane. Each of the mechanisms are described in the sections below.

There are two ways to configure NCache as a HybridCache provider in ASP.NET Core depending on your environment and deployment needs:

  • Using appsettings.json (Recommended for Production)
  • Using an Action Delegate in Program.cs

How the Pub/Sub Backplane Works in NCache Open Source

The Pub/Sub backplane operates completely transparently. It requires no manual configuration, subscription management, or maintenance, running automatically in the background from the moment your application starts.

On startup: During Dependency Injection (DI) initialization, the NCache HybridCache provider establishes a connection to the remote NCache cluster and subscribes to a dedicated, internal Pub/Sub topic. Every application instance (node) maintains its own subscription to this topic to ensure cluster-wide cache synchronization.

When any node calls SetAsync or RemoveAsync:

  • The value is written to (or removed from) the L2 NCache cluster.
  • The provider publishes a message on the internal Pub/Sub topic containing the affected key.
  • Every other subscribed node receives the message and immediately evicts or refreshes that key in its own L1 cache.

When any node calls RemoveByTagAsync: Tag invalidation uses a lightweight logical approach rather than a bulk delete, which is important for performance at cluster scale:

  • Instead of deleting every item that carries the tag, NCache writes a single sentinel timestamp for the tag into the L2 cluster. This is always one write, regardless of how many cached items carry that tag.
  • The provider publishes a Pub/Sub message broadcasting the tag invalidation.
  • Every node receives the message and records the sentinel locally.
  • From this point forward, on any node, when GetOrCreateAsync retrieves an item, NCache compares the item's creation time against the tag's sentinel timestamp. If the tag was invalidated after the item was created, the item is treated as stale and the factory is called to produce a fresh value.

How Caching Works in NCache Edition

The provider uses one NCache connection for both the client cache (L1) and distributed cache (L2). It does not create a separate Microsoft MemoryCache.

When your application calls GetOrCreateAsync:

  • NCache checks the client cache first.

  • If the entry is missing locally, NCache checks the distributed cache and fills the client cache as appropriate.

  • If neither level contains the entry, the provider calls your factory to load the data and stores the result.

NCache handles updates, removals, and synchronization with other connected client caches. Your application does not need a separate invalidation channel.

Note

How quickly other client caches receive changes depends on the configured client-cache synchronization mode. Changes may not appear immediately in every application instance.

Cache misses for the same key are coordinated within one application process to reduce duplicate factory calls. This does not prevent separate application instances from loading the same key at the same time.

Prerequisites

Before using the HybridCache with NCache, ensure that the following prerequisites are fulfilled:

  • .NET
  • Install the following NuGet package in your application:
    • NCache: NCache.Caching.Hybrid
    • NCache Open Source: NCache.OSS.Caching.Hybrid
  • To utilize the HybridCache provider, include the following namespace in Program.cs:
    • NCache.Caching.Hybrid
    • NCache.OSS.Microsoft.Extensions.Caching.Hybrid
    • Microsoft.Extensions.Caching.Hybrid
  • Configure the caches required by your edition:
    • NCache: Create and start the distributed cache. Configure each application machine as a client, then create and enable its associated client cache.
    • NCache Open Source: Configure an In-Proc local cache for L1 and a distributed cache for L2.
  • Ensure that the application can find the NCache client configuration and connect to the configured server address and port.
  • Make sure that the data being added is serializable.
Important

The NCache edition requires an enabled client cache on every application machine. Setting CacheName does not create or enable it. Initialization fails with an error containing Client cache is not configured if the connection does not use a client cache.

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.

NCache

{
  "ncache": {
    "defaultCache": {
      "server": "20.200.20.11",
      "port": 9800
    }
  },
  "NCacheHybridCache": {
    "CacheName": "defaultCache",
    "Expiration": "00:05:00"
  }
}

The ncache section provides SDK connection settings. You must still create and enable the associated client cache.

Register the provider in Program.cs:

using NCache.Caching.Hybrid;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddNCacheHybridCache(builder.Configuration);

// Alternatively, pass the section directly:
// builder.Services.AddNCacheHybridCache(
//     builder.Configuration.GetSection("NCacheHybridCache"));

var app = builder.Build();
app.Run();



Parameter Description
CacheName Required. The cache name used to connect to the distributed cache with its associated client cache enabled. No default is provided.
Expiration Optional. The default absolute entry lifetime. For example, "00:05:00" means five minutes. Reading an entry does not restart this period.
ServerList Optional. Values are validated but are not used to connect in this implementation. Use the SDK connection settings and client configuration instead.

NCache Open Source

{
  "NCacheHybridCache": {
    "LocalCacheName": "myLocalCache",
    "LocalCacheExpiration": "00:05:00",
    "DistributedCacheName": "myDistributedCache",
    "DistributedCacheExpiration": "00:30:00",
    "ServerList": [
      {
        "Ip": "20.200.20.11",
        "Port": 9800
      },
      {
        "Ip": "20.200.20.12",
        "Port": 9800
      }
    ]
  }
}

Then, in your Program.cs, register the service:

var builder = WebApplication.CreateBuilder(args);

// Method 1: Using specific configuration section
var config = builder.Configuration.GetSection("NCacheHybridCache");
builder.Services.AddNCacheHybridCache(config);

// OR Method 2: Auto-detect configuration section
// builder.Services.AddNCacheHybridCache(builder.Configuration);

// Build the application
var app = builder.Build();
app.Run();
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.

Parameters Description
LocalCacheName* Specifies the name of the NCache In-Proc cache used as local cache (L1). It must be created in NCache before application startup and runs in application process memory for fast access (microseconds).
DistributedCacheName* Specifies the name of the NCache distributed cache used as distributed cache (L2). It must be created in NCache before application startup. Shared across all application instances for data consistency.
LocalCacheExpiration Indicates how long items are retained in the local cache before expiration. If null, local caching is disabled. Should typically be shorter than DistributedCacheExpiration to balance performance and data freshness.
DistributedCacheExpiration Indicates the expiration time for items stored in the distributed cache. If null, uses distributed cache provider's default expiration. It should typically be longer than LocalCacheExpiration.
ServerList Consists of your cluster nodes. You should list at least one server. Each entry specifies IP address and port (default value 9800).

Method 2: Using an Action Delegate in Program.cs

This method involves setting the configuration properties directly within your code during the service registration.

NCache

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddNCacheHybridCache(options =>
{
    options.CacheName = "defaultCache";
    options.Expiration = TimeSpan.FromMinutes(5);
});

var app = builder.Build();
app.Run();

Configure the server connection separately through the NCache SDK settings and client configuration. The connection must use an enabled client cache.

NCache Open Source

var builder = WebApplication.CreateBuilder(args);

// Register NCache Hybrid Cache service with custom configuration
builder.Services.AddNCacheHybridCache(options =>
{
    // Name of the in-memory (local) cache
    options.LocalCacheName = "myLocalCache";

    // Expiration time for items stored in local cache
    options.LocalCacheExpiration = TimeSpan.FromMinutes(5);

    // Name of the distributed cache (shared across multiple instances)
    options.DistributedCacheName = "myDistributedCache";

    // Expiration time for items stored in distributed cache
    options.DistributedCacheExpiration = TimeSpan.FromMinutes(30);

    // List of cache server nodes for distributed cache
    options.ServerList = new List<ServerConfig>
    {
        // First cache server configuration, default port 9800 if not specified
        new ServerConfig { Ip = "20.200.20.11", Port = 9800 },

        // Second cache server configuration, default port 9800 if not specified
        new ServerConfig { Ip = "20.200.20.12", Port = 9800 }
    };
});

// Build the application
var app = builder.Build();
app.Run();

Expiration and Entry Flags in NCache

The NCache edition chooses the entry lifetime in this order:

  1. HybridCacheEntryOptions.Expiration supplied for the operation.

  2. Expiration configured when registering the provider.

  3. If neither is supplied, the provider adds no explicit expiration, and the cache's own policies control retention.

Reading an entry does not restart its lifetime.

Important

HybridCacheEntryOptions.LocalCacheExpiration is ignored by this provider. Use Expiration instead. Separate L1 and L2 entry lifetimes are not supported.

The local and distributed flags cannot control each cache level separately:

Flag Behavior
DisableLocalCacheRead or DisableDistributedCacheRead Either flag makes GetOrCreateAsync call the factory without reading from or storing the result in the cache.
DisableLocalCacheWrite or DisableDistributedCacheWrite Either flag prevents cache writes. On a miss, the factory can still return a value, but it is not stored. SetAsync does not store the value.

Leave these flags unset for normal two-level caching.

Logging in HybridCache

NCache HybridCache employs the standard ASP.NET Core logging infrastructure via the Logger interface. Configuration is managed through the standard Logging section in your appsettings.json. The cache automatically utilizes the logger instance injected by the Dependency Injection (DI) container.

  • Use Debug or Information logging level for detailed insights into cache operations (e.g., L1/L2 hits and misses).
  • Use Warning or Error to minimize log overhead in case of critical issues.

Use the logging category for your package:

  • NCache (NCache.Caching.Hybrid): NCache.Caching.Hybrid.NCacheHybridCache
  • NCache Open Source (NCache.OSS.Caching.Hybrid): NCache.Microsoft.Extensions.Caching.Hybrid
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "NCache.Caching.Hybrid.NCacheHybridCache": "Debug"
    }
  }
}

The example uses the NCache logging category. For NCache Open Source, replace it with NCache.Microsoft.Extensions.Caching.Hybrid.

Important

Logging is managed entirely through ASP.NET Core via standard providers.

See Also

ASP.NET Core Caching
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
Try NCache
Pricing
NCache Playground

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

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Terms of Use
  •  
  • Privacy Policy
  •  
  • Cookie Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
  • Facebook
  • Twitter
  • Youtube
  • LinkedIn
  • RSS