Explanation of NHibernate HiLo

前端 未结 4 1104
暖寄归人
暖寄归人 2020-12-23 16:50

I\'m struggling to get my head round how the HiLo generator works in NHibernate. I\'ve read the explanation here which made things a little clearer.

My understanding

4条回答
  •  梦毁少年i
    2020-12-23 17:38

    For those wondering how to choose a good max_lo value, the trade-off is essentially between:

    • Frequency with which you need to query a new hi value from the db.
    • Maximum amount of unique numbers you actually can generate.

    A lower max_lo will make sure there is no "waste" of id's, which in turn governs the moment at which you will hit the implicit limit of your datatype (which will likely be int). The price you pay is that each client needs to query and increase the hi value more frequently.

    A higher max_lo is useful to reduce the frequency of queries that get and increment hi, but result in more waste.

    The metrics you need to take into account to determine the optimal value are:

    • Frequency at which new entities are created and need an ID
    • Frequency at which the application restarts / gets recycled (anything that results in a new NHibernate SessionFactory)

    Let's consider a web application that is hosted in IIS and is recycled every 24 hours. The entities are Customer and Order.

    Now lets assume:

    • 10000 new Orders per 24 hours
    • 10 new customers per 24 hours

    Then the perfect max_lo is 10000 for Orders and 10 for Customers. Of course, in the real world you can never determine it so precicely and clearly, but you should get the idea here!

    Now let's consider different scenario where we pick totally wrong (ridiculous) max_lo's:

    • Suppose a 10 customers are making orders simultaneously every second, with a max_lo of only 10 on orders, every second there is a superfluous database call to increment hi.
    • Suppose your app is a desktop app and is installed on 50 clients (support staff?), that each start it about twice a day. Together they create about 100 helpdesk tickets a day. Now let's say we stick with the max_lo default of 32767. Hi is incremented 100 times a day (50 clients * 2), which means you will hit the maximum value of int in less than 2 years, should you have forgotten the important fact that hi gets incremented so frequently. A good max_lo here would be (100 tickets / 50 clients) = only 2.

    Hopes this helps with conceptualizing the HiLo algorithm and its implications in general, while also giving you the maths to actually stick a number on max_lo.

提交回复
热议问题