title: Explanation of NHibernate HiLo
body: <p>I'm struggling to get my head round how the HiLo generator works in NHibernate. I've read the explanation <a href="https://stackoverflow.com/questions/282099/whats-the-hi-lo-algorithm">here</a> which made things a little clearer.</p>
  
  <p>My understanding is that each SessionFactory retrieves the high value from the database. This improves performance because we have access to IDs without hitting the database.</p>
  
  <p>The explanation from the above link also states:</p>
  
  <blockquote>
    <p>For instance, supposing you have a "high" sequence with a current value of 35, and the "low" number is in the range 0-1023. Then the client can increment the sequence to 36 (for other clients to be able to generate keys while it's using 35) and know that keys 35/0, 35/1, 35/2, 35/3... 35/1023 are all available.</p>
  </blockquote>
  
  <p>How does this work in a web application as don't I only have one SessionFactory and therefore one hi value. Does this mean that in a disconnected application you can end up with duplicate (low) ids in your entity table?</p>
  
  <p>In my tests I used these settings:</p>
  
  <pre><code>&lt;id name="Id" unsaved-value="0"&gt;
    &lt;generator class="hilo"/&gt;
  &lt;/id&gt;
  </code></pre>
  
  <p>I ran a test to save 100 objects. The IDs in my table went from 32768 - 32868. The next hi value was incremented to 2. Then I ran my test again and the Ids were in the range 65536 - 65636.</p>
  
  <p>First off, why start at 32768 and not 1, and secondly why the jump from 32868 to 65536? </p>
  
  <p>Now I know that my surrogate keys shouldn't have any meaning but we do use them in our application. Why can't I just have them increment nicely like a SQL Server identity field would.</p>
  
  <p>Finally can someone give me an explanation of how the max_lo parameter works? Is this the maximum number of low values (entity ids in my head) that can be created against the high value?</p>
  
  <p>This is one topic in NHibernate that I have struggled to find documentation for. I read the entire NHibernate in action book and it still doesn't go into how this works in any detail.</p>
  
  <p>Thanks
  Ben</p>