| 1 | <!doctype html> |
| 2 | <notebook theme="air"> |
| 3 | <title>H2Histogram: Base-2 Redesign of HdrHistogram for Unbeatable Performance</title> |
| 4 | |
| 5 | <script type="text/html"> |
| 6 | <style> |
| 7 | :root { --max-width: 1100px; } |
| 8 | p, h1, h2, h3, h4, h5, h6, table, figure, figcaption, .katex-display { max-width: 760px; } |
| 9 | blockquote, ul, ol { max-width: 720px; } |
| 10 | </style> |
| 11 | </script> |
| 12 | |
| 13 | <script type="text/markdown"> |
| 14 | # H2Histogram: Base-2 Redesign of HdrHistogram for Unbeatable Performance |
| 15 | |
| 16 | The H2Histogram provides a histogram that is conceptually similar to |
| 17 | [HdrHistogram](http://www.hdrhistogram.org/), with modifications to the |
| 18 | bucket construction algorithm and configurable options. |
| 19 | |
| 20 | ## Background and Assumptions |
| 21 | |
| 22 | ### Background |
| 23 | |
| 24 | Recording and reporting quantile metrics is a very common task, and highly |
| 25 | valuable in characterizing workload and performance. Usually, system |
| 26 | input/output and behavior have a wide but bounded range of acceptable |
| 27 | values, and tracking the distribution within this range at a certain |
| 28 | precision provides rich insights into the workload. In high-throughput |
| 29 | scenarios, HdrHistogram is highly popular due to its low recording |
| 30 | overhead. However, HdrHistogram is a base-10 design. We believe a base-2 |
| 31 | variant works even better in terms of speed, simplicity, and |
| 32 | configurability. |
| 33 | |
| 34 | ### Assumptions |
| 35 | |
| 36 | Below are our core assumptions: |
| 37 | |
| 38 | 1. Bucket widths are powers of 2, and monotonically increasing for larger values |
| 39 | 2. We want to accept any natural number up to the maximum value allowed |
| 40 | 3. Using relative error as a constraint, the goal is to primarily maximize |
| 41 | recording throughput and secondarily minimize memory space |
| 42 | |
| 43 | ### Goals |
| 44 | |
| 45 | H2Histogram aims to provide a simpler implementation, finer-grain |
| 46 | configuration, and more efficient runtime compared to the reference |
| 47 | implementation provided by HdrHistogram. |
| 48 | |
| 49 | ## Basic Parameters |
| 50 | |
| 51 | **Maximum value in histogram**: ${tex.block`N = 2^n - 1`} |
| 52 | |
| 53 | This is the largest value the histogram can track, parameterized by the |
| 54 | exponent ${tex`n`}. |
| 55 | </script> |
| 56 | |
| 57 | <script type="module"> |
| 58 | const n = view(Inputs.range([8, 64], { value: 64, step: 1, label: tex`n` })); |
| 59 | </script> |
| 60 | |
| 61 | <script type="module"> |
| 62 | const N = (1n << BigInt(n)) - 1n; |
| 63 | </script> |
| 64 | |
| 65 | <script type="text/markdown"> |
| 66 | For ${tex`n = ${n}`}, ${tex`N`} = ${N.toString()}. |
| 67 | |
| 68 | **Relative error**: ${tex.block`e = 2^{-p}`} |
| 69 | |
| 70 | This is the upper bound on the relative error created by value |
| 71 | quantization, parameterized by the exponent (of its inverse), ${tex`p`}. |
| 72 | </script> |
| 73 | |
| 74 | <script type="module"> |
| 75 | const p = view(Inputs.range([2, 22], { value: 10, step: 1, label: tex`p` })); |
| 76 | </script> |
| 77 | |
| 78 | <script type="module"> |
| 79 | const e = 1 / 2 ** p; |
| 80 | </script> |
| 81 | |
| 82 | <script type="text/markdown"> |
| 83 | For ${tex`p = ${p}`}, ${tex`e = ${e.toPrecision(3)}`}. |
| 84 | |
| 85 | **Note**: the concept of relative error does not apply when the exact |
| 86 | integer value is recorded. |
| 87 | |
| 88 | ## Bucket Construction |
| 89 | |
| 90 | We use a bucket width of just 1 for small integers. As the absolute value |
| 91 | goes up, we can double the bucket width without violating the relative |
| 92 | error constraint, ${tex`e`}. |
| 93 | |
| 94 | The smallest value that allows bucket width to go from ${tex`1`} |
| 95 | (${tex`2^0`}) to ${tex`2`} (${tex`2^1`}) is ${tex`\frac{2}{e}`} (or ${tex`2^{p+1}`}). For ${tex`p = ${p}`}, that value is ${2 ** p * 2}. This means there are ${tex`2^{p+1}`} precise buckets. |
| 96 | |
| 97 | Bucket width can be doubled from ${tex`2`} (${tex`2^1`}) to ${tex`4`} |
| 98 | (${tex`2^2`}) for values greater than or equal to ${tex`\frac{4}{e}`} (or ${tex`2^{p+2}`}). For ${tex`p = ${p}`}, that value is ${2 ** p * 4}. |
| 99 | This also means there are ${tex`2^p`} buckets of width 2. |
| 100 | |
| 101 | So on and so forth, until the threshold value reaches the maximum value ${tex`N`}. At that point, there will be ${tex`(n - p)`} **groups** of |
| 102 | buckets of doubling widths. For ${tex`n = ${n}`} and ${tex`p = ${p}`}, |
| 103 | the number of groups is ${n - p}. |
| 104 | |
| 105 | **Note**: When ${tex`p = n - 1`}, the histogram will have the exact same |
| 106 | number of buckets as there are values. Notions of absolute and relative |
| 107 | errors do not apply in such a histogram. |
| 108 | |
| 109 | ### Bucket Summary |
| 110 | </script> |
| 111 | |
| 112 | <script type="module"> |
| 113 | const total_buckets = (1n << BigInt(p)) * BigInt(n - p + 1); |
| 114 | </script> |
| 115 | |
| 116 | <script type="text/markdown"> |
| 117 | - Total number of buckets: ${tex`(n - p + 1) \times 2^p`}. For ${tex`n = ${n}`} and ${tex`p = ${p}`}, that is **${total_buckets.toString()}** |
| 118 | buckets. |
| 119 | - Histogram size: number of buckets multiplied by counter size. For |
| 120 | ${tex`n = ${n}`} and ${tex`p = ${p}`}, that is |
| 121 | **${((total_buckets * 8n) / 1024n).toString()} KiB** (64-bit counters) |
| 122 | or **${((total_buckets * 4n) / 1024n).toString()} KiB** (32-bit |
| 123 | counters). |
| 124 | |
| 125 | The table below gives a sense of the total number of buckets and |
| 126 | histogram size for various ${tex`p`} values, assuming we want to record |
| 127 | values up to the maximum unsigned 64-bit integer. |
| 128 | |
| 129 | | p | relative error | #buckets | size (8-bit) | size (16-bit) | size (32-bit) | size (64-bit) | |
| 130 | |----|----------------|---------:|-------------:|--------------:|--------------:|--------------:| |
| 131 | | 2 | 25.0% | 252 | 0.2 KiB | 0.5 KiB | 1.0 KiB | 2.0 KiB | |
| 132 | | 3 | 12.5% | 496 | 0.5 KiB | 1.0 KiB | 1.9 KiB | 3.9 KiB | |
| 133 | | 4 | 6.25% | 976 | 1.0 KiB | 1.9 KiB | 3.8 KiB | 7.6 KiB | |
| 134 | | 5 | 3.13% | 1920 | 1.9 KiB | 3.8 KiB | 7.5 KiB | 15.0 KiB | |
| 135 | | 6 | 1.56% | 3776 | 3.7 KiB | 7.4 KiB | 14.8 KiB | 29.5 KiB | |
| 136 | | 7 | 0.781% | 7424 | 7.3 KiB | 14.5 KiB | 29.0 KiB | 58.0 KiB | |
| 137 | | 8 | 0.391% | 14592 | 14.3 KiB | 28.5 KiB | 57.0 KiB | 114.0 KiB | |
| 138 | | 9 | 0.195% | 28672 | 28.0 KiB | 56.0 KiB | 112.0 KiB | 224.0 KiB | |
| 139 | | 10 | 0.0977% | 56320 | 55.0 KiB | 110.0 KiB | 220.0 KiB | 440.0 KiB | |
| 140 | | 11 | 0.0488% | 110592 | 108.0 KiB | 216.0 KiB | 432.0 KiB | 864.0 KiB | |
| 141 | | 12 | 0.0244% | 217088 | 212.0 KiB | 424.0 KiB | 848.0 KiB | 1.7 MiB | |
| 142 | | 13 | 0.0122% | 425984 | 416.0 KiB | 832.0 KiB | 1.6 MiB | 3.3 MiB | |
| 143 | | 14 | 0.00610% | 835584 | 816.0 KiB | 1.6 MiB | 3.2 MiB | 6.4 MiB | |
| 144 | |
| 145 | If input values are 32-bit integers, which is also common, the histograms |
| 146 | are much smaller. |
| 147 | |
| 148 | | p | relative error | #buckets | size (8-bit) | size (16-bit) | size (32-bit) | size (64-bit) | |
| 149 | |----|----------------|---------:|-------------:|--------------:|--------------:|--------------:| |
| 150 | | 2 | 25.0% | 124 | 0.1 KiB | 0.2 KiB | 0.5 KiB | 1.0 KiB | |
| 151 | | 3 | 12.5% | 240 | 0.2 KiB | 0.5 KiB | 0.9 KiB | 1.9 KiB | |
| 152 | | 4 | 6.25% | 464 | 0.5 KiB | 0.9 KiB | 1.8 KiB | 3.6 KiB | |
| 153 | | 5 | 3.13% | 896 | 0.9 KiB | 1.8 KiB | 3.5 KiB | 7.0 KiB | |
| 154 | | 6 | 1.56% | 1728 | 1.7 KiB | 3.4 KiB | 6.8 KiB | 13.5 KiB | |
| 155 | | 7 | 0.781% | 3328 | 3.3 KiB | 6.5 KiB | 13.0 KiB | 26.0 KiB | |
| 156 | | 8 | 0.391% | 6400 | 6.3 KiB | 12.5 KiB | 25.0 KiB | 50.0 KiB | |
| 157 | | 9 | 0.195% | 12288 | 12.0 KiB | 24.0 KiB | 48.0 KiB | 96.0 KiB | |
| 158 | | 10 | 0.0977% | 23552 | 23.0 KiB | 46.0 KiB | 92.0 KiB | 184.0 KiB | |
| 159 | | 11 | 0.0488% | 45056 | 44.0 KiB | 88.0 KiB | 176.0 KiB | 352.0 KiB | |
| 160 | | 12 | 0.0244% | 86016 | 84.0 KiB | 168.0 KiB | 336.0 KiB | 672.0 KiB | |
| 161 | | 13 | 0.0122% | 163840 | 160.0 KiB | 320.0 KiB | 640.0 KiB | 1.3 MiB | |
| 162 | | 14 | 0.00610% | 311296 | 304.0 KiB | 608.0 KiB | 1.2 MiB | 2.4 MiB | |
| 163 | |
| 164 | ### Bucket Layout |
| 165 | </script> |
| 166 | |
| 167 | <script type="module"> |
| 168 | function compute_buckets(n, p) { |
| 169 | const groups = []; |
| 170 | let lower = 0n; |
| 171 | for (let w = 0; w + p < n; w++) { |
| 172 | const width = 1n << BigInt(w); |
| 173 | const upper = 1n << BigInt(p + w + 1); |
| 174 | groups.push({ |
| 175 | width: width.toString(), |
| 176 | lower: lower.toString(), |
| 177 | upper: upper.toString(), |
| 178 | buckets: ((upper - lower) / width).toString() |
| 179 | }); |
| 180 | lower = upper; |
| 181 | } |
| 182 | return groups; |
| 183 | } |
| 184 | </script> |
| 185 | |
| 186 | <script type="module"> |
| 187 | const buckets = compute_buckets(n, p); |
| 188 | </script> |
| 189 | |
| 190 | <script type="module"> |
| 191 | display(Inputs.table(buckets, { rows: 16, select: false })); |
| 192 | </script> |
| 193 | |
| 194 | <script type="text/markdown"> |
| 195 | ### Bucket Lookup |
| 196 | |
| 197 | Bucket lookup is the primary operation for recording a value. The |
| 198 | following algorithm only applies to positive integers (i.e. zero values |
| 199 | are not allowed). Support for the zero value is trivially added as a |
| 200 | first step of the lookup implementation. |
| 201 | |
| 202 | We represent the input value as an ${tex`n`}-digit binary: |
| 203 | ${tex.block`V = (a_{n-1}a_{n-2}\dots a_0)_2`} |
| 204 | |
| 205 | Looking up the right bucket offset ${tex`b`} for ${tex`V`} works as |
| 206 | follows: |
| 207 | |
| 208 | 1. Find the highest non-zero digit ${tex`h`}. ${tex`h`} |
| 209 | (${tex`0 \le h \le n-1`}) is such that ${tex`a_h = 1`} but |
| 210 | ${tex`a_i = 0`} for all ${tex`i`} that satisfy ${tex`h < i < n`}. |
| 211 | 2. Calculate the bucket offset. If ${tex`h \le p`}, ${tex`V`} maps to a |
| 212 | precise bucket, so we simply have ${tex`b = V`}; otherwise, first |
| 213 | compute ${tex`w = h - p`}, and we can compute ${tex`b`} as |
| 214 | ${tex`(w + 1) \times 2^p + (V - 2^h) \gg w`}. |
| 215 | |
| 216 | #### Explanation |
| 217 | |
| 218 | In the above algorithm, the highest non-zero digit ${tex`h`} tells us the |
| 219 | width of the bucket that should record the input value ${tex`V`}. For ${tex`h \le p`} the bucket width is ${tex`2^0`}; for ${tex`h = p + 1`} |
| 220 | the bucket width is ${tex`2^1`}; etc. For any positive ${tex`w`}, the |
| 221 | total number of buckets with a width *less than* ${tex`2^w`} is ${tex`(w+1) \times 2^p`}. |
| 222 | |
| 223 | There are ${tex`2^p`} buckets of width ${tex`2^w`}, with a lower bound ${tex`2^h`} as the value. To find out which bucket in this group is the |
| 224 | right one for ${tex`V`}, we compute the distance between ${tex`V`} and |
| 225 | the lower bound, and divide that by the bucket width of the current |
| 226 | group. Since all bounds are powers of 2, the division is converted to a |
| 227 | bit shift. |
| 228 | |
| 229 | #### Optimization |
| 230 | |
| 231 | On CPUs supporting SSE4, ${tex`h`} can be most efficiently computed by |
| 232 | using the `LZCNT` instruction. |
| 233 | |
| 234 | Below are a few lookup examples assuming ${tex`p = 9`}: |
| 235 | |
| 236 | - ${tex`V = 1`}: ${tex`h = 0`}, ${tex`b = 1`} |
| 237 | - ${tex`V = 1023`}: ${tex`h = 9`}, ${tex`b = 1023`} |
| 238 | - ${tex`V = 1024`}: ${tex`h = 10`}, ${tex`w = 1`}, |
| 239 | ${tex`b = 2 \times 512 + (1024 - 2^{10}) \gg 1 = 1024`} |
| 240 | - ${tex`V = 2048`}: ${tex`h = 11`}, ${tex`w = 2`}, |
| 241 | ${tex`b = 3 \times 512 + (2048 - 2^{11}) \gg 2 = 1536`} |
| 242 | - ${tex`V = 2052`}: ${tex`h = 11`}, ${tex`w = 2`}, |
| 243 | ${tex`b = 3 \times 512 + (2052 - 2^{11}) \gg 2 = 1537`} |
| 244 | |
| 245 | ### Quantile Lookup |
| 246 | |
| 247 | In a naïve implementation, reporting a particular quantile ${tex`q`} |
| 248 | requires traversing all the buckets once. Even if the total number of |
| 249 | values in the histogram is known, the number of buckets to traverse is |
| 250 | still linear to the total number of buckets. |
| 251 | |
| 252 | There are a couple of things to consider during implementation regarding |
| 253 | bias in reporting. Because each bucket covers a range except for the |
| 254 | precise ones, a decision needs to be made about what value in that range |
| 255 | to report when we do a quantile lookup. We also need to consider how to |
| 256 | interpret results that don't fall neatly in a single bucket — for |
| 257 | example, when there are 3 values in the histogram and the quantile in |
| 258 | question is ${tex`0.5`}. For the latter, we can use the |
| 259 | [nearest-rank method](https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method) |
| 260 | to find the nearest bucket with records. Alternatively, it is also |
| 261 | possible to extrapolate an in-between value based on existing data. Each |
| 262 | method has its drawbacks. For example, linear interpolation could lead |
| 263 | to a confusing situation where the interpreted value is deemed |
| 264 | impossible given how values are measured. |
| 265 | |
| 266 | #### Optimization |
| 267 | |
| 268 | To reduce the number of buckets traversed during lookup, one can store |
| 269 | the total number of counts, ${tex`C`}, across all buckets, and return |
| 270 | when the buckets traversed so far yield a cumulative count greater than ${tex`q \times C`} (if traversing from the lowest bucket) or ${tex`(1 - q) \times C`} (if traversing from the highest bucket). |
| 271 | Further reduction can be achieved by using some type of "sketch" that |
| 272 | stores cumulative values across multiple buckets, which allows the |
| 273 | cursor to jump over many buckets at a time. The tradeoff is that |
| 274 | multiple values will need to be updated for each recording, and more |
| 275 | space will be used. |
| 276 | |
| 277 | There are two typical scenarios where H2Histogram is deployed. The first |
| 278 | one is to check if there is any SLO violation, such as p99 latency. In |
| 279 | this case, the percentile of interest is very close to the highest end, |
| 280 | so a simple global count and backward traversal can greatly reduce the |
| 281 | number of buckets visited. The other one is to create a snapshot of |
| 282 | value distribution by reporting several pre-defined percentiles at once, |
| 283 | such as p25, p50, p75, p90, p95, p99... In this case, it is probably |
| 284 | the most efficient to create APIs that allow multiple quantiles to be |
| 285 | reported in a single sweeping trip through all the buckets. |
| 286 | |
| 287 | ## Appendix |
| 288 | |
| 289 | ### Counter Type |
| 290 | |
| 291 | Recording counts as integers provides precise readings within the |
| 292 | counter range, which means it is important to use enough bits to cover |
| 293 | the accumulated counts during the recording period. This generally means |
| 294 | 8-bit, 16-bit, 32-bit, or 64-bit unsigned integers. |
| 295 | |
| 296 | Recording counts as floating point numbers increases the dynamic range |
| 297 | of individual buckets at the cost of precision. Since H2Histogram has |
| 298 | the concept of precision as a configurable option, it is possible to |
| 299 | consider the use of floating point types in conjunction with overall |
| 300 | precision. |
| 301 | |
| 302 | Below is a table of the range and precision limits for different data |
| 303 | types when used to record counts: |
| 304 | |
| 305 | | Type | Range Limit | Relative Error | |
| 306 | |-----------------------|------------------------|------------------| |
| 307 | | 8-bit integer | ${tex`255`} | — (precise) | |
| 308 | | 16-bit integer | ${tex`65535`} | — (precise) | |
| 309 | | 32-bit integer | ${tex`2^{32} - 1`} | — (precise) | |
| 310 | | 64-bit integer | ${tex`2^{64} - 1`} | — (precise) | |
| 311 | | 16-bit (half) float | ${tex`65519`} | ${tex`2^{-10}`} | |
| 312 | | 32-bit (single) float | ${tex`\approx 2^{128}`} | ${tex`2^{-23}`} | |
| 313 | | 64-bit (double) float | ${tex`\approx 2^{1024}`} | ${tex`2^{-52}`} | |
| 314 | |
| 315 | From the above table, it should be obvious that if considering using |
| 316 | 16-bit numbers or less, integer types are strictly superior; for 32- |
| 317 | and 64-bit numbers, the choice should be based on the potential range |
| 318 | of the highest single-bucket count. |
| 319 | |
| 320 | ### Truncated Histogram |
| 321 | |
| 322 | Often, the range of plausible values has both an upper and a lower |
| 323 | bound. In the current H2Histogram design, expressing an upper bound is |
| 324 | straightforward — just provide the smallest ${tex`n`} that fits the |
| 325 | value. But we haven't discussed lower bound. |
| 326 | |
| 327 | In fact, having a lower bound could potentially meaningfully reduce the |
| 328 | amount of memory needed to store a histogram, because smaller values are |
| 329 | stored in finer buckets. For example, for ${tex`n = 32`} and ${tex`p = 8`}, if we know the lower bound of values is 1024, we can eliminate 768 out of 6400 buckets, a 12% reduction. |
| 330 | |
| 331 | More precisely, if we know the lower bound is at least ${tex`2^l`}, we |
| 332 | can eliminate ${tex`2^l`} buckets (if ${tex`l \le p+1`}) or ${tex`(l - p + 1) \times 2^p`} buckets (if ${tex`l > p + 1`}). |
| 333 | |
| 334 | How common do values have lower bounds? In high-level time measurements |
| 335 | in particular, this condition is extremely common. For example, if we |
| 336 | use a clock with nanosecond precision to track common software |
| 337 | operations, the lower bounds are significantly higher than the |
| 338 | resolution of the measurement. Many syscalls are measured in |
| 339 | microseconds, request/response time is often measured in milliseconds. |
| 340 | This means we can expect ${tex`l`} to be in the range of 10 to 20 in a |
| 341 | lot of real-life use cases. |
| 342 | |
| 343 | Use the following calculator to see how much space a truncated |
| 344 | histogram can save you: |
| 345 | </script> |
| 346 | |
| 347 | <script type="module"> |
| 348 | const l = view(Inputs.range([0, n - 1], { value: Math.min(10, n - 1), step: 1, label: tex`l` })); |
| 349 | </script> |
| 350 | |
| 351 | <script type="module"> |
| 352 | const truncated_buckets = l > p + 1 ? BigInt(l - p + 1) * (1n << BigInt(p)) : (1n << BigInt(l)); |
| 353 | </script> |
| 354 | |
| 355 | <script type="module"> |
| 356 | const reduction_pct = total_buckets === 0n ? 0 : (Number(truncated_buckets) / Number(total_buckets)) * 100; |
| 357 | </script> |
| 358 | |
| 359 | <script type="text/markdown"> |
| 360 | - **Number of buckets (original histogram)**: ${total_buckets.toString()} |
| 361 | - **Number of buckets (truncated histogram)**: ${(total_buckets - truncated_buckets).toString()} |
| 362 | - **Buckets saved**: ${truncated_buckets.toString()} (${reduction_pct.toFixed(1)}%) |
| 363 | </script> |
| 364 | |
| 365 | </notebook> |