title: Solution for Generate next sequence number in race condition
body: <p>I am facing the issue of generating a next sequence number (kind of invoice number). The Requirement are <br></p>
  
  <ol>
  <li><p>There is no duplicate number.</p></li>
  <li><p>There is no gap between those numbers.</p></li>
  </ol>
  
  <p>The normal approach is </p>
  
  <pre><code> 1. Find the last number 
   2. Increase value 
   3. Insert new number
  </code></pre>
  
  <p>When we have multiple request at the same time, the 3rd step of First Request could be not yet complete and the First step of Second Request has been started. and it lead to duplicate numbers.<br>
  There are some solutions for it <br><br>
   <strong>1. Using transaction and lock</strong>. <br>
  Bad thing about it is there is a waiting there and it slow the app. Moreover, we have more than 1 databases involve, that make us have to enable DTC in all DB servers and app server. <br><br>
  <strong>2. Using Pre-Generate number and Azure Queue Storage</strong> <br>
   1. PreCreated a queue that contain a list of number that you gonna
      use <br>
   2. Pop out a last number. Return the number back to the queue incase there is an exception in using it. Do nothing if nothing happen <br>
   3. Auto push in number every mid night (or every hour) <br>
   4. Manual function trigger inserting number if it's run out of value <br></p>
  
  <p><strong>My Question is: Which way is better and is there any other solutions for this kind of problem.</strong></p>
  
  <p><strong>UPDATING:</strong>
  <br/> The 2nd Way bring the potential error: duplicate request (at the same time, like user double click) will create 2 invoices which is not what we want.
  <br/>In the end, we use Distributed Lock and dont care about transaction using <a href="https://github.com/madelson/DistributedLock" rel="nofollow noreferrer">DistributedLock</a> library </p>