Using Memcached cache from your C# application

In the application I’m currently working on there’s a lot of data like translations and page styling coming from the database. Altogether this is quite a lot of data being retrieved to render just a single page. This data however doesn’t change a lot so caching the calculated objects would mean better performance and far less requests on our api and database. In this blog I’ll explain how we’re using Memcached to solve this problem. The full demo application can be found on my GitHub page.

ASP.Net internal cache

Our application has been written using ASP.Net MVC and WebApi and our landscape consists of multiple services running on even more machines. There is a cache object build into the framework that you could use. The cache object is only ideal for applications hosted in a single server environment. First of all, an instance of the cache class is created on a per-AppDomain basis and remains valid until that AppDomain is up and running so it’s gone when the app restarts. Furthermore this cache is also not shared between machines in our webfarm meaning all servers still have to retrieve all the data for themselves.

Using an out-of-process and distributed cache then seems ideal since multiple servers and even multiple applications could make use of the same cache as long as they share the key definitions. Using a cache outside of gives us another advantage; the application reading most of the data is not the same as the application modifying most of the data. Using a distributed cache while sharing the keys between these applications lets us update the cache without having to notify the other applications of this change. Something that would have been quite harder using build in caching.

Memcached to the rescue

After searching for software that would meet our requirements we found Memcached is perfectly described at this wiki page so I’m not going into those details.

I’m using this library to do most of the hard work for me. Using that library, I wrote the following implementation. All throughout our application I’m using the GetOrSet function. It will try to get the data from the cache but when it cannot find the item it will execute the supplied action and store and return that outcome. Creating a new connection every time you are calling your Memcached it quite expensive so make site that you create a singleton of this class per app-domain. I’m doing this through a singleton DI registration.

You may also like...