Cookie Consent by Free Privacy Policy Generator NHibernate Second Level Cache - NCache

NHibernate Second Level Cache

NHibernate is a popular Object-Relational Mapping (ORM) framework for .NET applications, which enables seamless database interactions through object-oriented code. However, when applications handle a high volume of transaction loads, they often experience performance bottlenecks due to frequent database queries.

To address this, NHibernate provides Second-Level Caching, which keeps objects in memory at the application level, reducing the need to repeatedly access the database. NCache, an extremely fast and scalable distributed cache, acts as an NHibernate Second-Level Cache provider, which significantly improves application speed, scalability, and reliability.

NCache provides a high-performance, distributed Second Level (L2) Cache for NHibernate that eliminates database bottlenecks in .NET applications. It offers linear scalability, 100% uptime through peer-to-peer clustering, and requires zero code changes for integration.

How does NCache improve NHibernate application performance?

NCache boosts NHibernate with faster queries, reduced database load, and high-availability as explained below.

  • Performance: Storing frequently accessed data in-memory reduces database trips by up to 90%, leading to faster query execution and improved responsiveness. This eliminates "Database Choke Points" where the database cannot handle the volume of repeat read requests from multiple web servers, allowing the application tier to scale linearly while keeping database load minimal. Internal benchmarks show NCache can handle over 2 million operations per second with sub-millisecond latency.
    • Client Cache: It allows applications to access the most frequently used subset of the cached data from the their own memory, reducing network calls and further enhancing performance.
    • Compact Serialization: NCache ensures efficient serialization and deserialization with Compact Serialization, making data retrieval significantly faster than standard .NET serialization.
  • Linear Scalability: NCache allows applications to scale dynamically by adding more cache servers. It also ensures the cache load is evenly distributed in a clustered environment.
  • High Availability: NCache's Peer-to-peer clustering eliminates downtime, while automatic failover & replication prevent data loss and maintain cache consistency. NCache offers intelligent data replication through multiple caching topologies, including:
    • Partition-Replica Cache: Maintains redundant copies of cached data across partitions to prevent data loss.
    • Mirrored Cache: Provides a synchronous backup mechanism for real-time failover.
    • Replicated Cache: Ensures data availability by distributing the same cache across multiple nodes in the cluster.
  • Common Use Cases for NCache NHibernate L2 Cache:
    • High-Traffic Web Farms: Scaling .NET applications across multiple servers without database contention.
    • Real-Time Data Consistency: Using SQL Dependency to sync cache with external database changes.
    • Legacy System Modernization: Improving performance of existing NHibernate apps with a plug-and-play provider.

Technical Comparison: NHibernate L1 vs. NCache L2

Feature NHibernate L1 (Session Cache) NCache (Distributed L2 Cache)
Scope & Isolation Transaction-scoped. Data is isolated to a single ISession object. Process-wide/Cluster-wide. Data is shared across all sessions and all servers in the web farm.
Data Persistence Ephemeral. Objects are disposed of as soon as the session is closed or the request ends. Persistent In-Memory. Data lives in the cache cluster independently of application restarts or session closures.
Scalability In-process only. Limited by the memory of a single web server; cannot be shared across a farm. Linear Scalability. You can add cache servers dynamically to increase storage capacity and throughput.
Database Sync None. L1 has no mechanism to know if another process updated the DB. Automatic Synchronization. Uses SqlCacheDependency, Oracle Dependency, or Polling to invalidate stale data.
Query Caching Not applicable (L1 is primarily for ID-based lookups). Supported. Caches results of complex queries to avoid repeated expensive SQL executions.

Key Features of NCache for NHibernate

Following are some of the key features that NCache offers to NHibernate users:

No Code Change Required

  • Easily integrates with NHibernate as a plug-and-play solution without modifying existing application code.
  • All configurations are managed through XML-based configuration files.

Multiple Cacheable Regions

  • Cache Item Priority: Assign different priority levels (High, Normal, Low) to cached data, ensuring frequently accessed objects stay in the cache longer.
  • Absolute Expiration: Cache entries expire at a fixed time. This ensures that stale data is automatically purged regardless of how often it is accessed.
  • Sliding Expiration: Expiration resets upon access, making it ideal for frequently used but dynamic data.
  • Region-Based Configuration: Customize caching behavior for different data regions using the NCacheNHibernate.xml configuration file.
<configuration>
  <application-config application-id="myapp"
                      enable-cache-exception="true"
                      default-region-name="default"
                       key-case-sensitivity="false" >
    <cache-regions>
      <region name="AbsoluteExpirationRegion"
              cache-name="demoCache"
              priority="Default"
              expiration-type="sliding"
              expiration-period="180" />
          <region name="default" 
              cache-name="demoCache" 
              priority="default"
              expiration-type="none" 
              expiration-period="0"/>
    </cache-regions>
  </application-config>
</configuration>

How does NCache keep NHibernate data synchronized with the database?

  • Monitors database changes to keep cached data up to date.
  • Works seamlessly with SQL Server, Oracle, and OLEDB-based databases.
  • Uses SQL dependency-based invalidation to remove or refresh stale cached data.
<configuration>
   <application-config application-id="myapp" 
      enable-cache-exception="true" 
      default-region-name="default" 
      key-case-sensitivity="false">

    <database-dependencies>
      <dependency entity-name="nhibernator.BLL.Customer" 
                     type="sql"
sql-statement="SELECT ContactName FROM dbo.Customers WHERE CustomerID =?"                     
                cache-key-format="dependency.customer: [us]"/>
    </database-dependencies>
  </application-config>
</configuration>

NHibernate Query Cache

  • Query Result Caching: Caches query results to reduce repeated executions of the same database queries.
  • Query Storage: Stores queries in the NHibernate.QueryCache region for faster lookups.
  • Async Operations: Updates the cache non-blocking, ensuring that application execution is not delayed.
  • Sync Operations: Instantly updates or invalidates cached data when database changes occur, maintaining data consistency.

Enable Query Caching in Application Code

This example shows how to enable NHibernate query caching with NCache to store and reuse query results for improved performance.

using (var session = sessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        IQuery query = session.CreateQuery("FROM Customer c")
                              .SetCacheable(true);
        var customers = await query.ListAsync<Customer>();

        var newCustomer = new Customer { Name = "John Doe" };
        await session.SaveAsync(newCustomer);

        await session.FlushAsync();
        transaction.Commit();
    }
}

How to Configure NCache with NHibernate?

Install NCache Client for NHibernate

  • Install the NCache NHibernate Provider for Enterprise via NuGet:
    Install-Package NHibernate.NCache

Install NCache Server

Configure NCache for NHibernate

Modify your NHibernate configuration files to enable NCache as the second-level cache provider.

Update hibernate.cfg.xml

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="cache.provider_class">
      Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider,
      Alachisoft.NCache.Integrations.NHibernate.Cache
    </property>
    <property name="cache.use_second_level_cache">true</property>
  </session-factory>
</hibernate-configuration>

What to Do Next?

Frequently Asked Questions (FAQ)

NCache provides a distributed, multi-node alternative to NHibernate's default primary (L1) cache. While L1 is limited to a single session, NCache allows your application to share cached data across an entire web farm, reducing database trips by up to 90% and preventing database bottlenecks during peak traffic.

Yes. NCache fully supports NHibernate Query Caching, which stores the results of expensive SQL queries in the distributed cache. This ensures that subsequent executions of the same query with the same parameters do not hit the database, significantly improving application latency.

NCache maintains 100% data consistency through Database Synchronization features. By using SQL Dependency (SqlCacheDependency) or Oracle Dependency, NCache automatically invalidates and removes stale cached items whenever the underlying database data changes, ensuring your application always serves the most current information.

No code changes are required. NCache is a plug-and-play L2 cache provider. Integration is handled entirely through configuration by modifying your hibernate.cfg.xml or app.config file to point to the NCache provider factory.

For most NHibernate environments, the Partition-Replica Topology is recommended as it offers the best balance of performance and high availability. For read-intensive workloads, the Client Cache (Inproc) feature can be enabled to provide "near-cache" speeds by storing a subset of data directly in the application's memory.

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.