May 27th 2008 05:33 pm

Time based Caching in a Load Balanced ASP.Net Application

When using the asp.net application cache a common problem occurs when the application scales from a single web server to a web farm. This problem and more are more broadly discussed here.

One common approach to keep cache items in sync across web servers is use of file dependencies on a central file server. When a depenency file is modified, all web servers in the farm remove the dependent items from their cache.

This works well until one tries to cache an item for a specified duration without a specific file dependency. Consider a web site that shows “recent blog posts”. The list may be constantly changing and although some latency of the data is allowed(hence the caching), the data must always be consistent no matter which web server serves the response.

We can use the same file dependency strategy to keep the cache items in sync between web servers. The “trick” is to produce a hash of the data to be cached and include that information when synchronizing the servers.

If a web server receives a request and does not have the data in its application cache, it must retrieve it.  The server then compares a hash of the data against the contents of a dependency file (unique to that cache item) accessible to all web servers. If the contents of the file are different than the hash generated, the latest results retrieved for the cache item do not match the cache items on other web servers. By replacing the contents of the cache item dependency file with the value of the new hash we can guarantee that the cache items on other web servers will be invalidated and removed.

A sample project demonstrating this is here.

 

No Comments yet »

Trackback URI | Comments RSS

Leave a Reply

« Class Table Inheritance: An Investigation into SQL Performance | Optimize UpdatePanel performance by avoiding unnecessary element disposal »