title: Azure Cache intermittent response times from WCF REST service
body: <p>I'm building an EF6 web app in Azure and I'm using Azure Cache.
  I'm testing calls to my WCF service and I'm getting wildly erratic response times - between 300ms and 15sec!</p>
  
  <p>I configured my code according to the <a href="http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-service/#create-cache-object" rel="nofollow noreferrer">this example</a> and it runs fine locally </p>
  
  <p>I've debugged remotely and I can see that the cache key is being found and the data is getting called from cache, so I'm struggling to understand why there is sych a huge variation in response times. Most of the time it's 5+sec which is obviously waaay too long.</p>
  
  <p><strong>The example I've been testing is as follows:</strong></p>
  
  <p>WCF service GET request to: 
  <a href="http://feniksdev-staging.azurewebsites.net/EkckoNewsService.svc/getFriends" rel="nofollow noreferrer">http://feniksdev-staging.azurewebsites.net/EkckoNewsService.svc/getFriends</a></p>
  
  <pre><code>       // Cache client configured by settings in application configuration file.
          public DataCacheFactory cacheFactory = new DataCacheFactory();
          public DataCache _cache;
          public DataCache cache
          {
              get 
              {
                  if (_cache == null)
                      _cache = cacheFactory.GetDefaultCache();
  
                  return _cache;
              }
              set { }
          } 
  ...
  ...
  
  [OperationContract]
      [System.ServiceModel.Web.WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getFriends")]
      public string getFriends()
      {
          string cachekey = "getFriends/{" + user.Id + "}";
          object result = cache.Get(cachekey);
          if (result == null)
          {
              using (EkckoContext entities = new EkckoContext())
              {
                  var frnds = entities.UserConnections.Where(uc =&gt; uc.UserId == user.Id).Select(uc =&gt; new { Name = uc.Friend.Username }).ToList();
                  JsonSerializerSettings jsonSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };
                  string json = JsonConvert.SerializeObject(frnds, jsonSettings);
                  cache.Add(cachekey, json);
                  return json;
              }
          }
          else
          {
              return (string)result;
          }
      }
  </code></pre>
  
  <p>UserConnection is a simple table in my db and currently has no data, so the call returns an empty JSON array. <code>user</code> is a Session object and currently defaults to 1 for <code>user.Id</code></p>
  
  <p>When remote-debugging this, the object is found in cache and the cached object is returned. So all good, except the response time still varies by a factor of 20 (300ms - 6sec).</p>
  
  <p>When remote debugging one of the other web service methods, I got the following error when attempting to access the cached object using the corresponding key (<code>object result = cache.Get(cachekey);</code>):</p>
  
  <blockquote>
    <p>{"ErrorCode:SubStatus:There is a temporary failure. Please retry later. (One or more specified cache servers are unavailable, which could be caused by busy network or servers. For on-premises cache clusters, also verify the following conditions. Ensure that security permission has been granted for this client account, and check that the AppFabric Caching Service is allowed through the firewall on all cache hosts. Also the MaxBufferSize on the server must be greater than or equal to the serialized object size sent from the client.). Additional Information : The client was trying to communicate with the server: net.tcp://ekckodev.cache.windows.net:22238."}</p>
  </blockquote>
  
  <p>I then set the maxBufferSize in my config as follows:</p>
  
  <pre><code>    &lt;configSections&gt;
  &lt;section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" /&gt;
      &lt;section name="cacheDiagnostics" type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon" allowLocation="true" allowDefinition="Everywhere" /&gt;
  &lt;/configSections&gt;
  ...
  ...
  &lt;system.web&gt;
  ...
  ...
  &lt;caching&gt;
        &lt;outputCache defaultProvider="AFCacheOutputCacheProvider"&gt;
          &lt;providers&gt;
            &lt;add name="AFCacheOutputCacheProvider" type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheOutputCache" /&gt;
          &lt;/providers&gt;
        &lt;/outputCache&gt;
      &lt;/caching&gt;
  &lt;/system.web&gt;
      ....
      ....
      ...
        &lt;dataCacheClients&gt;
          &lt;dataCacheClient name="default"&gt;
            &lt;autoDiscover isEnabled="true" identifier="ekckodev.cache.windows.net" /&gt;
            &lt;localCache  isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" /&gt;
            &lt;securityProperties mode="Message" sslEnabled="false"&gt;
              &lt;messageSecurity authorizationInfo="xxxxxxxxxxxxxxxxxxxxxxx" /&gt;
            &lt;/securityProperties&gt;
            &lt;transportProperties connectionBufferSize="131072" maxBufferPoolSize="268435456"
                                 maxBufferSize="8388608" maxOutputDelay="2" channelInitializationTimeout="60000"
                                 receiveTimeout="600000"/&gt;
          &lt;/dataCacheClient&gt;
        &lt;/dataCacheClients&gt;
  </code></pre>
  
  <p>But I still get such erratic response times - particularly when hitting the same service call repeatedly.</p>
  
  <p>After adding the maxbuffersize config, the cache calls are still hit-and-miss. some fetch the object; other times I get the same exception, however the port is different </p>
  
  <blockquote>
    <p>"... The client was trying to communicate with the server: net.tcp://ekckodev.cache.windows.net:22233."}"</p>
  </blockquote>
  
  <p>Could this be a firewall issue? If so, how do I open the appropriate ports?</p>
  
  <p>I also just got the following exception when instantiating the DataCache object:</p>
  
  <p><code>_cache = cacheFactory.GetDefaultCache();</code></p>
  
  <blockquote>
    <p>ErrorCode:SubStatus:There is a temporary failure. Please retry later. 
    (One or more specified cache servers are unavailable, which could be caused by busy network or servers. 
    For on-premises cache clusters, also verify the following conditions. Ensure that security permission has 
    been granted for this client account, and check that the AppFabric Caching Service is allowed through the 
    firewall on all cache hosts. Also the MaxBufferSize on the server must be greater than or equal to the 
    serialized object size sent from the client.)</p>
  </blockquote>
  
  <p>Any thoughts on why I'm getting such results? it's certainly no quicker WITH the cache than WIHTOUT it, so it appears there is some sort of latency in the cache which doesn't seem right...</p>
  
  <p>Thanks in advance for any help!</p>
  
  <p><strong>UPDATE</strong>:
  After doing some more searching, it seems I'm not the only one with this issue:
  <a href="https://stackoverflow.com/questions/8754964/poor-performance-with-azure-cache">poor performance with azure cache</a></p>
  
  <p>I find it hard to believe that this is the performance I should expect</p>
  
  <p><strong>UPDATE 2</strong>
  I have commented out all cache-related code from my service and ran the same tests again. The response times are appreciably lower WITHOUT the cache! the "getFriends" callaverages about 250ms wihtout the cache, but peaks at over 5sec WITH the cache.
  My other method that fetches about 4kb of data, was peaking at 20+ seconds with cache and now averages about 2sec WITHOUT the cache.</p>
  
  <p>Again: I find it hard to believe that this is the performance I should expect</p>
  
  <p><strong>UPDATE 3</strong>
  I have now scrapped Azure Cache in favour of MemoryCache. Nice example <a href="http://pieterderycke.wordpress.com/2012/04/09/caching-in-wcf-services-part-1/" rel="nofollow noreferrer">here</a>
  My service calls are now consistently taking approx 300ms in the browser.</p>
  
  <p>I've opened a ticket with Microsoft Azure support regarding Azure Cache, so I'll update this post when they get in touch and I've asked them why their cache is so rubbish. Just when my faith in Microsoft was climbing :/</p>