Your official information source from the .NET Web Development and Tools group at Microsoft.
Warning. This is obsolete, see my new blog
Warning: Most of the information in this blog is for the Preview edition and should not be used or targeted for production code. Use the In-Role Cache for production code.
In this blog post I’ll take my MVC Movie app and in 15 minutes connect it to the preview Windows Azure Cache service. The image below shows the details of a movie along with timing data (1.4 milliseconds), cache status (Hit in this case) and the PID of the IIS server.
You can download the completed app here. Later in the tutorial we’ll use the PID to show the session cache preserves data across web site failovers.
Select the Configure tab for Cache in the Management Portal. Each cache has a default named cache, and the Standard and Premium cache offerings support up to nine additional named caches, for a total of ten. Each named cache has its own set of options which allow you to configure your cache in a highly flexible manner.
In the image below, the default cache is configured for a one minute sliding policy.
Each time a cache item is accessed, the expiration clock is reset. Setting it to one minute makes it easy to test the app. In the download example, each page shows the cache Hit or Miss status, so setting it to one minute makes it easy to show expirations. Cache aside algorithms generally use a sliding cache. You should configure the expiration for the longest period possible that doesn’t overflow the cache and force excessive evictions. When the cache memory is full, new additions to the cache force evictions of the oldest items in the cache (LRU), and you pay a minor penalty waiting to evict the oldest cache items to make room for the new items. You can stress test your app and use the Monitor tab to see what percent of the cache capacity the app is using. (Monitoring is shown later in the tutorial.)
There are many cache approaches you can take depending on your application needs. For this sample I’ll use the on demand/cache aside approach. Each query for a movie or list of movies first searches the cache. If the data is found in the cache, it’s immediately returned without banging on the database. If the requested data is not in the cache, it uses the normal data access code, but then caches the data for the next time that data is requested. The following shows the getMovie method which is called by the Details, Edit and Delete action methods.
public class MoviesController : Controller
private MovieDBContext db = new MovieDBContext();
private DataCache cache = new DataCache();
Movie getMovie(int id)
Stopwatch sw = Stopwatch.StartNew();
Movie m = (Movie)cache.Get(id.ToString());
if (m == null)
Movie movie = db.Movies.Find(id);
When a movie is edited or deleted, it is evicted from the cache:
void ClearAllMoviesCache(int id = 0)
if (id > 0)
Note the code above also clear out the cache entry “All Movies”, which contains a list of all the movies and is used in the Index method.
Download and configure the sample using the instructions above. You must create a web site with a database. For instructions on deploying a web site with a database, see my tutorial Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to a Windows Azure Web Site.
The app is configured to display timing and cache status on each page.
In the root Web.config file, find the <localCache> element and remove the comment characters. Local Cache, an ultra-fast second level cache stores cached items locally (in the memory of your web site or cloud service instance so there are no network hops or deserialization costs). Local Cache is hundreds of times faster than the cache service, reducing latency to the .01 millisecond range. Local Cache is not synchronized with the cache, so it shouldn't be used where you need exact data values. However you can register for notifications to update the local cache at regular intervals from the cache cluster. Deploy the updated application and you will notice cache hits are now in the .01 millisecond range.
From the portal, click on a cache endpoint, then click Monitor. The image below shows the cache usage data over the last hour. Note the read/write requests per second are in units of a 1,000.
Click the Add Metrics button on the bottom of the portal page to add additional metrics.
While it’s considered a best practice is to avoid using session state, some applications can actually have a performance/complexity benefit from using some session data, and other apps require session state. The default in memory provider for session state does not allow scale out (running multiple instances of the web site). The ASP.NET SQL Server session state provider will allow multiple web sites to use session state, but it incurs a high latency cost compared to an in memory provider. The ASP.NET session state cache provider is a low latency alternative that is very easy to configure and set up. If your app uses only a limited amount of session state, you can use most of the cache for caching data and a small amount for session state.
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<!-- Windows Azure Cache session state provider -->
<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
<add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
<!-- Windows Azure Cache output cache provider --><!--Uncomment this section to use Windows Azure Cache for output cache-->
<add name="AFCacheOutputCacheProvider" type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheOutputCache" />
The sample download provides an easy mechanism to test session state is preserved on web site fail over. Run the download sample an click the Write Session button. You can optionally add route data to the session in the URL, such as Movies/WriteSession/MyTestSessionData.
Click on the Read Session tab to read the session data. Now stop and restart the web site. (You can do this from the portal or from Visual Studio). Refresh the page or click the Read Session tab and you’ll see the PID has changed.
See Session State Provider for more details. Erez Benari has a great blog on Disabling ARR’s Instance Affinity in Windows Azure Web Sites to allow you to use session state with multiple web sites, but with that approach, when a web site or host is updated, the load balancer sends subsequent requests to a new web site and all session data will be lost. If you app doesn’t use much session state and you’re using the already using the cache, you can get reliable and fast session state for practically free with the cache Session State Provider.
<dataCacheClient name="default" isCompressionEnabled="true">
Follow me ( @RickAndMSFT ) on twitter where I have a no spam guarantee of quality tweets.
Windows Azure Cache Extension Library WACEL implements high-level data structures that can be shared among your services and application. You can use WACEL data structures just as if you were using local data structures such as arrays, tables, circular buffers and OLAP cubes, and these data structures are backed by Windows Azure Cache, Windows Azure Table Storage, or both.
Microsoft Patterns and Practices - Windows Azure Guidance. See Caching guidance and Cache-Aside pattern.
This would be even better baked directly into the Entity Framework. ;)
@shawn baked directly into EF.
I'll let the EF folks know you'd like a SqlDependency like feature using this cache. Thanks for the feedback.
Is there a known performance ceiling when you have large object sizes?
I tried using the Cache Service with an object that was 2.5Mb and performance was terrible, sometimes taking up to 4 seconds to return. I had to use Table Storage instead!
Hi Dear Friend
From Iran we cant Reach and sign up in Azure because Our country name is not in the optional list to get verify phone code and send it back to confirmation.
pleade help how can we sign up for Azure ?
Thanks Dear Friend
and really thanks for sharing these great and useful tut
I need an azure account but I can't buy it from Our Country Iran .
my country name is not in the sign-up list to get and and send to verify my account . do you know any way else to help me ?
if you know please help me to buy one year or more account for my website to test it .
my email address is : "firstname.lastname@example.org"
with the best Regard :