ASP.NET Session State Store in Microsoft Azure

Microsoft Azure provides a platform for ASP.NET applications in the cloud. Very often, these applications are high transactional and mission critical in nature. Therefore, it is very important that these applications are able to scale and that there are no data loss if a web server goes down at any time.

ASP.NET Session State needs to be stored somewhere and its storage becomes a major performance and scalability bottleneck. In Microsoft Azure, you can store ASP.NET Session State in In-proc, SQL Azure (database), Azure Table Storage or in a distributed cache.

InProc Option

In-proc session storage option doesn’t work well in Microsoft Azure architecture. First of all, ASP.NET Session State is not shared between multiple instances of the Web Role in In-proc mode. Secondly, you end up using sticky sessions in Microsoft Azure, which may result in uneven load distribution. Additionally, sticky sessions involve extra configurations on your part as Microsoft Azure doesn’t use sticky sessions by default. Moreover, any Web Role instance going down due to failure or for maintenance will result in session data loss and this is obviously not acceptable.

Azure Table Option

Azure Table Storage is file based ASP.NET Session State provider, which is provided on an ‘as-is basis’ as a code sample, meaning it is not officially supported by Microsoft. It is intended for storing entities that are structured. Even though it is a cheaper option it is still not an ideal place to store ASP.NET Session State primarily because of performance as it is file based.

SQL Database Option

Microsoft Azure SQL Database can also be used as storage for ASP.NET Session State by using conventional ASP.NET SQLServer Mode. But, ASP.NET Session State object is stored in the database as a BLOB and relational databases were never really designed for BLOB storage. This causes performance issues and it is definitely a major scalability bottleneck for your Microsoft Azure ASP.NET application.

Distributed Cache Option

Distributed Cache provides an ideal storage for ASP.NET Session State in Microsoft Azure. For example you can use NCache for Azure which is a Microsoft Azure Distributed Cache for .NET applications. It is extremely fast and more scalable than all other Microsoft Azure options mentioned above and it also replicates sessions so there is no data loss if a cache server ever goes down. Moreover, you eliminate all issues related to session sharing as well as use equal load balancing that ensures full utilization of all of your Azure Web role instances.

How to Configure NCache in Azure ASP.NET Session State Provider?

NCache in Azure has implemented the ASP.NET Session State provider that can be used by Microsoft Azure ASP.NET applications. NCache in Azure uses Microsoft Azure VMs and formulates a dedicated caching tier. ASP.NET applications in Microsoft Azure can then be directed to use this Azure Distributed Cache for ASP.NET Session State storage.

The nice thing about NCache in Azure ASP.NET Session State provider is that it doesn’t require any application code changes. Simply modify your application web.config file as follows to use NCache in Azure as your Distributed Cache for ASP.NET Session State:

      <add assembly="Alachisoft.NCache.SessionStoreProvider,
           Version=x.x.x.x, Culture=neutral,

<sessionState cookieless="false" regenerateExpiredSessionId="true" mode="Custom"
              customProvider="NCacheSessionProvider" timeout="20">

      <add name="NCacheSessionProvider"
           sessionAppId="NCacheTest" cacheName= "TestCache"
           writeExceptionsToEventLog="false" />

Here are a few important benefits you achieve when you use NCache for Azure as your distributed cache for storing ASP.NET Session State.

  • Linear Scalability and Performance: NCache for Azure is based on dynamic clustering protocol, which allows you to add more servers to your cache at runtime. Your application can scale out linearly by adding more servers to your Azure Distributed Cache when your application load grows without changing application architecture.
  • Session Replication: NCache for Azure provides reliability support with help of replication. You can take application instances offline for maintenance, patching and for new releases without having to worry about any session data loss.
  • High Availability: NCache for Azure provides fault tolerant support of high availability as it is based on hundred percent peer to peer architecture. It is guaranteed that you will not lose any data or have any application downtime in case of any node failure from distributed cache.


Azure Distributed Cache such as NCache in Azure is the best option for storing ASP.NET Session State in Microsoft Azure primarily because of performance, scalability, reliability and high availability features. Microsoft Azure Distributed Cache offered by NCache for Azure is very easy to use and doesn’t require any application code changes.

Download NCache for Azure Trial | NCache for Azure Details

Posted in ASP.Net, Distributed Cache, Microsoft Azure | Tagged , , | Leave a comment

ASP.NET Session State Sharing across Multiple Azure Regions

Many high traffic ASP.NET applications in Microsoft Azure are deployed over multiple Microsoft Azure regions in order to handle geographically separated traffic. In these situations, the load balancer always sends traffic to the Microsoft Azure region closest to the user for faster response time.

In this scenario, you may run into a situation where you have to redirect some of your traffic to and from one Microsoft Azure region to another. This may happen because you have too much traffic in one Microsoft Azure region and another region is underutilized. Another reason may be that you need to bring a region down for maintenance.

When you redirect traffic, your users normally lose their ASP.NET sessions because your ASP.NET Session State is not available in the other Microsoft Azure region. And, this is obviously not good. Ideally, you want to redirect traffic without causing any interruptions for your users.

In Microsoft Azure, the only way you can achieve this is if you keep a common ASP.NET Session State storage across multiple Microsoft Azure regions. This allows you to redirect traffic without losing any ASP.NET Session State. But, this option has severe performance issues because a large percentage of ASP.NET sessions are being accessed across the WAN.

NCache in Azure is an extremely fast and scalable Microsoft Azure distributed cache for .NET applications. NCache in Azure provides an intelligent multi-region ASP.NET Session State support for your ASP.NET applications deployed in multiple Microsoft Azure regions.

NCache in Azure intelligently detects and then automatically moves your ASP.NET sessions from one Microsoft Azure region to another region when user request is redirected from one Microsoft Azure region to another. All subsequent requests are served from this new Microsoft Azure region. This allows your ASP.NET applications to seamlessly share ASP.NET sessions across Microsoft Azure regions without negatively impacting performance or causing session data loss.

NCache for Azure allows you to achieve multi-region ASP.NET Session State capability by defining primary and secondary caches in each Microsoft Azure region. Additionally, you also specify “sid-prefix” attribute, which is prefixed to all session-IDs in each Microsoft Azure region. This helps NCache for Azure SSP module to identify which ASP.NET sessions belong to which Microsoft Azure region and then NCache for Azure decides to move ASP.NET sessions when a request redirects to another Microsoft Azure region.

Here is a sample config to use NCache for your ASP.NET Session State storage:

      <add assembly="Alachisoft.NCache.SessionStoreProvider,
           Version=x.x.x.x, Culture=neutral,

<sessionState cookieless="false" regenerateExpiredSessionId="true" mode="Custom"
              customProvider="NCacheSessionProvider" timeout="20">

      <add name="NCacheSessionProvider"
           sessionAppId="NCacheTest" cacheName= "London_Cache"
           writeExceptionsToEventLog="false" />

Additionally you need location affinity configurations for  Azure Multi-region ASP.NET Session State support.

     <section name="ncache" type="Alachisoft.NCache.Web.SessionStateManagement.NCacheSection,
              Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>

      <primaryCache id =  "London_Cache"  sid-prefix = "LDC"/>
      <secondaryCache id ="NewYork_Cache" sid-prefix = "NYC"/>
      <secondaryCache id ="Tokyo_Cache"   sid-prefix = "TKC"/>
   </sessionLocation >

Please note that <ncache> section in each Azure Region will be different, meaning each region will have its own “PrimaryCache” and will define all other region caches as “SecondaryCache”.

All ASP.NET sessions originated from any Microsoft Azure region are originally stored in the primary cache in that region. However, when a request from another Microsoft Azure region is redirected to the current Microsoft Azure region then NCache for Azure multi-region SSP module intelligently detects that the ASP.NET Session State resides in one of the other Microsoft Azure regions (using “sid-prefix” attached to ASP.NET Session ID) and it automatically contacts the corresponding secondary cache on remote Microsoft Azure region and moves it to primary cache on current Microsoft Azure region. All subsequent requests are then served from this new location.

Say for example, you have defined London_Cache to be your primary cache while NewYork_Cache and Tokyo_Cache are defined as secondary caches for London site. You also specify “LDC”,”NYC” and “TKC” as sid-prefix that are attached to each session-id corresponding to London_Cache, NewYork_Cache and Tokyo_Cache sessions respectively. Now, all ASP.NET sessions originated from London region have “LDC” attached as prefix to their ASP.NET Session IDs and are stored and served from London_Cache, which is primary cache for London region. But, if a request is redirected from other Microsoft Azure region such as New York or Tokyo to London region then this ASP.NET Session State is immediately identified based on sid-prefix and ASP.NET Session State is transferred from NewYork_Cache or Tokyo_Cache to London_Cache. All subsequent requests are served from London_Cache locally once ASP.NET Session State is moved to London region.


NCache for Azure multi-region ASP.NET Session State support allows you to have your ASP.NET applications deployed in two or more active Microsoft Azure regions and be able to redirect traffic between Microsoft Azure regions without impacting performance or causing any application downtime. You can seamlessly redirect requests between Microsoft Azure regions to handle traffic overflows and site maintenance.

Download NCache for Azure Trial | NCache for Azure Details

Posted in ASP .NET performance, ASP.Net, Microsoft Azure | Tagged , , , | Leave a comment

Distributed Cache as NHibernate Second Level Cache

NHibernate is a very popular object-relational mapping (ORM) solution for .NET applications because it simplifies your database programming. As a result, many applications using NHibernate are high traffic in nature and therefore face scalability bottlenecks in the database.

To tackle this, NHibernate provides a caching infrastructure so that applications can use an in-memory cache store instead and database is not exhausted anymore due to such high request load.  NHibernate caching includes first level cache and second level cache.

NHibernate First Level Cache and its Limitations

NHibernate First Level (1st level) Cache provides you a basic standalone (in-proc) cache which is associated with Session object and is limited to the current session only. 1st level cache is used by default to reduce the number of SQL queries on the database per session. But, there are a lot of limitations with this 1st level cache as follows:

  • Each process has its own 1st level cache that is not synchronized with other 1st level caches so data integrity cannot be maintained.
  • Cache size is limited to the process memory and cannot scale.
  • Worker process recycling causes cache to be flushed. Then, you have to reload it which reduces your application performance.

Solution: A Distributed Cache for NHibernate

NHibernate Second Level Cache exists at the Session Factory level, which means multiple user sessions can access a shared cache. Additionally, NHibernate 2nd level cache has a plug-able architecture so you can plug-in a third party distributed cache to it without any programming. NCache has implemented NHibernate Second Level Cache Provider and you can use it as your distributed cache for NHibernate without any code changes.

Following example shows you how to use NCache in your NHibernate application as its 2nd level cache:

        <property name="cache.provider_class">Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider, Alachisoft.NCache.Integrations.NHibernate.Cache
        <property name="proxyfactory.factory_class"> NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate </property>
        <property name="cache.use_second_level_cache">true

        <region name="AbsoluteExpirationRegion" cache-name="myCache" priority="Default" expiration-type="sliding" expiration-period="180" use-async="false" />
        <region name="default" cache-name="myCache" priority="default" expiration-type="none" expiration-period="0" />

Here are some important benefits of NCache as NHibernate 2nd level cache:

  • NCache synchronizes across processes & servers: NCache is a shared cache across multiple processes and servers. This ensures that cache is always consistent across multiple servers and all cache updates are synchronized correctly so no data integrity issues arise.
  • Scalable cache size: NCache pools memory of all cache servers together. So, you can grow the cache size by simply adding more servers to the cache cluster. This means your cache can grow to 100′s of gigabytes and even terabytes.
  • Application process recycling does not affect the cache: Your application processes now become stateless as all the data is kept in an out-proc distributed cache. So, application process recycling has no impact on the cache.
  • Linear scalability to handle larger transaction loads: You can handle larger transaction loads without worrying about your database becoming a bottleneck. This is because the distributed cache scales linearly and reduces your database traffic by as much as 90%.
  • Use Client Cache to store data In-proc: NCache provides support of client cache, which is a synchronized local cache and can also run in-proc within your worker process. You can use it to attain more performance within your NHibernate applications.

As you can see, a distributed cache like NCache enables you to use NHibernate and still run your application in a multi-server configuration. You can also scale your application and handle high transaction loads by using NCache as NHibernate Second Level Cache.

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

Posted in 3rd party integrations, Distributed Cache, NHibernate | Tagged , , , , | Leave a comment

How to Replicate a Distributed Cache across the WAN?

Web applications today are handling millions of users a day. Even with this high traffic, you have to maintain high performance for your users. To achieve this performance goal, many people are using in-memory distributed cache because it is faster than going to the database. A distributed cache also provides scalability by allowing you to add cache servers at runtime as you need to handle higher transaction load.

This is all good. But, you may need to deploy and run your web applications in multiple data centers. You may do this for a variety of reasons. One is to have a disaster recovery option. In this option, you have one active and one passive data center. If the active data center goes down, the passive data center quickly picks up the traffic without causing any interruptions for the users.

Another reason is to locate data centers closer to your customers especially if they are geographically dispersed. This greatly speeds up the application response time for your users. In this option, you may have two or more active data centers rather than an active-passive data center.

If you have multiple data centers either for handling region specific traffic or for disaster recovery purpose, then you need to replicate your cache across all data centers. This replication is across the WAN and would be very slow due to latency unless you do asynchronous replication.

NCache Banner - Reliable multi-site ASP.NET Session Storage

NCache is an extremely fast in-memory distributed cache that also provides WAN replication for your multi-datacenter needs. With NCache, there is no performance degradation while replicating your cache across the WAN because NCache does it asynchronously.

NCache Bridge Topology maintains an in-memory mirrored queue which has all the cache updates. The Bridge can then apply the same updates to one or more target caches whether they’re active or passive. You can read more about Bridge Topology at WAN Replication Topologies (Bridge)

How to Handle WAN replication for Different Scenarios?

Active-Passive Data Centers

NCache Bridge Topology can be configured for active-passive replication. The active distributed cache submits cache changes to the Bridge so it can apply it to the passive datacenter cache.

Active-Active Data Centers

In this scenario, the Bridge has to also handle conflict resolution because both data centers are active and could be updating the same data. This is called conflict resolution and is discussed later in this blog.

You can use any Bridge Topology according to your needs. For example, you may be storing ASP.NET Session State in your distributed cache and these sessions need to be replicated across the WAN to the other data center.

When the same data element/item in multiple distributed caches is updated and submitted to Bridge for replication a conflict occurs. To handle conflicts, NCache adds a timestamp for every operation before submitting it to the Bridge. This is to help the Bridge determine which operation was done last for the “last update win” rule.

NCache also provides you the flexibility to implement your own custom conflict resolver and plug in it with your distributed cache.

Here is an example of a conflict resolver:

public class BridgeConflictResolverImpl : IBridgeConflictResolver
   private bool _enableLogging;
   private TextWriter _textLogger;

   // to initialize any parameters if needed.
   public void Init(System.Collections.IDictionary parameters) { ... }

   // To resolve entry on the basis of old and new entries.
   public ConflictResolution Resolve(ProviderBridgeItem oldEntry,
                                     ProviderBridgeItem newEntry)
      ConflictResolution conflictResolution =
                                        new ConflictResolution();
      switch (oldEntry.BridgeItemVersion)
         case BridgeItemVersion.OLD:
              conflictResolution.ResolutionAction =
         case BridgeItemVersion.LATEST:
              conflictResolution.ResolutionAction =
         case BridgeItemVersion.SAME:
              if (oldEntry.OpCode == BridgeItemOpCodes.Remove)
                    conflictResolution.ResolutionAction =
                    conflictResolution.ResolutionAction =

      return conflictResolution;

   // To dispose parameters if needed.
   public void Dispose() {...}

As you can see, the custom conflict resolver allows you to make content driven decisions about which update should “win”.

In summary, the Bridge Topology allows you to run your applications in multiple data centers without having to worry about your cache getting out of sync with the other location. This ensures that your application will always be up even if one data center goes down or you will be able to re-route traffic to the other data center if one datacenter gets overwhelmed with it.

Download NCache Trial | NCache Details

Posted in Bridge Topology, Distributed Cache, Distributed Cache Replication | Tagged , , | Leave a comment

How to Store ASP.NET Session State in Multi-Site Deployments?

ASP.NET has become really popular for developing high traffic web applications. Many of these applications are deployed to multiple geographical locations. This is done either for disaster recovery purposes or for handling regional traffic by having the ASP.NET application closer to the end user. In case of disaster recovery, there is usually one active site and one passive site. The passive site becomes active as soon as the active site goes down for any reason. In other cases, two or more sites can all be active, but handling traffic closer to their region (e.g. New York, London, and Tokyo). ASP.NET keeps user specific information in ASP.NET Session State object on the web server. This ASP.NET Session State is created when the user first uses the ASP.NET application and stays active as long as the user is actively using the application. By default, after 20 minute of inactivity by the user, ASP.NET expires this session. ASP.NET Session State object is either stored in-memory on the web server (InProc), in-memory on any server (StateServer), in a SQL Server database, or in a third-party store by using ASP.NET Session State Provider (SSP) architecture. The third-party option usually is an in-memory distributed cache. An in-memory distributed cache like NCache is a great place to store ASP.NET Session State. The reasons are faster performance, greater scalability, and better reliability of ASP.NET Session State due to session replication. Below is an example of how you can specify a “custom” session storage option in web.config file, which results in NCache being used as ASP.NET Session State storage:

Active-Passive Multi-Site Deployment

But, if your application is running in a multi-site deployment, then the question you have to address is what to do about ASP.NET Session State storage. If your ASP.NET application is deployed in an active-passive multi-site configuration, then all your ASP.NET Session State is being created and stored in the active site. And, the passive site does not have any session data. So, if the active site goes down and all the traffic is redirected to the passive site, then all users will suddenly lose their sessions and will have to start over.

NCache Banner - Reliable multi-site ASP.NET Session Storage

You can avoid this by using NCache Bridge Topology. Once you create a Bridge between the active and the passive sites, the active site starts submitting all adds, updates, and removes of ASP.NET Session State objects to the Bridge. The Bridge asynchronously replicates them across the WAN to the passive site. The nice thing about the Bridge architecture is that it doesn’t block the active site operations at all so you don’t see any performance degradation because of it. The only issue you have to keep in mind is that since the Bridge replicates asynchronously, there may be some sessions in the “replication queue” that won’t make it to the passive site if the active site abruptly shuts down. But, this is usually a very small number. Read more about NCache Bridge Topology and all the situations where you can use it.

Active-Active Multi-Site Deployment

If your ASP.NET application is deployed to two or more active sites simultaneously then I recommend that you not replicate ASP.NET Session State to all the sites to save on bandwidth cost. Additionally, most likely, each of your active site is geographically separated and it might make sense for you to keep its regional traffic to this site completely. However, you probably want the ability to route some of the traffic to other sites to handle overflow situations. Or, you may need to bring one of the sites down for maintenance without any interruptions for the users. In this case, you can use the multi-site ASP.NET Session State Storage feature in NCache that lets you handle these cases. It lets you specify in web.config to generate session-ids with a location prefix for this session’s “primary” site. Then, even if this session request is routed to another site, that site knows where to find this session. In this approach, the sessions do not move from their primary location even if the user request is routed to the other site. But, the other site is able to access this session from its “primary” site. Actually, each site specifies its “primary” and all others as “secondary” sites. Below are the steps you take to achieve this goal:

    1. Add entry in web.config. It is required to generate ASP.NET session-id in the same manner on all servers and sites. You can use the genmackeys utility available with NCache installation to generate the keys.

  1. To enable location affinity of a session-id, add configuration mentioned below:

  1. Specify custom session-id manager using the sessionIDManagerType attribute of the sessionState element in web.config.

Please note that in the above example, the <ncache> section in each site will be different, meaning each site will have its own “primary” and will consider all other sites as “secondary”. In the above example, you can see that ASP.NET is being asked to generate session-id in a specific format so the sid-prefix can be prepended with the session-id. Once this is done, it helps ASP.NET know where this ASP.NET Session State was actually created so the cache for that site is accessed. With this configuration, if you route any requests from one site to another for overflow, the other site fetches the ASP.NET Session State from its original “primary” site because this is part of the session-id as a location prefix. So, your WAN bandwidth consumption is minimized and you only pay for overflow traffic. The other situation is where you want to bring a site down. In this case, just redirect all of its traffic to other sites but don’t shut down the cache servers of this site; you can shut down the web servers. And, then wait for all existing ASP.NET Session State objects to expire after their users have stopped using the application. Once this is done, just shut down the cache servers as well. With this, your users will not feel any downtime. Take a look at how NCache helps you achieve this goal. Download a fully working 60-day trial of NCache.

Download NCache Trial | NCache Details

Posted in ASP.Net, Distributed Cache | Tagged , , | Leave a comment

How to Use Custom Dependency in Distributed Cache?

Today, web applications are increasingly using distributed cache for boosting performance and scalability by caching frequently used data so as to reduce expensive database trips. Distributed cache spans and synchronizes over multiple cache servers to let you scale in a linear fashion. A good distributed cache usually has a Cache Dependency feature to let you expire cached items when something they depend on changes. A Cache Dependency can be key-based, file-based, or database-based. So, in essence you can specify a cached item to be dependent on another item in the cache (key-based), a file in the file system (file-based), or a row or a dataset in a SQL Server database (database-based). And, when data in any of these sources changes, your cached item is automatically removed from the cache because the “dependency was expired”. This allows you to keep your cached data fresh and correct always.

This is all well and good but what if you want your cached items to be dependent on data in data sources other than the ones mentioned above. For example, you might have an RSS feed (Rich Site Summary) that provides you data changes. And, you have your own program to read this feed and want to expire certain cached items based on whatever data changes you see in the RSS feed. There are many other similar situations where the data source is “custom”. So, to handle these situations, a good distributed cache should provide you the flexibility to implement your own Custom Cache Dependency for your cached items so they can be expired when data in your custom data source changes.

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

NCache provides such a Custom Cache Dependency feature. NCache is a powerful distributed cache for all kinds of .NET applications. And, NCache lets you implement your own custom dependencies. Let me demonstrate how easily you can implement a custom dependency with NCache below. Here are the steps you have to take:

  1. Add using Alachisoft.NCache.Runtime.Dependencies; reference to your custom dependency implementation.
  2. NCache provides extensible abstract class named as ExtensibleDependency which is base class of all dependencies. You just have to inherit your custom dependency class from ExtensibleDependency and then just override its HasChanged property. When this property will return true, than item dependent item will be expired from cache.

Here is a full example of custom dependency implementation in which if available units of a specified product are less than 100 then dependency change will be triggered.

using Alachisoft.NCache.Runtime.Dependencies;

public class CustomDependency : ExtensibleDependency
   private string _connString;
   private int _productID;

   public override bool Initialize(){ return false; }

   public CustomDependency(int productID, string connStr)

     _connString = connStr;
     _productID = productID;


   internal bool DetermineExpiration()
     if (GetAvailableUnits(_productID) < 100)
            return true;
     return false;

   internal int GetAvailableUnits(int productID)
     OleDbDataReader reader=null;
     OleDbConnection connection=
                      new OleDbConnection(_connString);
     int availableUnits=-1;
        OleDbCommand cmd = connection.CreateCommand();

        cmd.CommandText =
        "Select UnitsInStock From Products" +
        " where ProductID = {0}", productID);
        reader = cmd.ExecuteReader();

        if (reader.Read())
          availableUnits =

        return availableUnits;
     catch (Exception)
         return availableUnits;

   public override bool HasChanged
         return DetermineExpiration();
  1. Once you implemented your custom dependency and deployed it with NCache service, all you need is to register this dependency with dependent cache items in your application wherever needed.
using Alachisoft.NCache.Web.Caching; //add namespace

//Add following code in your application
Cache _cache = NCache.InitializeCache("myCache");

string connString =
       "Provider=SQLOLEDB;Data Source=localhost;
        User ID=sa;password=;Initial Catalog=Northwind";

CustomDependency hint = new CustomDependency(123, connString);

_cache.Add("Product:1001", "Value", new CacheDependency(hint),
       Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 10),

Now when data in your custom data source changes, NCache expires the dependent cached items automatically from cache. NCache is responsible for running your custom dependency code so you don’t need to worry about implementing your own separate program and hosting it in some reliable process. Try and explore it for your application specific scenarios.

Download NCache Trial | NCache Details

Posted in Cache dependency, Custom Dependency, Distributed Cache, Distributed caching | Tagged , , , | Leave a comment

How to Configure .NET 4.0 Cache to use a Distributed Cache?

In-memory distributed cache today has become really popular for applications running in a multi-server environment because it helps improve application scalability and performance. Until .NET Framework 3.5 there was ASP.NET Cache object available only for web application under System.Web.Caching namespace. But, in .NET Framework 4.0, .NET 4.0 Cache is added under System.Runtime.Caching namespace for all types of .NET applications. .NET 4.0 Cache has functionality similar to ASP.NET Cache. But, unlike ASP.NET Cache, it has an abstract class ObjectCache that can be implemented in a customized way as needed. So, in essence .NET 4.0 Cache can be extended which ASP.NET Cache cannot be. And, MemoryCache is the default in-memory cache implementation of .NET 4.0 Cache. Here is an example:

private static ObjectCache cache = MemoryCache.Default;

private CacheItemPolicy policy = null;

private CacheEntryRemovedCallback callback = null;

// Registering callbacks and policies…
callback = new

policy = new CacheItemPolicy();

policy.Priority =
 (MyCacheItemPriority == MyCachePriority.Default) ?

CacheItemPriority.Default : CacheItemPriority.NotRemovable;

policy.RemovedCallback = callback;

HostFileChangeMonitor changeMonitor =
 new HostFileChangeMonitor(FilePath);


// Add inside cache…
cache.Set(CacheKeyName, CacheItem, policy);

One limitation of .NET 4.0 Cache’s default implementation MemoryCache is that it is a stand-alone in-process cache. If your .NET application runs on a multi-server environment, then you cannot use this because you need a distributed cache that can synchronize the cache across multiple servers. But fortunately, .NET 4.0 Cache architecture allows us to plug in a third party distributed cache solution and extend it.

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

To address this need, Alachisoft has implemented an easy to use .NET 4.0 Cache Provider that can solve data synchronization, distribution and scalability issues especially in case of web farm/garden. This provider basically integrates NCache with .NET 4.0 Cache. NCache is a very popular enterprise level distributed cache for .NET. Through NCache’s .NET 4.0 Cache Provider you can plug in NCache with your application to achieve the benefits of a distributed cache. Let me show you how easily it can be done with NCache by a few steps.

  1. Create a Clustered (distributed) cache through GUI based NCache Manager. I created a clustered cache named as “MyClusterCache”.
  2. Start the cache to make it ready to use.
  3. Add references of  Alachisoft.NCache.ObjectCacheProvider library to your application from “NCacheInstallDir/NCache/integration/DotNet4.0 Cache Provider
  4. Include the following namespace in your project.
    using Alachisoft.NCache.ObjectCacheProvider;
  5. Initialize your CacheProvider (inherited from ObjectCache) and pass your cache name to the provider as shown below.
    ObjectCache _cache;
    string _cacheId = "MyClusterCache" ;
    _cache = new CacheProvider(_cacheId);
  6. Now you can perform all cache related operations on your cache using CacheProvider commands.

Here is full example of .NET 4.0 extended for NCache:

ObjectCache _cache;

string _cacheId = "MyClusterCache" ;

// Initialize with NCache’s .NET 4.0 Cache Provider.
_cache = new CacheProvider(_cacheId);

// Registering callbacks and policies…
NCacheFileChangeMonitor changeMonitor =
 new NCacheFileChangeMonitor(fileNames);

CacheItemPolicy ciPolicy = new CacheItemPolicy();


ciPolicy.RemovedCallback +=
 new CacheEntryRemovedCallback(onCacheEntryRemoved);

//Add the dependent items in the cache.
_cache.AddItems(ciPolicy, 0, totalKeys);

NCache implementation of .NET 4.0 Cache also includes custom implementation of ChangeMonitor as NCacheEntryChangeMonitor, NCacheFileChangeMonitor, NCacheSqlChangeMonitor and NCacheOracleChangeMonitor for entry, file, SQL and Oracle based changes respectively. Through NCache’s implementation of .NET 4.0 Cache interface, you can now adopt .NET 4.0 Cache as your standard and at the same time benefit from an enterprise level distributed cache for your .NET applications running in a multi-server environment.

Download NCache Trial | NCache Details

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

How to Cache ASP.NET View State in a Distributed Cache?

ASP.NET today is widely used for high traffic web applications that need to handle millions of users and are deployed in load balanced web farms. One important part of ASP.NET is View State that many applications use. ASP.NET View State is a very powerful mechanism that stores pages, controls and custom values between multiple HTTP requests across client and the web server.

ASP.NET View State values are stored in a hidden field on the page and encoded as a Base64 string. An ASP.NET View State looks like this:

<input id="__VIEWSTATE" type="hidden"
value="/wEPDwUJNzg0MDMxMDA1D2QWAmYPZBYCZg9kF..." />

Although very useful, ASP.NET View State frequently becomes quite large especially in situations where your ASP.NET application has grid controls and many other controls on pages. This is added to your HTTP request and response and that really slows down your ASP.NET response time to unbearable levels.

Another downside of heavy ASP.NET View State is the increased bandwidth usage that increases your bandwidth cost considerably. For example, if for each HTTP requests, you end up appending 60-100k of additional ASP.NET View State data, just multiply it by the total number of transactions and you’ll quickly see how much more it will cost you in bandwidth consumption.

Finally, in some situations, there is a security risk with sending confidential data as part of ASP.NET View State. Encrypting it before sending is also costly.

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

To resolve all these problems you can cache ASP.NET View State on the web server and assign a GUID as its key in the cache. This GUID is then sent to the browser in a hidden field and it comes back along with the next HTTP request and is used to fetch the corresponding ASP.NET View State from the cache. This reduces your payload sent to the browser, which not only improves ASP.NET response time, but also reduces your bandwidth consumption cost dramatically.

If your ASP.NET application is running in a load balanced web farm, then you must use a distributed cache. A stand-alone cache like ASP.NET Cache won’t work. NCache is an enterprise level distributed cache that provides ASP.NET View State caching module. In order to use it, you don’t need to do any programming. Just modify your ASP.NET web.config for it.

Here are the steps to use NCache for caching ASP.NET View State:

  1. Create an app.browser file in your ASP.NET application. Create it under the directory App_browsers. Plug in page adapters in the app.browser file as following:
    <browser refID="Default">
    <adapter controlType="System.Web.UI.Page"
  2. Then add the following assembly reference in compilation section of web.config file.
    <compilation defaultLanguage="C#" debug="true">
    <add assembly="Alachisoft.NCache.Adapters,
  3. Register your config section in web.config file.
    <sectionGroup name="ncContentOptimization">
    <section name="settings"
    allowLocation="true" allowDefinition="Everywhere"/>
  4. Specify settings for your config section in web.config file (that was registered above).
    <settings enableMinification="true"
    <cacheSettings cacheName="mycache">
    <expiration type="Sliding" duration="300"/>
  5. In the end, register the HTTP handler in the HttpHandlers section of web.config as following:
    <add verb="GET,HEAD" path="NCResource.axd"
    Alachisoft.NCache.Adapters, Version=,

After configuring NCache, you can see the ASP.NET View State tag in your application as:

< input type="hidden"
value="vs:cf8c8d3927ad4c1a84da7f891bb89185" />
< input type="hidden"
name="__VIEWSTATE" id="__VIEWSTATE" value="" />

Notice that another hidden tag is added with ASP.NET View State. It contains the unique key assigned to ASP.NET View State of your page, in your distributed cache. So whenever your application server needs ASP.NET View State value it can get it from cache easily.

With this, you will see a remarkable performance boost in your ASP.NET response times and your bandwidth consumption cost is reduced significantly as well.

Please explore more about ASP.NET View State caching by trying NCache ASP.NET View State module yourself.

Download NCache Trial | NCache Details

Posted in ASP .NET performance, ASP.Net, ASP.NET Cache, Distributed Cache, Distributed caching | Tagged , , | 2 Comments

How to Configure Preloading in a Distributed Cache?


Today’s applications need to scale and handle extreme levels of transaction loads. But, databases are unable to scale and therefore become a bottleneck. To resolve this, many people are turning to in-memory distributed cache because it scales linearly and removes the database bottlenecks.

A typical distributed cache contains two types of data, transactional data and reference data. Transactional data changes very frequently and is therefore cached for a very short time. But, caching it still provides considerable boost to performance and scalability.

Reference data on the other hand does not change very frequently. It may be static data or dynamic data that changes perhaps every hour, day, etc. At times, this data can be huge (in gigabytes).

It would be really nice if this reference data could be preloaded into a distributed cache upon cache start-up, because then your applications would not need to load it at runtime. Loading reference data at runtime would slow down your application performance especially if it is a lot of data.

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

How Should Reference Data be Preloaded into a Distributed Cache?

One approach is to design your application in such a way that during application startup, it fetches all the required reference data from the database and puts it in the distributed cache.

However, this approach raises some other issues. First, it slows down your application startup because your application is now involved in preloading the cache. Second, if you have multiple applications sharing a common distributed cache, then you either have code duplication in each application or all your applications depend on one application preloading the distributed cache. Finally, embedding cache preloading code inside your application corrupts your application design because you’re adding code that does not belong in your application. Of course, neither of these situations is very desirable.

What if we give this preloading responsibility to the distributed cache itself? In this case, preloading could be part of the cache startup process and therefore does not involve your application at all. You can configure the cache to preload all the required data upon startup so it is available for all the applications to use from the beginning. This simplifies your application because it no longer has to worry about preloading logic.

NCache provides a very powerful and flexible cache preloading capability. You can develop a cache loader and register it with NCache and then NCache calls this custom code developed by you upon cache startup. Let me demonstrate how to do this below:

  • Implement a simple interface named ICacheLoader. It is called to assist the cache in answering the question “How and which data to load?”
class CacheLoader : ICacheLoader

 public void Init(System.Collections.IDictionary parameters)
   // Initialization of data source connection, assigning parameters etc.

 public bool LoadNext(
 ref System.Collections.Specialized.OrderedDictionary data,
 ref object index)
   // Fill ref objects with data that should be loaded in cache.

 public void Dispose()
   // Disposing connections and other required objects.


  • Next step is to configure above implemented startup loader with cache. We can do it by using NCache Manger that comes with NCache or simply by adding following configuration in cache config.
<cache -loader retries="3" retry-interval="0" enable-loader="True">
   <provider assembly-name="TestCacheLoader, Version=, Culture=neutral,
   < !—parameters that will be passed to Init method of the loader-->
   <parameters name="connectionString"
   value="Data Source= SQLEXPRESS;
   Initial Catalog=testdb;Integrated Security=True;Pooling=False"></parameters>

Any exception occurred during startup loader processing is logged without creating any problem for your application. Simple and effective!

As you can see, NCache provides you a powerful mechanism to preload your distributed cache and keep the performance of your applications always high.

Download NCache Trial | NCache Details

Posted in Distributed Cache | Tagged , , | Leave a comment

How to use a Distributed Cache for ASP.NET Output Cache?

ASP.NET Output Cache is a mechanism provided by Microsoft that allows you to keep an in memory copy of the rendered content of ASP.NET page. Due to this, ASP.NET is able to serve the subsequent user requests for this page from an in-memory cached copy instead of re-executing this page which can be quite expensive because it usually also involves database calls.

So, ASP.NET Output Cache not only improves your application performance, but also reduces a lot of expensive database trips. This improves your ASP.NET application scalability because otherwise the database would become a scalability bottleneck if all those ASP.NET pages were executed again and again.

But, the problem with the ASP.NET Output Cache is that it resides in your ASP.NET worker process address space. And, worker process resets or recycles quite frequently. When that happens, all the ASP.NET Output Cache is lost. Secondly, in case of a web garden (meaning multiple worker processes) the same page output is cached multiple times, once in each worker process and this consumes a lot of extra memory. Also, did you know that one of the most common support calls for ASP.NET is out-of-memory errors caused by ASP.NET Output Cache?

Download NCache free trial - Extremely fast and scalable in-memory distributed cacheAlso read: ASP.NET Output Cache in Microsoft Azure to Improve Performance

To overcome these limitations of ASP.NET Output Cache and to take advantage of its benefits, try using a distributed cache for storing all of ASP.NET Output Cache content. In this regard, NCache has implemented an ASP.NET Output Cache provider to enable the caching of ASP.NET rendered output in out-of-process (out-proc) cache instead of worker process address space. This way, the output of your rendered ASP.NET page is available to all other web servers in the web farm without even rendering the same ASP.NET page locally in each worker process.

By using NCache as ASP.NET Output Cache provider you can not only cache more data in out-proc cache,  but can also dramatically reduce the load on your database. This is because each rendered ASP.NET page output is accessible to all web servers in web farm without executing the page rendering process in each worker process which involves expensive database trips.

Further, NCache as ASP.NET Output Cache provider gives you the flexibility to even cache the output of certain parts of your ASP.NET page instead of complete page. This approach is very helpful in scenarios where you want certain parts of your ASP.NET to render each time. In addition, NCache also provides you high availability because even if your worker process resets or recycles, your data is not lost because it is not part of your worker process address space and resides on separate caching servers.

Steps to Configure NCache Output Caching Provider

1. Register NCache as ASP.NET Output Cache Provider: Modify your ASP.NET applications web.config to register NCache output caching provider as follows:

    &amp;amp;amp;amp;lt;outputCache defaultProvider ="NOutputCacheProvider" /&amp;amp;amp;amp;gt;
&amp;amp;amp;amp;lt;add name="NOutputCacheProvider"
     exceptionsEnabled="true" enableLogs="false"
     cacheName="mypartitionofReplicaCache" /&amp;amp;amp;amp;gt;

&amp;amp;amp;amp;lt;compilation debug="true" targetFramework="4.0"&amp;amp;amp;amp;gt;
      &amp;amp;amp;amp;lt;add assembly="Alachisoft.NCache.OutputCache,
           Version=, Culture=neutral"/&amp;amp;amp;amp;gt;

2. Add ASP.NET Output Cache tag: Add the under mentioned Output cache tag to those pages whose output you want to cache.

&amp;amp;amp;amp;lt;%@ OutputCache VaryByParam="ID" Duration="300" %&amp;amp;amp;amp;gt;

By the way, ASP.NET versions earlier than ASP.NET 4.0 do not provide support of custom ASP.NET Output Cache providers. Therefore, to support all earlier versions of ASP.NET NCache has also implemented another version of ASP.NET Output Cache provider using an HttpModule. This HttpModule based ASP.NET Output Cache provider by NCache enables you to use distributed cache to store rendered ASP.NET page output, even if your application is using ASP.NET versions earlier than 4.0.

In summary, by using NCache output caching provider you can easily boost your ASP.NET application response time and can reduce database load.

Download NCache Trial | NCache Details

Posted in ASP.Net, ASP.NET Output Cache, Distributed Cache | Tagged , , | 1 Comment