Skip to main content

Outsource your caching with memcached

I'm currently working on a large business system for a client where there are several caching situations, because the service that delivers the data is too slow, the database is too slow or we don't want to hit the source for the data all too often. I've been hand rolling most of these cache layers myself. I don't like the idea of using ASP.NET caching for non ASP.NET applications.


Always when I hit the same problem the third time, I start looking for a common solution. When I was about to write my third caching implementation, I made a google search and found out that I probably should move the cache outside the application pool into a seperate service. Memcached is a service that I've heard of before, but I haven't really tried it out. Memcached is

  • a key/value store
  • hip and cool because it's NoSQL
  • available as a windows service from NorthScale with a simple .NET client API

How does it work?

Download and install the service from NorthScale. You'll get a user interface where you can analyze status of your cache service. Notice all the stuff about clustering which is cool, but probably only usable if you're Facebook or Twitter.

northscale ui

Before you start writing code you should create a bucket, where you want to store your data. If I understood this correctly, buckets are just there to separate one type of cached data from another type of cached data.

Your own project

Add references to the Enyim.Caching.dll and Northscale.Store.dll.

references tree in visual studio solution explorer

You will need to add configuration to tell NorthScaleClient where to find memcached service.

  <section name="northscale" type="NorthScale.Store.Configuration.NorthScaleClientSection, NorthScale.Store" />
  <servers bucket="default" userName="Administrator" password="password">
   <add uri="http://localhost:8080/pools/default" />
  <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:00:10" />

Now you can get and set data from the cache like this.

public string GetData(string key)
    // "memcached" is the configuration section name
    // "default" is the bucket name
    var cache = new NorthScaleClient("northscale", "default");

// Get data from key, returns null if key is not set in cache
var result = cache.Get&lt;string&gt;(key);
if (result == null)
    // Since cache did not exist, get from real source
    result = service.GetData();

    // Input data found to cache
    // Add result to cache (will not overwrite any value)
    // &quot;key&quot; - the key to store it under
    // &quot;result&quot; - the value to store
    // TimeSpan.FromDays(1) - let it expire in 24 hours
    cache.Store(StoreMode.Add, key, result, TimeSpan.FromDays(1));

return result;


Easy huh! Now, go out there and cache the world!

comments powered by Disqus