Using NCache as Hibernate Second Level Java Cache

Hibernate is an Object-Relational Mapping library for Java language. It provides you mapping from Java classes to database table and reduces the overall development cycle. Because of benefits Hibernate provides, more and more high transactional applications are developed using Hibernate. Here is an example of Hibernate in a Java application.


import org.hibernate.*;

public class HibernateSample
{
	...
Session session = factory.openSession();
session = factory.openSession();
Transaction tx = session.beginTransaction();
Query query =  session.createQuery("from Customer c");
Iterator it = query.list().iterator();
while (it.hasNext ()){
Customer customer = (Customer) it.next();
...
}
       tx.commit();
session.close();
}

But, these high traffic Hibernate applications are encountering a major scalability issue. Although they are able to scale at application-tier level, their database or data storage is not able to scale with the growing number of transactional load.

Java distributed caching is the best technique to solve this problem because it reduces the expensive trips to database that is causing scalability bottlenecks. For this reason, Hibernate provides a caching infrastructure that includes first-level and second-level cache.

Hibernate first-level cache provides you a basic standalone (in-proc) cache which is associated with the Session object, and is limited to the current session only. But, the problem with Hibernate first-level cache is that it does not allow the sharing of object between different sessions. If the same object is required by different sessions all of them make the database trip to load it which eventually increases database traffic and causes scalability problem. Moreover, when the session is closed all the cache data is also lost and next time you have to fetch it again from database.

These high traffic Hibernate applications with only first-level when deployed in the web farm also faces across server cache synchronization problem. In web farm, each node runs a web server – Apache, Oracle WebLogic etc. – with multiple instances of httpd process to server the requests. And, Hibernate first-level cache in each httpd worker process has a different version of the same data cached directly from the database.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

That is why Hibernate provides you a second-level cache with provider model. Hibernate second-level cache allows you to plug-in 3rd party distributed (out-proc) caching provider to cache object across sessions and servers. Hibernate second-level cache is associated with SessionFactory object and is available to entire application, instead of single session.

When you enable Hibernate second-level cache, you end up with two caches; one is first-level cache and the other is second level cache. Hibernate always tries to retrieve the objects from first-level cache if fails tries to retrieve them from second-level cache. If that also fails then objects are directly loaded from the database and cached as well. This configuration significantly reduces the database traffic because most of the data is served by the second-level distributed cache.

NCache Java has implemented a Hibernate second-level caching provider by extending org.hibernate.cache.CacheProvider. You can easily plug in NCache Java Hibernate distributed caching provider with your Hibernate application without any code changes. NCache allows you to scale your Hibernate application to multi-server configurations without database becoming the bottleneck. NCache also provides you all the enterprise level distributed caching features like data size management, data synchronization across server and database etc.

You can plug in NCache Java Hibernate caching provider by simply modifying your hibernate.cfg.xml and ncache.xml as follows

<hibernate-configuration>
  <session-factory>
<property name = "cache.provider_class">
alachisoft.ncache.integrations.hibernate.cache.NCacheProvider,
alachisoft.ncache.integrations.hibernate.cache
</property>
  </session-factory>
</hibernate-configuration>

<ncache>
<region name = "default">
   <add key = "cacheName" value = "myClusterCache"/>
   <add key = "enableCacheException" value = "false"/>
   <class name = "hibernator.BLL.Customer">
<add key = "priority" value = "1"/>
<add key = "useAsync" value = "false"/>
<add key = "relativeExpiration" value = "180"/>
   </class>
</region>
</ncache>

Hence, by using NCache Java Hibernate distributed cache provider you can linearly scale your Hibernate applications without any code changes.

So, download a fully working 60-day trial of NCache Enterprise and try it out for yourself.

Download NCache Trial | NCache Details

Posted in Hibernate Second Level Cache, Java Distributed Cache | Tagged , | Leave a comment

How to Synchronize Distributed Cache with Database with CLR Stored Procedures

Distributed caching has become a very important part of any high transaction application in order to ensure that the database does not become a scalability bottleneck. But, since a distributed cache keeps a copy of your application data, you must always ensure that it is kept synchronized with your database. Without this, the distributed cache has older stale data that causes data integrity problems. SQL Server provides an event notification mechanism where the distributed cache like NCache can register itself for change notification through SqlCacheDependency and then receive notifications from SQL Server when underlying data changes in the database. This allows NCache to immediately invalidate or reload the corresponding cached item and this keeps the cache always synchronized with the database. However, SqlCacheDependency can become a very resource intensive way of synchronizing the cache with the database. First of all, you have to create a separate SqlCacheDependency for each cached item and this could easily go into tens of thousands if not hundreds of thousands. And, SQL Server uses data structures to maintain each SqlCachDependency separately so it can monitor any data changes related to it. And, this consumes a lot of extra resources and can easily choke the database server.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

Secondly, SQL Server fires separate .NET events for each data change and NCache catches these events. And, these .NET events can be quite heavy and could easily overwhelm the network traffic and overall performance of NCache and your application. There is a better alternative. This involves you writing a CLR stored procedure that connects with NCache from within SQL Server and directly updates or invalidates the corresponding cached item. And, then you can call this CLR stored procedure from an update or delete trigger of your table. You can do this either with SQL Server 2005 or 2008 and also from Oracle 10g or later but only if it is running on Windows. A CLR stored procedure is more resource efficient because it is not creating data structures related to SqlCacheDependency. And, it also does not fire .NET events to NCache. Instead, it open up an NCache client connection and directly tells NCache whether to invalidate a cached item or reload it. And, this connection with NCache is highly optimized and much faster and lighter than .NET events. Below is an example of how to use a CLR stored procedure.

  1. Copy log4net and protobuf-net from Windows GAC to NCache/bin/assembly/2.0 folder (choose 4.0 if the target platform is .NET 4.0).

2.   Register NCache and following assemblies in SQL server. Example is given below. In this example we are using Northwind as a sample database.

use Northwind

alter database Northwind
set trustworthy on;
go

drop assembly SMdiagnostics
drop assembly [System.Web]
drop assembly [System.Messaging]
drop assembly [System.ServiceModel]
drop assembly [System.Management]

CREATE ASSEMBLY SMdiagnostics AUTHORIZATION dbo
FROM N'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\SMdiagnostics.dll'
WITH permission_set = unsafe

CREATE ASSEMBLY [System.Web] AUTHORIZATION dbo
FROM N'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Web.dll'
WITH permission_set = unsafe

CREATE ASSEMBLY [System.Management] AUTHORIZATION dbo
FROM N'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.management.dll'
WITH permission_set = unsafe

CREATE ASSEMBLY [System.Messaging] AUTHORIZATION dbo
FROM N'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll'
WITH permission_set = unsafe

CREATE ASSEMBLY [System.ServiceModel] AUTHORIZATION dbo
FROM N'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll'
WITH permission_set = unsafe

CREATE ASSEMBLY NCache
FROM N'C:\Program Files\NCache\bin\assembly\2.0\Alachisoft.NCache.Web.dll'
WITH permission_set = unsafe

3. Open visual studio to write a stored procedure against NCache And create a SQL CLR Database project as mentioned below. Add a reference to the NCache assembly that you created in the last step. The assembly that you need to refer is highlighted above. It will appear under SQL Server with the same name as “NCache”.

CLR_VS_Studio

4.  Write your stored procedure. Here is a sample code given:

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void TestSProc(string cacheName)
    {
        //--- Put your code here
        SqlPipe sp = SqlContext.Pipe;

        try
        {
            sp.Send("Starting .....");

            if (string.IsNullOrEmpty(cacheName))
                cacheName = "mycache";

            Cache _cache = NCache.InitializeCache(cacheName);
            _cache.Insert("key", DateTime.Now.ToString());
            sp.Send("Test is completed ...");
        }

5.  Enable CLR integration on database as given below:

sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

6. Deploy the stored procedure from Visual Studio and test it.
7. After deploying the stored procedure, you need to place your stored procedure assembly in (C:\Program Files\NCache\bin\assembly\2.0) folder as it does not resolve assembly references directly from windows GAC folder and needs them locally.

CLR based stored procedures or triggers can greatly improve the application performance as compared to the SqlCacheDependency that is relatively slower and can be overwhelming for large datasets.

Download NCache Trial | NCache Details

Posted in CLR procedures, Database synchronize, Distributed caching | Tagged , , | 3 Comments

How Compact Object Serialization Speeds up Distributed Cache?

Serialization transforms an object into a byte-stream so it can be moved out of a process either for persistence or to be sent to another process. And de-serialization is the reverse process that transforms a byte-stream back into an object. 

And, unlike a stand-alone cache, a distributed cache must serialize objects so it can send them to different computers in the cache cluster. But, the serialization mechanism provided by .NET framework has two major problems: 

1.  Very slow: .NET Serialization uses Reflection to inspect type information at runtime. Reflection is an extremely slow process as compared to precompiled code. 

2.  Very bulky: .NET Serialization stores complete class name, culture, assembly details, and references to other instances in member variables and all this makes the serialized byte-stream many times the original object in size. 

Since a distributed cache is used to improve your application performance and scalability, anything hampering this becomes very critical. And, the regular .NET Serialization is a major performance overhead in a distributed cache because thousands of objects need to be serialized every second before being sent to distributed cache for in-memory storage. And, any slowdown here becomes a slowdown for the distributed cache. 

The other issue is that a bulky serialized byte-stream consumes 2-3 times extra space and reduces the overall storage capacity of a distributed cache. An in memory storage can never be as big as a disk storage which makes this an even more sensitive issue for a distributed cache. 

Download NCache free trial - Extremely fast and scalable in-memory distributed cache 

To overcome .NET serialization problems, NCache has implemented a Compact Serialization Framework. In this framework, NCache stores two-byte type-ids instead of fully qualified assembly/class names. It further reduces the serialized byte-stream by only serializing the field values and excluding their type details. Finally, NCache Compact Serialization Framework avoids the use of .NET Reflection because of its overhead by directly accessing fields and properties of the instance object. 

There are two ways to use NCache Compact Serialization in your application.  

  1. Let NCache generate Compact Serialization code at runtime
  2. Implement an ICompactSerializable interface yourself

In this blog, I will stick to first approach only. I’ll discuss the second approach in a separate blog. 

Let NCache generate Compact Serialization code at runtime 

Identify the types of objects you are caching, and register them with NCache as Compact Serialization types as shown in Figure. That is all you have to do, and NCache takes care of the rest. 

Compact Serialization

Compact Serialization

 

 Figure 1: Register Types for Compact Serialization with NCache 

NCache sends the registered types to NCache client at the time of initialization. Based on received types, NCache client generates the runtime code to serialize and deserialize each type. The runtime code is generated only once by the NCache client at the time of initialization and used over and over again. It runs much faster than Reflection based serialization. 

Hence, using NCache Compact Serialization you can efficiently utilize your distributed cache memory and can boost your application performance. 

So, download a fully working 60-day trial of NCache Enterprise and try it out for yourself. 

Download NCache Trial | NCache Details

Posted in Distributed Cache, Serialization | Tagged , | 1 Comment

Using Distributed Cache in Entity Framework Applications

Entity Framework is an object-relational mapping engine that provides abstraction from underlying relational database and therefore greatly simplifies development. Because of these benefits, more and more data-centric and high transactional applications and services are developed with Entity Framework.

But, these high traffic applications are facing scalability problems. Although the application-tier level is scalable, their database or data storage cannot keep up with growing number of transactions being thrown at them.

This is where a distributed cache comes in because it allows you to cache data and reduce those expensive database trips that are causing scalability bottlenecks.  But, Entity Framework does not provide an out of the box solution that allows you to use distributed cache in your application. There are however two ways in which you can incorporate distributed cache into your Entity Framework application. One is to modify your Entity Framework application code and make direct API calls to the distributed cache. Second, is to use a distributed cache that has implemented a custom ADO.NET provider that incorporates caching behind-the-scenes.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

Entity Framework has public provider model for ADO.NET providers where you can write providers for 3rd party databases. NCache has implemented a custom Entity Framework ADO.NET provider of its own through which it is able to make distributed cache calls to NCache API. This custom Entity Framework ADO.NET provider intercepts all the database query calls and puts the result-sets of these queries in a distributed cache. Then, NCache custom Entity Framework provider intercepts all subsequent query calls and simply returns the results from its distributed cache rather than making that expensive database trip. If result-set for a query does not exist in the distributed cache then query is executed against database and it’s result-set is then put in the distributed cache. 

And, NCache custom Entity Framework provider also needs to ensure that data in the distributed cache is always consistent and synchronized with the database. And, for that NCache uses SqlCacheDependency provided in .NET. SqlCacheDependeny registers a SQL query with SQL Server so if any row in the dataset represented by this query is changed in the database, SQL Server throws a .NET event notification to NCache. NCache catches this .NET event and removes the corresponding result-set from the distributed cache.

Figure 1 shows how NCache Entity Framework Provider plugs into an Entity Framework application.

EF Caching

EF Caching

Figure 1 NCache Entity Framework Provider being used

 You can integrate NCache custom Entity Framework ADO.NET provider in your application in just four simple steps:

  1. Replace default provider: Replace your applications default provider with NCache Entity framework provider in app.config/web.config and .edmx file.
  2. Register NCache provider: Register your application in NCache Entity Framework config (efcaching.conf). In efcaching.config, you can easily specify log level and expiration policies etc. for your Entity Framework application.
  3. Run app in analysis mode: Run your application in analysis mode. In Analysis mode, NCache Entity Framework provider, logs Entity Framework queries executed by your application along with their frequency. Based on the logs you can scrutinize Entity Framework queries you want to cache.
  4. Run app normally: Switch to caching mode and run your application.

 Hence, by using NCache Entity Framework caching provider you can easily achieve linear scalability without changing your Entity Framework application code.

So, download a fully working 60-day trial of NCache Enterprise and try it out for yourself.

Download NCache Trial | NCache Details

Posted in Distributed caching, Entity Framework | Tagged , | 2 Comments

How to use LINQ for Searching Distributed Cache?

Distributed caching is becoming really popular among developers of high transaction applications because it improves your application’s performance and scalability. And, this popularity means that developers are caching more and more data in it which they also want to be able to search just like they are able to search relational databases.

But, one major limitation of many distributed caches is that they only provide (key, value) Hashtable interface to you. This means that for you to fetch any cached item, you must know its key. But in real life this is not always possible and in many cases you need to search for data based on other search criteria (e.g. “Give me all customers from New York”). So, if you’re not able to search a distributed cache, you’re likely to only cache data for which you always know their keys. And, this prevents you from caching a lot of data that would otherwise really boost your application’s performance and scalability.

Fortunately, NCache provides you a very powerful SQL-like querying capability (called Object Query Language or OQL) to let you search the cache based on object attributes and not just the keys. And, for .NET applications, NCache provides LINQ integration and allows you to search the cache through LINQ.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. And, it connects the object world and data world and makes searching very easy and manageable. Moreover, LINQ allows you to integrate your own data storage to it.

NCache provides a LINQ plug-in. So, you now issue LINQ queries from your .NET application and behind the scene this query runs against an NCache distributed cache and a result set is returned to your application. NCache is integrated with LINQ by implementing a class named “NCacheQuery”, which further implements the interface called “IQueryable” provided by .NET framework. By this integration you can run LINQ queries on cached items.
Here is a source code example of LINQ Query.


namespace NCacheLINQ
{
      class Program
      {
          static void Main (string[] args)
          {
             IQueryable<Product> products = new NCacheQuery<Product> (_cache);
             try
             {
                var result1 =  from product in products
                		    where product.ProductID > 10
                		    select product;
                if (result1 != null)
                {
                       foreach (Product p in result1)
                       {
                            Console.WriteLine("ProductID : " + p.ProductID);
                       }
                }
                else
                {
                       Console.WriteLine("No record found.");
                }
             }
             catch (Exception)
             {
                 Console.WriteLine(_error);
             }
          }
      }
}

In summary, querying in-memory collections wasn’t this much easy and manageable before LINQ and NCache gives LINQ integration in such a way that you don’t have to change code all you need to do is add a new assembly reference and namespace in your application.

So, download a fully working 60-day trial of NCache Enterprise and try it out for yourself.

Download NCache Trial | NCache Details

Posted in ASP .NET performance, ASP.Net, ASP.NET Cache, Cache dependency, Distributed caching, LINQ Query | Tagged , , , | Leave a comment

How SQLCacheDependency Synchronizes Distributed Cache with Database?

Distributed Caching has become a popular way of improving .NET application performance and scalability. That is why developers are caching more and more data in distributed cache. However along with this come a few challenges. One important challenge is to ensure that data in the cache is always synchronized with the database. This is because the cache is keeping a copy of the data that already exists in the database.

If you have multiple applications updating the same data in the database but not all of them have access to the distributed cache, you’ll end up with a situation where data in the cache is older and different than its counterpart in the database. And, while this may be okay for some reference type of data, it is definitely not acceptable for transactional data. Reference data is one that you read a lot but don’t modify very frequently (e.g. product catalog) while transactional data is something you read and modify frequently (e.g. customer or account data).

So, how do you ensure that in these situations, the distributed cache stays synchronized with the database? The answer is SqlCacheDependency. SqlCacheDependency is part of ASP.NET Cache (System.Web.Caching) and allows you to specify a dataset in the database with an SQL statement and then receive .NET event notifications from SQL Server 2005/2008 whenever your dataset is modified in the database.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

NCache has internally incorporated SqlCacheDependency for the purpose of synchronizing cache with SQL Server 2005/2008 or Oracle database. To you, NCache provides a similar interface called SqlDependency that allows you to specify an SQL statement representing one or more rows in a given table that make up your cached item. NCache then internally uses SqlCacheDependency to establish a link with the database against these rows.

So, if your data is updated in the database by one of your applications, SQL Server fires a .NET event notification which NCache catches and removes the corresponding item from the distributed cache. This resolves data inconsistency issue of having two different copies of the same data. This is because when your application wants the same data next time, it doesn’t find it in the cache and is forced to retrieve the latest copy from the database which it then caches as well. This way, NCache ensures that the data in the cache is always consistent with the data in the database.

Here is a source code example of using SqlDependency of NCache that internally uses SqlCacheDependency:


public class Program {

    // A standard Load method that loads a single row from database
    public Customer LoadCustomer(Customer cust)
    {
	String key = "Customer:CustomerID:" + cust.CustomerID;

	Customer cust2 = (Customer)NCache.Cache.Get(key);
	if (cust2 != null)
	   return cust2;

	CustomerFactory custFactory = new CustomerFactory();

	// Load a single customer from the database
	// SELECT * FROM Customers WHERE CustomerID = 'ALFKI'
	custFactory.Load(cust);

	// Create a SqlCacheDependency for this item
	CacheItem item = new CacheItem(cust);
	item.Dependency = SqlDependencyFactory(connectionString,
	    "SELECT CustomerID FROM Customers WHERE CustomerID = '"
		+ cust.CustomerID + "'");

	// Store item in the cache along with SqlCacheDependency
	NCache.Cache.Insert(key, item);
	return cust;
    }

    // A query method
    public List<Customer> FindCustomers(String city)
    {
	String key = "List<Customer>:City:" + city;
	List<Customer> custList = (List<Customer>)NCache.Cache.Get(key);
	if (custList != null)
	    return custList;

	CustomerFactory custFactory = new CustomerFactory();

	// Load a list of customers from database based on a criteria
	// SELECT * FROM Customers WHERE City = 'San Francisco'
	custList = custFactory.FindByCity(city);

	// Create a SqlCacheDependency for this list of customers
	CacheItem item = new CacheItem(custList);
	item.Dependency = SqlDependencyFactory.(connectionString,
	    "SELECT CustomerID FROM Customers WHERE City = '" + city + "'");

	// Store list of customers in the cache along with SqlCacheDependency
	NCache.Cache.Insert (key, item);
	return custList;
    }
}

In summary, SqlDependency feature of NCache allows you to synchronize cache with the database and maintain data integrity. You can now start caching all data without the fear of using stale data from the cache. And, of course, the more data you cache, the better your application performance and scalability becomes.

So, download a fully working 60-day trial of NCache Enterprise and try it out for yourself.

Download NCache Trial | NCache Details

Posted in ASP .NET performance, ASP.Net, ASP.NET Cache, Cache dependency, Distributed caching, SQL cache dependency | Tagged , , , | Leave a comment

How to Improve ASP.NET Performance with Distributed Caching?

If your ASP.NET application only has a few users, you probably don’t care how fast or slow it is and it is probably giving you pretty good performance anyway. But, as you add more load to your ASP.NET application, the chances are quite high that ASP.NET performance will drop significantly. It might even grind to a halt if enough load is put on it. And, ironically, all of that happens just when your business is seeing more activity so the impact is even greater.

ASP.NET today has become really popular for high traffic apps and it is now common to see 10-20 server load balanced web farms and in some cases even 50-100 server farms. So, in these situations, ASP.NET performance is even more sensitive issue to resolve.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

The main reason for ASP.NET performance drop as you increase load on it is your database which cannot handle larger loads the way your ASP.NET application web farm can. This is because you can add more servers to the ASP.NET web farm but you cannot do the same with your database.

So, in these situations, your best bet is to use a distributed cache like NCache. NCache is in-memory so it is much faster than the database. And, NCache builds a cluster of cache servers and you can grow the cluster linearly just like the web farm. As a result, with NCache, your ASP.NET performance remains great even under extreme transaction loads.

You can use NCache in two ways: 

1. ASP.NET Session State Storage

You can configure your ASP.NET application to store ASP.NET Session State in NCache instead of InProc, State Server, or SQL Server. Please note that no programming is needed here. You only modify web.config code as following:

  <sessionstate cookieless="false"
                     regenerateExpiredSessionId="true"
                     mode="Custom"
                     customProvider="NCacheSessionProvider"
                     timeout="20">
     <providers>
         <add name="NCacheSessionProvider"
	      type="Alachisoft.NCache.Web.SessionState.NSessionStoreProvider"
	      exceptionsEnabled="true" enableSessionLocking="true"
	      emptySessionWhenLocked="false"  sessionLockingRetry="-1"
	      sessionAppId="NCacheTest" useInProc="false" enableLogs="false"
	      cacheName="myReplicatedCache" writeExceptionsToEventLog="false"
	      AsyncSession="false"/>
     </providers>
   </sessionstate>

2. ASP.NET Application Data Cache

The other way is for you to cache application data in a distributed cache like NCache so the next time your ASP.NET application needs this data, it will find it in the cache. Here is a small code sample on how to cache application data:

using Alachisoft.NCache.Web.Caching;

      ...

      Cache cache = NCache.InitializeCache("myCache");

      // Create a key to lookup in the cache
      // The key for will be like “Employees:PK:1000”
      string key = "Employee:EmployeeId:" + emp.EmployeeId.ToString();
      Employee employee = (Employee)Cache[key];
      if (employee == null) {
            // item not found in the cache. load from db
            LoadEmployeeFromDb(employee);

            // Now, add it to the cache for future reference
            Cache.Insert(key, employee, null,
                         Cache.NoAbsoluteExpiration,
                         Cache.NoSlidingExpiration,
                         CacheItemPriority.Default, null );
        }

The more data you cache, the less you have to go to the database and the faster is your ASP.NET application performance.

Download NCache Trial | NCache Details

Posted in ASP .NET performance, ASP.NET Cache, Distributed caching | Tagged , | Leave a comment

How Cache Dependency Manages Data Relationships?

Distributed cache is becoming very popular because it is a powerful way to boost your application performance and scalability and handle extreme transaction load without slowing down. Both .NET and Java applications are using it more and more each day. 

But, one challenge people face with distributed cache is how to map and store relational data in a HashTable (key, value) pairing storage that a distributed cache is. Most caches today do not provide any mechanism to handle this. Today, I will discuss Cache Dependency which ASP.NET Cache provides and that NCache incorporated from day one. 

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

Just like ASP.NET Cache, in NCache, Cache Dependency allows you to specify a dependency in the distributed cache between two cached items. Cached item A depends on cached item B. And, if B is ever updated or removed from the distributed cache, A is automatically removed. This ensures that if there is a referential integrity constraint between A and B in the database that it is also honored in the distributed cache. You can also specify cascading Cache Dependency where A depends on B and B depends on C. Then, if you update or remove C, A and B are both removed. Here is a brief example of Cache Dependency:
Cache Dependency lets you create one-to-one, one-to-many, and many-to-many relationships in the distributed cache. Here is how you would handle different scenarios: 

One-to-one relationship:

A has one-to-one with B. Add B without any Cache Dependency. Then, add A and specify a Cache Dependency for B. If A and B both have a mutual dependency, then when update B afterwards and specify a dependency on A. 

One-to-many relationship:

A has one-to-many with B. Add A first without any Cache Dependency. Then, add one or more B items and specify a Cache Dependency for the given A for all of them. This way, if A is updated or removed, all of B’s will be removed automatically by NCache. 

Many-to-many relationship:

A and B have many-to-many with each other. Add one or more A’s. Then, add one or more B’s and specify Cache Dependency for the appropriate A’s. Then, go back and update A’s to specify Cache Dependency on appropriate B’s. 

public void CreateDependencies(Cache cache)
{
   string keyB = "objectB-1000";
   ObjectB objB = new ObjectB();
   string keyA = "objectA-1000";
   ObjectA objA = new ObjectA();
    // “null” third argument means objB does not depend on anything
   _cache.Add(keyB, objB, null,
              Cache.NoAbsoluteExpiration,
              Cache.NoSlidingExpiration,
              CacheItemPriority.Default, null, null);
    // third argument specifies that objA depends on objB
   string[] ADependsOn = { keyB };
   _cache.Add(keyA, objA, new CacheDependency(null, ADependsOn),
              Cache.NoAbsoluteExpiration,
              Cache.NoSlidingExpiration,
              CacheItemPriority.Default, null, null);
    // Removing "objB" automatically removes “objA” as well
   _cache.Remove(keyB);
   _cache.Dispose();
}

So, NCache allows you to take advantage of Cache Dependency and specify data relationships in the distributed cache. Download a fully working 60-day trial of NCache Enterprise and try it out for yourself.  

Download NCache Trial | NCache Details

Posted in ASP .NET performance, ASP.NET Cache, Cache dependency, Distributed caching, SQL cache dependency | Tagged , , , | 4 Comments

When to use client cache with distributed caching

A distributed cache is essential for any application that demands fast performance during extreme transaction loads. An in-memory distributed cache is faster than a database. And, it can provide linear scalability in handling greater transaction loads because it can easily let you add more servers to the cache cluster that a database server cannot do.

Despite all these benefits, there is still one problem. In most cases a distributed cache is hosted on a set of dedicated cache servers across the network so your application has to make network trips to fetch any data. And, this is not as fast as accessing data locally and especially from within the application process. This is where client cache comes in handy.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

In NCache, a client cache keeps a connection open to the distributed cache cluster and receives event notifications from the cache cluster whenever client cache data changes there. A distributed cache cluster knows which data items are being kept in which client cache so event notifications are sent only the relevant client cache instead of broadcasting them to all client caches.

How does client cache work?

A client cache is nothing but a local cache on your web/application server but one that is aware of a distributed cache and is connected to it. Additionally, a client cache can either be in-process, meaning a client cache exists inside your application process, or out-of-process. This allows a client cache to deliver much faster read performance than even distributed cache and at the same time ensure that client cache data is always kept synchronized with the distributed cache.

ncache-client-cache

ncache-client-cache

However, a distributed cache notifies client cache asynchronously after it successfully updates data in the distributed cache cluster. This means that there is technically a small window of time (in milliseconds) during which some of the data in client cache is older than the distributed cache. Now, in most cases, this is perfectly acceptable to applications. But, in some cases, applications demand 100% accuracy of data.

So, to handle such situations, NCache provides a pessimistic synchronization model for client cache as well. In this model, every time the application tries to fetch anything from the client cache, the client cache first checks whether the distributed cache has a newer version of the same cached item. If it does, then the client cache fetches newer version from the distributed cache. Now, this trip to the distributed cache has its cost but it is still faster than fetching the cached item entirely from the distributed cache.

When to use a client cache?

So, having known all of this, the main question that comes to mind is when to use a client cache and when not to use it. Well, the answer is pretty straight forward. Use a client cache if you’re doing a lot more reads than writes and especially if you’re reading the same items over and over again. And, if you’re doing a lot of updates or at least as many updates as reads (e.g. in case of ASP.NET Session State or JSP Servlet Session storage in NCache) then don’t use a client cache because the updates are actually slower with a client cache because you’re updating two different caches now, the client cache and the distributed cache.

So, NCache allows you to take advantage of client cache with a distributed cache. Download a fully working 60-day trial of NCache Enterprise and try it out for yourself.

Download NCache Trial | NCache Details

Posted in ASP.Net, client cache, Distributed caching | Tagged , , | 1 Comment

Using ASP.NET Cache in Web Farms

ASP.NET has now become a really popular technology for web apps and more and more people are developing high traffic applications in it. And, to handle higher traffic, these ASP.NET apps are deployed in load balanced web farms where you can add more servers as your traffic load increases. So, it is very scalable except for one problem.

And, that problem is the database and your data storage which cannot scale in the same fashion to handle the higher traffic loads. So, what you get very quickly is a bottleneck where your ASP.NET application slows down and can even grind to a halt.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

In such situations, data caching is an excellent way of resolving this database and data storage bottleneck. Caching allows you to store application data close-by and reduce those expensive database trips.

What is ASP.NET Cache?

ASP.NET Cache allows you to cache application data and is actually a fairly feature-rich cache including the following features:

  • Expirations: Automatic absolute and sliding expirations
  • CacheDependency: To manage data relationships in the cache
  • SqlCacheDependency: To synchronize cache with database
  • Callbacks: To be notified when items are updated in cache

Here is some sample code showing ASP.NET Cache usage.

using System.Web.Caching;

// Create a key to lookup in the cache
// The key for will be like “Employees:PK:1000”
string key = "Employee:EmployeeId:" + emp.EmployeeId.ToString();

Employee employee = (Employee)Cache[key];
if (employee == null) {
    // item not found in the cache. load from db
    LoadEmployeeFromDb(employee);

    // Now, add it to the cache for future reference
    Cache.Insert(key, employee, null,
                 Cache.NoAbsoluteExpiration,
                 Cache.NoSlidingExpiration,
                 CacheItemPriority.Default, null );
}

ASP.NET Cache Limitations in Web Farms

Despite very useful caching features, ASP.NET Cache has some serious limitations. They are:

  • Does not synchronize across server or worker processes: It does not synchronize across multiple servers or even multiple worker processes. So, you cannot use it in a web farm or even a web garden unless your data is read-only whereas you need to cache all kinds of data, including one that changes somewhat frequently.
  • Cache size limitation: You cannot grow the ASP.NET Cache to be more than what one ASP.NET worker process can contain. For 32-bit systems, this is 1GB and that includes app code as well. Even for 64-bit systems, the size cannot scale.

Use ASP.NET Cache Compatible Distributed Cache

The way to work around these limitations of ASP.NET Cache is to use a distributed cache like NCache for web farms. NCache provides the same features that ASP.NET Cache plus more. But, as a distributed cache, NCache easily synchronizes across multiple servers. Here are some benefits you get from NCache:

  1. Scales transaction load very nicely: You can keep adding more cache servers to the cache cluster as your web farm grows from 2 to 200 servers. NCache never becomes a bottleneck in handling more traffic.
  2. Scales data storage nicely: As you add more cache servers, your cache storage capacity grows due to Partition Cache topology.
  3. Replicates data for reliability: You can ensure that no data loss occurs even if a server goes down because data is replicated to other servers.
  4. Dynamic self healing cache cluster: NCache provides 100% uptime through this. And, you can add or remove cache servers at runtime without stopping the cache or your application.

asp-net-cache-blog-figure1

Well, if you have an ASP.NET application running in a web farm, take a look at NCache and see how it will help improve your application’s performance and scalability. Here are some useful links for NCache:

 Download NCache Trial  |  NCache Details

Posted in ASP.Net, ASP.NET Cache, Distributed caching, SQL cache dependency | Tagged , , , , , | 3 Comments

Configure ASP.NET Session State for Web Farms

There is absolutely no doubt about it. ASP.NET has come to age and a good majority of ASP.NET applications now are high traffic and mission-critical. That means you cannot afford unscheduled downtime of either the entire website or some of the servers where many users are getting bumped out. This is because these downtimes cost you dearly in lost revenue and a bad reputation that is hard to fix.

ASP.NET Session State storage if not handled correctly can cause unscheduled downtimes. Microsoft offers four storage options for ASP.NET Session State:

  • InProc: Sessions kept inside worker process
  • StateServer: Session kept in a separate process
  • SqlServer: Session kept in SQL Server
  • Custom: Session kept in a third-party custom store

Both InProc and StateServer don’t have the capability to replicate ASP.NET Session State to more than one server and therefore cause data loss if any web server goes down. In fact, if you have a single StateServer for the entire website and it goes down, you’re totally hosed because your entire website will go down.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

SqlServer is the third storage option for ASP.NET Session State and it does provide server redundancy and data replication because you can build a database cluster, either mirrored or load-balanced cluster.

But, it’s expensive to setup SQL Server clusters and there are cheaper and more viable alternatives available. Additionally, SQL Server (like all relational databases) was designed to store structured relational data and not BLOBs; whereas, ASP.NET Session State is stored in SQL Server as BLOBs. So, not only are the sessions slow to access but the database quickly becomes a bottleneck as you try to scale your application.

A considerably better alternative to all of this is to use the Custom storage option of ASP.NET Session State and use an in-memory distributed cache (NCache) as your ASP.NET Session State storage. NCache replicates sessions across multiple servers so if any one server goes down, there’s no loss of session data. NCache is also much faster to access than SQL Server because it is in-memory. Finally, NCache allows you to easily scale the cache cluster as your web farm size grows. Simply add more cache servers to the cluster so there is never a bottleneck.

And, best of all, there is no programming needed to use NCache for ASP.NET Session State storage. Simply modify your web.config to specify the following:

<assemblies>
    <add assembly=”Alachisoft.NCache.SessionStoreProvider,
                   Version=3.8.0.0, Culture=neutral,
                   PublicKeyToken=CFF5926ED6A53769″/
>
</assemblies>
<sessionState cookieless=”false” regenerateExpiredSessionId=”true” 
    mode=”Custom” customProvider=”NCacheSessionProvider”
    timeout=”20″>
    <providers>
            <add name=”NCacheSessionProvider”
type=”Alachisoft.NCache.Web.SessionState.NSessionStoreProvider”
                
 sessionAppId=”NCacheTest” enableLogs=”false”
                 cacheName=”myReplicatedCache”/>
    </providers>
</sessionState>

Well, if you have an ASP.NET application running in a web farm, take a look at NCache and see how it will improve your ASP.NET Session State storage. Here are some useful links for NCache:

Download NCache Trial  |  NCache Details

Posted in ASP .NET performance, ASP.Net, Distributed caching | Tagged , , | 1 Comment