Use with NHibernate

Learn how to use NCache as second level cache for NHibernate. NCache provides an NHibernate second level cache provider that you can plug-in through web.config or app.config changes. NCache has also implemented database synchronization feature in this so you can specify which classes should be synchronized with the database. NCache lets you specify SqlDependency or any OLEDB compliant databased dependency for this.

NCache is an Enterprise Distributed Caching solution, meant for your application scalability and performance. In today's tutorial, we are going to see how we can scale out NHibernate Applications using a Level 2 Cache provider from NCache.

Limitations with NHibernate L1 Cache

NHibernate is an excellent ORM tool for your application and it simplifies your coding standards across different teams.

Limitations with NHibernate L1 Cache
Limitations with NHibernate L1 Cache

NHibernate gives you with an in-process cache by default where you can hold the data temporarily inside your worker process for each transaction. This works fine for single server applications but this becomes a performance bottleneck for enterprise applications.

In enterprise applications, you usually have multiple web servers in a load balance scenario and their multiple worker processors running on each of them. So, it results in placing multiple redundant queries on your database for the same data from each worker process, which slows down your application as a net result and it also results in redundant storage individually on each worker process side in its own memory, and you can't scale out when you need to grow out your user base.

NHibernate L2 Cache provider Model

So, to overcome these limitations NHibernate provides you with a Level 2 Cache provider, where you can plug in a Second Level Cache.

  • Ideally L2 cache should be
    • out of process
    • in-memory
    • Distributed cache
  • Reliable and Highly Available
  • Scalable

NHibernate L2 Cache Provider Model

The Second Level Cache is used in conjunction with your in-process cache. Whenever you get the data from your database first time, NHibernate automatically pushes that data into the Second Level Cache, which is shared by all worker processes.

Ideally the Second Level Cache should be an In-Memory Cache, as you want to increase your application performance. It needs to be an out of process cache which does not get flushed even if your worker process recycles. It needs to be distributed, so, it can be shared among multiple worker processes on different web servers.

Remember you can only increase your application scalability and performance, if your underlying caching infrastructure is highly scalable and performance oriented.

NCache - NHibernate L2 Cache provider

So, here we have such a Level 2 Cache provider from NCache.

NCache - NHibernate L2 Cache provider
NCache - NHibernate L2 Cache provider

This is an out of process In-Memory Distributed Caching Solution, which has a dynamic clustering capability and it spans over multiple servers. The transaction load from your application gets distributed equally, to all the cache servers at runtime, to get you more performance and NCache keeps the data replicated across the entire cluster to provide you with a consistent failover in case you lose any of your Cache Servers.

NCache supports both synchronous and asynchronous replication modes. So, you can keep the data replicated without any performance overhead. The performance of NCache grows out linearly, when you add more servers to the caching tier. There's no limit on the cache size, so, you can grow as much as you want on your data size.

You can also include more servers at runtime into the cache cluster dynamically, to increase the transactional capability as well as have more memory.

It also provides you with a dashboard style monitoring, which helps you with a quick glance, to see the cache performance, your client application activity on the cache and the various system resources consumed by the cache.

The right-hand side picture shows the Partition-Replica topology, which keeps the data partitioned and replicated on multiple Servers. Partition-Replica is the most popular topology within NCache.

NCache Distributed Level-2 Cache for NHibernate

So, here is a high-level architecture diagram.

High-level Architecture Diagram
High-level Architecture Diagram

When you plug in this Level 2 provider from NCache in your enterprise application, it doesn't require any code changes in your application. You only need to have some configuration changes in your web.config or app.config, we'll talk about it. So, there are no more redundant calls going to your database, if you have already fetched the data in the previous transaction.

In a load balance web farm like this, the data is pushed to the Second Level Cache automatically by NHibernate, once you get it first time from your database and this cache is shared by all the web servers. So, it helps you reduce the load on your database.

NCache Level-2 Cache Configurable Features

So, with the configuration changes, you can configure a number of features for the Second Level Cache provider.

  • Use NHibernate regions
  • Expire cache objects with:
    • Sliding or die time
    • Absolute expiration
  • Database Synchronization with:
    • SQL Dependency
    • Polling Dependency
  • Use Sync. / Async. cache operations
  • Set cache item priority

NCache Level-2 Cache Configurable Features

For example, you can use NHibernate regions, you can set cache objects to expire with an absolute or idle time expiration, you can also configure SQL dependency for database synchronization. Both synchronous and asynchronous cache operations are supported and you can also configure the cache item priority.

So, I'm going to take you through a quick step-by-step hands-on session to configure NCache Level 2 Cache provider for a sample application.

I would suggest you to download the free 30-Day Enterprise Edition from our website. This is a fully functional and feature-rich product, even in the evaluation days.

NHibernate Integration Sample in NCache

Once you install NCache, here's how it looks like on your system.

NHibernate Integration Sample
NHibernate Integration Sample

It installs a bunch of Visual Studio samples. Let's go to the NHibernate sample for example, open in Visual Studio. You might need to rebuild the sample if you're using Video Studio 2010. You may need the conversion as well.

Let's take a look at the configuration changes that you need to do for your app.config for the Second Level Cache provider from NCache.

app.config File
app.config File

All you need to define a section named ‘ncache’ for the Cache provider like this in your app.config and then you can add a property for the Cache provider like this.

We also define the NCache section itself with multiple regions. These regions are the NHibernate regions. Each region maps to a different Cache name from NCache.

So, we have a default region here, which caters for all the entities on which you do not specify any NHibernate region and we have specific name region like this ‘Customer’ region. Within each region, you can specify multiple properties for each of the classes that fall into that region.

NHibernate Regions
NHibernate Regions

For example, set the SQL Dependency for that, set the priority of the Cache items, use Synchronous or Asynchronous, set the expiration strategy to be relative or idle time.

Running the Caches

So, in order to run the sample, what you need to have is, you need to have a couple of caches. The default cache and ‘myPartitionReplicaCache’ running, within your NCache Manager.

Let's go to NCache Manager, I've set this up with ‘myPartionedReplicaCache’ and default Cache with 2 Server setups right now. Let's run your application, view the customers list, for example just watch the Request/sec going to both of the servers pushing the data to it, once you obtain it from the Database.

Requests/Sec Equally Answered
Requests/Sec Equally Answered

So, there are about 49 plus 42 items on both these servers, equally distributed to both and if I run the query again, I'll be able to get these results directly from the Second Level Cache Cluster, instead of going to your database. So, just watch the Requests/sec equally answered, from both the Servers.

Cache Reliability Test

We can have the reliability test. We can take down one of the cache servers and still you will see that the cache cluster is capable to give you the items and recover it from the remaining servers.

For that we'll have to stop one of the servers and I’m going to do that. We have the 2 servers, 21 and 22. I am going to stop 22, as if it has gone out of the cluster and then rerun the query.

Stopping Cache Server
Stopping Cache Server

You will see 49 plus 42, the 91 items are still available on one of the servers. They have been recovered from the other Server now and if I rerun the query again, view the customers list again, I should be able to get all the items from this server, from the cluster. You can see the Requests/sec going on, Fetches/sec going on, from this server.

Reliability Test Successful
Reliability Test Successful

So, you have the reliable caching in place now, no matter if one of your cache servers is not available at runtime. The other cache servers can recover the data and respond well to your queries. At the same time, you're reducing load on your database. No more redundant queries are going to your database.

Integration Code for NHibernate in NCache

We do provide the integration code for the NHibernate in NCache, as you can see in the project that I have opened up and this source code is available for you to optimize or customize for your specific NHibernate versions.

Integration Code for NHibernate in NCache
Integration Code for NHibernate in NCache

If you go to the NCache installation folder, here we have the code. So, thanks very much for your time today and we today saw, how NCache can be useful. How reliable and scalable NCache is, to increase the performance of your NHibernate application. Stay tuned for more updates from NCache. We'll discuss various features in the coming tutorials. If you have any questions send us an email on

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