title: How do I address sudden loss of connection to SQL Azure in my Azure role?
body: <p>My Azure role <a href="https://stackoverflow.com/q/5433567/57428">grabs stuff to process from a database</a> - it holds an instance of <code>System.Data.SqlClient.SqlConnection</code> and periodically creates an <code>SqlCommand</code> instance and executes an SQL query.</p>
  
  <p>Now once in a while (usually once in several days) running a query will trigger an <code>SqlException</code> exception</p>
  
  <blockquote>
    <p>The service has encountered an error processing your request. Please try again. Error code 40143.
    A severe error occurred on the current command.  The results, if any, should be discarded.</p>
  </blockquote>
  
  <p>Which I've already seen many times and now my code catches it, calls <code>Dispose()</code> on the <code>SqlConnection</code> instance and then reopens the connection and retries the query. The latter typically results in another <code>SqlException</code> exception</p>
  
  <blockquote>
    <p>Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.</p>
  </blockquote>
  
  <p>Which looks pretty much like SQL Azure server not responding or being unavailable for whatever reason.</p>
  
  <p>Currently my code doesn't catch the latter exception, it is propagated outside <code>RoleEntryPoint.Run()</code> and the role is restarted. Restart typically takes about ten minutes and once it completes the problem is gone for a day or so.</p>
  
  <p>I don't like my role restarting - it's takes a while and my service functionality is hindered. I'd like to do something smarter.</p>
  
  <p>What would be a strategy to address this problem? Should I retry the query several times and how many times and with what interval? Should I do something else? When do I give up and let the role just restart?</p>