Search code examples
c#asp.netasp.net-web-apimemorycache

Caching strategy for Web API


I am developing a small blog application using the following technologies:

  1. ASP.NET Web API for the back-end.
  2. HTML, CSS and JavaScript (KnockoutJS specifically)

Internally i use the MemoryCache class. Let's say i want to give the users the ability to add/edit/remove blog posts. Is it a good practise to save a JSON containing all blog posts from the database to the cache? In a real-world scenario there will be a significant amout of posts so the serialization/deserialization of cache may become an expensive operation. Also what is the best way to support pagination for these items? Thank you in advance for your help.


Solution

  • There is more than one way to cache Web API results.

    1- HTTP Caching, this is where you set the cache on the HTTP level, the browser or Ajax requests will cache the output of the REST calls and will not request it from the server, there are some libraries to handle this, ex: CacheCow.Server, see this link for more details http://www.hanselman.com/blog/NuGetPackageOfTheWeekASPNETWebAPICachingWithCacheCowAndCacheOutput.aspx

    2- Output/Response Caching, this will be stored in the server memory, the request will be received by the server and the results will be returned immediately from the server memory without executing the action method, see this link for more details https://docs.asp.net/en/latest/performance/caching/response.html

    3- Server Side Caching, this is the method you are using, where you cache the data, and your data should be classified as Reference[not changed], Activity[per user] and Shared [between users] data

    You are using a MemoryCache object to cache the results which is a good option, but I suggest you have a look at RedisCache as it provides more capabilities and will excel if you have a web farm as it is a distributed cache solution, see this link for more details https://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/