May 2006 - Posts

A Reluctant Cache Pattern

I have written an short article on a caching pattern that I use on dotnetkicks.com and which I call the 'Reluctant Cache' pattern (does anyone know if there is a formal name for this pattern?).

It allows items to be placed in the cache only once they have reached a threshold level of requests within a configurable time period. The result is that only the most frequently accessed data will be cached resulting in memory savings for your server.

   1:  public static List<Customer> GetCustomers() {
   2:      string cacheKey = "Customers";
   3:      int cacheDurationInSeconds = 5; //an artificially low number for demonstration
   4:   
   5:      object customers = HttpRuntime.Cache[cacheKey] as List<Customer>;
   6:   
   7:      if (customers == null) {
   8:          customers = CustomerDao.GetCustomers();
   9:   
  10:          if (new ReluctantCacheHelper(cacheKey, cacheDurationInSeconds, 2).ThresholdHasBeenReached) {
  11:              HttpRuntime.Cache.Insert(cacheKey, customers, null, DateTime.Now.AddSeconds(cacheDurationInSeconds), System.Web.Caching.Cache.NoSlidingExpiration);
  12:          }
  13:      }
  14:   
  15:      return (List<Customer>)customers;
  16:  }

As you can see, it only adds one extra line to our cache helper class. The ReluctantCacheHelper class keeps a count of any requests for a particular item over a period of time. If this request count reaches a configurable threshold, it inserts the item into the cache.

A simple demonstration of this illustrates the point. If the list of customers are requested more than once in a five second period, they are placed in the cache. Source code is also available.

on dotnetkicks.com


Posted by gavinjoyce | with no comments

Add a dotnetkicks.com kick counter to your blog posts

I have just added a new counter feature to dotnetkicks.com which allows you to include a dynamic kick counter in your blog posts.

Here is the live counter for this post:



To add one to your .NET related posts, just insert the following HTML, replacing the two [URL] parameters with the URL of your post:

<a href="http://www.dotnetkicks.com/kick/?url=[URL]"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=[URL]" border="0" /></a>


More Posts