ASP.NET Output Cache in Microsoft Azure to Improve Performance

Microsoft ASP.NET Output Cache provides functionality to cache rendered content of ASP.NET pages or user controls for a specified duration. This allows your ASP.NET application to serve all subsequent requests from the cache instead of re-rendering and re-execution of a page.

You add the <% @OutputCache %> directive on the page to use ASP.NET Output Cache.

<%@Page ... %>

ASP.NET Output Caching is a very useful feature, especially for situations when a page is accessed more frequently than it changes and you serve it from cache. This improves application performance by avoiding page re-executions and also by reducing your expensive database trips especially when page involves a lot of heavy database operations. This also improves application scalability because the database generally becomes a scalability bottleneck when there are millions of such pages and requests involving database operations.

Problems with ASP.NET Output Cache in Microsoft Azure Environment

When you use Output Cache in Microsoft Azure then page output is stored as InProc within your Microsoft Azure Web Role by default. First problem with this is that it limits you to the memory that is available on your Web Role instance and this may create an out of memory issue when you cache a large amount of page output data. Another issue is that your application runs on multiple load balanced Microsoft Azure Web Role instances. The next request might go to another Web Role instance, which creates a new copy of ASP.NET Output Cache data in this instance, as well. These redundant copies of page outputs in each Web Role instance consume a lot of extra memory.

Microsoft Azure Web Role instances also recycle quite frequently for maintenance and patching. When this happens, all page outputs are lost and you’ll have to re-execute all pages to re-populate your page Output Cache, which is a negative performance impact on your Azure application.

How to Resolve Output Caching Problems in Microsoft Azure?

One way you can resolve all these issues in Microsoft Azure is to use a distributed cache, which runs out-of-process and is a common store for all Microsoft Azure Web Role instances. ASP.NET 4.0 has introduced an extensibility point that helps developers to use any distributed cache of their choice as their ASP.NET Output Cache store.

Distributed cache is shared by all Microsoft Azure Web Roles for page outputs so there are no redundant copies made within individual web role instances. Microsoft Azure Web Roles become purely stateless so data is never lost when Web Roles are recycled. You can cache a huge amount of data in distributed cache by pooling memory resources of all cache servers together. Moreover, distributed cache reduces load on your database because you don’t have to go through page executions involving database calls in each Microsoft Azure Web Role instance separately.

NCache for Azure is an in-memory distributed cache for .NET applications deployed in Microsoft Azure cloud. NCache for Azure has implemented ASP.NET Output Cache provider which you can use to store ASP.NET page output and resolve all above mentioned issues. Additionally, deploying NCache as a Azure caching service provides data reliability with replication as well as improves application scalability.

How to use NCache for Azure ASP.NET Output Cache Provider

You can use NCache for Azure for output caching in ASP.NET as it follows without any code change to your Microsoft Azure application.

Step 1: Add Reference of NCache for Azure Output Cache provider assembly.

File: web.config

<compilation debug="true "targetFramework="4.0">
        <add assembly= "Alachisoft.NCache.OutputCache,Version=x.x.x.x,Culture=neutral"/>

Step 2: Register NCache for Azure Output Cache Provider under <configuration> section and provide cache settings.

File: web.config

    <outputCache defaultProvider ="NOutputCacheProvider" />
            <add name="NOutputCacheProvider" type="NCOutputCache.NOutputCacheProvider"
            exceptionsEnabled="true" enableLogs="false" cacheName="mypartitionofReplicaCache"/>

Step 3: Add ASP.NET Output Cache directive on the page that you want to cache. 


Documentation: Using ASP.NET Output Caching with NCache

NCache for Azure ASP.NET Output Cache Features

NCache for Azure provides a rich set of features for caching and managing Output Caching of Microsoft Azure. Below is a list of them:

  1. Specify duration for Page Output: NCache for Azure allows you to specify a duration for which you want to cache ASP.NET page output.
  2. Cache different versions of a page: NCache for Azure allows you to cache different versions of page depending on the various ASP.NET Output Cache directives such as VaryByParam,VaryByCustom, VaryByControl. Another version of page output is stored in distributed cache if a different param is received for a page request.
  3. Cache different portions of a page: You can also specify only portions of the page instead of caching entire page. This is for situations where you cache only static portion of the page and leave the dynamic part which is rendered at runtime.
  4. Implement Custom Hooks for ASP.NET Output Cache: NCache for Azure allows you to implement and register your custom hooks (interface) for page output. This is to attach some extended attributes to your page outputs such as NCache for Azure database dependencies, Tags, Groups, etc.


 As you have seen, distributed cache allows you to cache ASP.NET page outputs, which resolves your application issues with multiple load balanced Azure Web Roles.  NCache is an Azure ASP.NET Output Cache provider which helps improve ASP.NET application performance scalability and reliability.

Download NCache Trial

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

Event Driven .NET and Java Data Sharing using In-Memory Distributed Cache

These days, many companies are running both .NET and Java applications in their enterprise environment.  Often these applications need to share data with each other at runtime. The most common way they do that today is by storing the data in the database and having the other application poll and look for it. Some people also develop web services solely for the purpose of allowing Java applications to obtain data from .NET applications and vice versa.

The problem with the first approach is that data sharing cannot happen instantaneously because the other “consumer” application has to poll the database, which happens after some predetermined interval. It also has performance and scalabilities issues like any application accessing the database for data. As you know, a database cannot scale the same way that today’s applications can. This is because although you can linearly scale an application tier by adding more application servers, you cannot do the same at the database tier.

The second approach requires a lot of custom programming and essentially changing your application’s architecture just so you can share data with other applications, whether they’re .NET or Java. It would be much nicer if you could continue to develop each application for the purpose that it is being built and not worry about creating a custom framework for data sharing.

Runtime Data Sharing through a Distributed Cache

The second approach requires a lot of custom programming and essentially changing your application’s architecture just so you can share data with other applications, whether they’re .NET or Java. It would be much nicer if you could continue to develop each application for the purpose that it is being built and not worry about creating a custom framework for data sharing.

Ideally, you would want to have an event driven model where a .NET application can be notified whenever a Java application has some data for it and vice versa. But, as you know, .NET and Java are not inherently compatible for this kind of use.

This is where a distributed cache like NCache comes in really handy. NCache provides events that are platform independent and can be shared between .NET and Java. NCache also provides binary level data type compatibility between .NET and Java. This allows you to not only receive events, but also corresponding data in the form of objects and all of that without having to go through any XML based transformation for data sharing purposes.

NCache event notification framework enables you to register to be notified when different types of events occur within the cache cluster. This way, whenever there are any changes made to the data, either by .NET or Java applications, your application gets notified. Here is sample code using NCache item-based event for data sharing in Java:

import com.alachisoft.ncache.web.caching.*;

public void AddToCache()
CacheEventListener onItemRemoved = new CacheEventListner();
Cache cache = NCache.initializeCache("PORCache");
Employee emp = new Employee();

CacheItem cItem = new CacheItem(emp);
cache.insert("EMP-1000-ENG", cItem);

public class CacheEventListner implements CacheItemRemovedCallback
  public void itemRemoved(String key, Object value,
  CacheItemRemovedReason reason)
Employee emp = (Employee) key;
System.out.println("Employee Removed " + key + "Dept" + emp.getDept());

NCache provides you different cached item level notifications like item-added, item-removed and item-updated. Applications can register interest in various cached item keys (that may or may not exist in the cache yet), and they’re notified separately whenever that item is added, updated or removed from the distributed cache by anybody for any reason. For example, even if an item is removed due to expiration or eviction, the item-remove event notification is fired.

Both .NET and Java applications can register interest for the same cached items and be notified about them. The notification includes the affected cached item as well, which is transformed into either .NET or Java, depending on the type of application.

Here is a sample code of using NCache item-based event for data sharing in .NET:

public void AddToCache()
Cache cache = NCache.InitializeCache("PORCache");
Employee emp = new Employee();
emp.Name = "David Rox";
emp.Dept = "Engineering";

cache.Insert("EMP-1000-ENG", emp, null,

//Register Callback to get notified of changes related to provided key
new CacheItemUpdatedCallback(OnItemUpdated),
void OnItemRemoved(string key, object value,CacheItemRemovedReason reason)
//Item is removed. Do something
Employee emp = (Employee) value;
	Console.WriteLine("Employee Removed {0}, Name {1}", key, emp.Dept);

In summary, with NCache you can not only share data between .NET and Java applications at runtime but can also use distributed events to notify applications of any change in data.

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

Download NCache Trial | NCache Details

Posted in data sharing, Data Sharing with Distributed Cache, Distributed Cache, Distributed caching, Distributed events, Event driven data sharing | Tagged , , | Leave a comment

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 transaction 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 , , | 2 Comments

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