Thursday, April 28, 2011

ASP.NET Data Cache - preserve contents after app domain restart

I am using ASP.NET's data caching API. For example:

HttpRuntime.Cache.Insert(my_data, my_key);

Is there any way to configure cache so its contents are preserved when the App Domain recycles?

I load many object into cache, but there is a substantial delay re-loading these every time the app domain restarts. Assume for this question that I can't prevent the appdomain restart due to a server configuration.

From stackoverflow
  • Recycling the appdomain dumps the cache. If you want to get around this you'd need to use a distributed cache. Here's an example.

  • For your most expensive data you can cache the objects with a distributed cache such as Memcached or velocity. Depending on the size of the object and the length of runtime you could also serialize it to disk or to your database provided that the access speed to these resources is less than the time to create the object.

    Now since the in-proc cache is super fast compared to any other solution since it just holds a reference to the memory object you will want to use it where possible. You can keep a copy of your cached object on disk until it is lost and then re-create it from that and place it in memory. Where this is tricky is when you have to expire the data so only use the cache/disk/sql combo where you won't need to expire/invalidate the data otherwise you will need to ensure that you clear both. This will also get around not being able to implement distributed caching on a shared server for example.

  • Is there any way to configure cache so its contents are preserved when the App Domain recycles?

    No. The Cache object holds references in RAM. Period.


    1. Out-of-process Session state (although that's per-user)
    2. Distributed cache
    3. Use SQL Server as a cache (where it keeps data in memory, rather than on disk)
    4. Write the objects to disk at the web tier

    I generally prefer #3 myself, although there are scenarios where the others are appropriate.

    frankadelic : The Cache API can't be configured to persists to SQL Server though, right? I would need to modify my current Cache API calls to go through another API.
    RickNZ : Correct. The Cache API works for in-memory references only; there aren't any options to make the entries persistent. The reason is that persistence requires serialization in some form, which is expensive. One of common uses of the Cache API, in fact, is specifically to avoid serialization and the related overhead. However, if your data originated from SQL Server, then you don't need to persist it again yourself; you just need to be notified if it changes, which is what SqlDependency is all about.


Post a Comment