<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Daniel Dyla</title>
    <description>Daniel is a Senior Open Source Architect at Dynatrace where he works on OpenTelemetry, sits on the W3C Distributed Tracing Working Group, and promotes open source observability.
</description>
    <link>https://dyladan.me/</link>
    <atom:link href="https://dyladan.me/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Fri, 19 May 2023 18:14:02 +0000</pubDate>
    <lastBuildDate>Fri, 19 May 2023 18:14:02 +0000</lastBuildDate>
    <generator>Jekyll v4.3.2</generator>
    
      <item>
        <title>Exponential Histograms</title>
        <description>&lt;p&gt;Previously, in &lt;a href=&quot;/histograms/2023/05/02/why-histograms/&quot;&gt;Why Histograms?&lt;/a&gt; and &lt;a href=&quot;/histograms/2023/05/03/histograms-vs-summaries/&quot;&gt;Histograms vs Summaries&lt;/a&gt;, I went over the basics of histograms and summaries, explaining the tradeoffs, benefits, and limitations of each. Because they’re easy to understand and demonstrate, those posts focused on so-called explicit bucket histograms. The exponential bucket histogram, also referred to as native histogram in Prometheus, is a low-cost, efficient alternative to explicit bucket histograms. In this post, I go through what they are, how they work, and the problems they solve that explicit bucket histograms struggle with.&lt;/p&gt;

&lt;h1 id=&quot;types-of-histograms&quot;&gt;Types of histograms&lt;/h1&gt;

&lt;p&gt;For the purposes of this blog post, there are two major types of histograms: explicit bucket histograms and exponential bucket histograms. In previous posts, I’ve focused on what OpenTelemetry calls explicit bucket histograms and1 Prometheus simply refers to as histograms. As the name implies, an explicit bucket histogram has each bucket configured explicitly by either the user or some default list of buckets. Exponential histograms work by calculating bucket boundaries using an exponential growth function. This means each consecutive bucket is larger than the previous bucket and ensures a constant relative error for every bucket.&lt;/p&gt;

&lt;h1 id=&quot;exponential-histograms&quot;&gt;Exponential histograms&lt;/h1&gt;

&lt;p&gt;In OpenTelemetry exponential histograms, buckets are calculated automatically from an integer &lt;em&gt;scale factor&lt;/em&gt;, with larger scale factors offering smaller buckets and greater precision. It is important to select a scale factor that is appropriate for the distribution of values you are collecting in order to minimize error, maximize efficiency, and ensure the values being collected fit in a reasonable number of buckets. In the next few sections, I’ll go over the scale and error calculations in detail.&lt;/p&gt;

&lt;h1 id=&quot;scale-factor&quot;&gt;Scale factor&lt;/h1&gt;

&lt;p&gt;The most important and most fundamental part of an exponential histogram is also one of the trickiest to understand, the scale factor. From the scale factor, bucket boundaries, and by extension resolution, range, and error rates, are derived. The first step is to calculate the histogram base.&lt;/p&gt;

&lt;p&gt;The base is a constant derived directly from the scale using the equation &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 ^ (2 ^ -scale)&lt;/code&gt;. For example, given a scale of 3, the base can be calculated as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2^(2^-3) ~= 1.090508&lt;/code&gt;. Because the calculation depends on the power of the negative scale, as the scale grows, the base shrinks and vice versa. As will be shown later, this is the fundamental reason that a greater scale factor results in smaller buckets and a higher resolution histogram.&lt;/p&gt;

&lt;h1 id=&quot;bucket-calculation&quot;&gt;Bucket calculation&lt;/h1&gt;

&lt;p&gt;Given a scale factor and its resulting base, we can calculate every possible bucket in the histogram. From the base, the upper bound of each bucket at index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; is defined to be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;base ^ (i + 1)&lt;/code&gt;, with the first bucket lower boundary of 1. Because of this, the upper boundary of the first bucket at index 0 is also exactly the base. For now, we will only consider nonnegative indices, but negative indexed buckets are also possible and define all buckets between 0 and 1. Keeping with our example using a scale of 3 and resulting base of 1.090508, the third bucket at index 2 has an upper bound of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.090508^(2+1) = 1.29684&lt;/code&gt;. The following table shows upper bounds for the first 10 buckets of a few different scale factors:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;index&lt;/th&gt;
      &lt;th&gt;scale -1&lt;/th&gt;
      &lt;th&gt;scale 0&lt;/th&gt;
      &lt;th&gt;scale 1&lt;/th&gt;
      &lt;th&gt;scale 3&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;-1&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;4&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;1.4142&lt;/td&gt;
      &lt;td&gt;1.0905&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;16&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;4&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;1.1892&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;64&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;2.8284&lt;/td&gt;
      &lt;td&gt;1.2968&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;256&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;16&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;4&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;1.4142&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;1024&lt;/td&gt;
      &lt;td&gt;32&lt;/td&gt;
      &lt;td&gt;5.6569&lt;/td&gt;
      &lt;td&gt;1.5422&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;4096&lt;/td&gt;
      &lt;td&gt;64&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;1.6818&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;16384&lt;/td&gt;
      &lt;td&gt;128&lt;/td&gt;
      &lt;td&gt;11.3137&lt;/td&gt;
      &lt;td&gt;1.8340&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;7&lt;/td&gt;
      &lt;td&gt;65536&lt;/td&gt;
      &lt;td&gt;256&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;16&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;262144&lt;/td&gt;
      &lt;td&gt;512&lt;/td&gt;
      &lt;td&gt;22.6274&lt;/td&gt;
      &lt;td&gt;2.1810&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;9&lt;/td&gt;
      &lt;td&gt;1048576&lt;/td&gt;
      &lt;td&gt;1024&lt;/td&gt;
      &lt;td&gt;32&lt;/td&gt;
      &lt;td&gt;2.3784&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;I’ve bolded some of the values here to show an important property of exponential histograms called &lt;em&gt;perfect subsetting&lt;/em&gt;.&lt;/p&gt;

&lt;h1 id=&quot;perfect-subsetting&quot;&gt;Perfect subsetting&lt;/h1&gt;

&lt;p&gt;In the chart above, some of the bucket boundaries are shared between histograms with differing scale factors. In fact, each time the scale factor increases by 1, exactly 1 boundary is inserted between each existing boundary. This feature is called perfect subsetting because each set of boundaries for a given scale factor is a perfect subset of the boundaries for any histogram with a greater scale factor.&lt;/p&gt;

&lt;p&gt;Because of this, histograms with differing scale factors can be normalized to whichever has the lesser scale factor by combining neighboring buckets. This means that histograms with different scale factors can still be combined into a single histogram with exactly the precision of the least precise histogram being combined. For example, histogram &lt;em&gt;A&lt;/em&gt; with scale 3 and histogram &lt;em&gt;B&lt;/em&gt; with scale 2 can be combined into a single histogram &lt;em&gt;C&lt;/em&gt; with scale 2 by first summing each pair of neighboring buckets in &lt;em&gt;A&lt;/em&gt; to form histogram &lt;em&gt;A’&lt;/em&gt; with scale 2. Then, each bucket in &lt;em&gt;A’&lt;/em&gt; is summed with the corresponding bucket of the same index in &lt;em&gt;B&lt;/em&gt; to make &lt;em&gt;C&lt;/em&gt;.&lt;/p&gt;

&lt;h1 id=&quot;relative-error&quot;&gt;Relative Error&lt;/h1&gt;

&lt;p&gt;A histogram does not store exact values for each point, but represents each point as a bucket consisting of a range of possible points. This can be thought of as being similar to lossy compression. In the same way the it is impossible to recover an exact source image from a compressed JPEG, it is impossible to recover the exact input data set from a histogram. The difference between the input data and the estimated reconstruction of the data is the error of the histogram. It is important to understand histogram errors because it affects φ-quantile estimation and may affect how you define your SLOs.&lt;/p&gt;

&lt;p&gt;The relative error for a histogram is defined as half the bucket width divided by the bucket midpoint. Because the relative error is the same across all buckets, we can use the first bucket with the upper bound of the base to make the math easy. An example is shown below using a scale of 3.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;scale = 3
# For base calculation, see above
base  = 1.090508

relative error = (bucketWidth / 2) / bucketMidpoint
               = ((upper - lower) / 2) / ((upper + lower) / 2)
               = ((base - 1) / 2) / ((base + 1) / 2)
               = (base - 1) / (base + 1)
               = (1.090508 - 1) / (1.090508 + 1)
               = 0.04329
               = 4.329%
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For more information regarding histogram errors, see &lt;a href=&quot;https://github.com/open-telemetry/oteps/blob/976c9395e4cbb3ea933d3b51589eba94b87a17bd/text/0149-exponential-histogram.md&quot;&gt;OTEP 149&lt;/a&gt; and the
&lt;a href=&quot;https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#base2-exponential-bucket-histogram-aggregation&quot;&gt;specification for exponential histogram aggregations&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;choosing-a-scale&quot;&gt;Choosing a scale&lt;/h1&gt;

&lt;p&gt;Because increasing the scale factor increases the resolution and decreases the relative error, it may be tempting to choose a large scale factor. After all, why would you want to introduce error? The answer is that there is a positive relationship between the scale factor and the number of buckets required to represent values within a specified range. For example, with 160 buckets (the OpenTelemetry default), histogram &lt;em&gt;A&lt;/em&gt; with a scale factor of 3 can represent values between 1 and about 1 million; histogram &lt;em&gt;B&lt;/em&gt; with a scale of 4 the same number of buckets would only be able to represent values between about 1 and about 1000, albeit at half the relative error. To represent the same range of values as &lt;em&gt;A&lt;/em&gt; with &lt;em&gt;B&lt;/em&gt;, twice as many buckets are required; in this case 320.&lt;/p&gt;

&lt;p&gt;This brings me to the first most important point of choosing a scale, &lt;em&gt;data contrast&lt;/em&gt;. Data contrast is how you describe the difference in scale between the smallest possible value x and the largest possible value y in your dataset and is calculated as the constant multiple c such that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y = c * x&lt;/code&gt;. For example, if your data is between 1 and 1000 milliseconds, your data contrast is 1000. If your data is between 1 kilobyte and 1 terabyte, your data contrast is 1,000,000,000. Data contrast, scale, and the number of buckets are all interlinked such that if you have 2, you can calculate the third.&lt;/p&gt;

&lt;p&gt;Fortunately, if you are using OpenTelemetry, scale choice is largely done for you. In OpenTelemetry, you configure a maximum scale (default 20) and a maximum size (default 160), or number of buckets, in the histogram. The histogram is initially assumed have the maximum scale. As additional data points are added, the histogram will rescale itself down such that the data points always fit within your maximum number of buckets. The default of 160 buckets was chosen by the OpenTelemetry authors to be able to cover typical web requests between 1ms and 10s with less than 5% relative error. If your data has less contrast, your error will be even less.&lt;/p&gt;

&lt;h1 id=&quot;negative-or-zero-values&quot;&gt;Negative or zero values&lt;/h1&gt;

&lt;p&gt;For the bulk of this post we have ignored zero and negative values, but negative buckets work much the same way, growing larger as the buckets get further from zero. All of the math and explanation above applies in the same way to negative values, but they should be substituted for their absolute values, and upper bounds for buckets are lower bounds (or upper absolute value bounds). Zero values, or values with an absolute value less than a configurable threshold, go into a special zero bucket. When merging histograms with differing zero thresholds, the larger threshold is taken and any buckets with absolute value upper bounds within the zero threshold are added to the zero bucket and discarded.&lt;/p&gt;

&lt;h1 id=&quot;opentelemetry-and-prometheus&quot;&gt;OpenTelemetry and Prometheus&lt;/h1&gt;

&lt;p&gt;Compatibility between OpenTelemetry and Prometheus is probably a topic large enough for its own post. For now I will just say that for all practical purposes, OpenTelemetry exponential histograms are 1:1 compatible with Prometheus native histograms. Scale calculations, bucket boundaries, error rates, zero buckets, etc are all the same. For more information, I recommend you watch this talk given by Ruslan Vovalov and Ganesh Vernekar: &lt;a href=&quot;https://www.youtube.com/watch?v=W2_TpDcess8&quot;&gt;Using OpenTelemetry’s Exponential Histograms in Prometheus&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;edits&quot;&gt;Edits&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Fix a typo in the scale factor and bucket calculations.
Thanks &lt;a href=&quot;https://github.com/pirgeo&quot;&gt;@pirgeo&lt;/a&gt;!&lt;/li&gt;
  &lt;li&gt;Rewrite &lt;a href=&quot;#relative-error&quot;&gt;Relative Error&lt;/a&gt; section incorporating feedback from &lt;a href=&quot;https://github.com/oertl&quot;&gt;@oertl&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
        <pubDate>Thu, 04 May 2023 23:00:00 +0000</pubDate>
        <link>https://dyladan.me/histograms/2023/05/04/exponential-histograms/</link>
        <guid isPermaLink="true">https://dyladan.me/histograms/2023/05/04/exponential-histograms/</guid>
        
        <category>metrics</category>
        
        <category>opentelemetry</category>
        
        <category>prometheus</category>
        
        <category>histograms</category>
        
        
        <category>Histograms</category>
        
      </item>
    
      <item>
        <title>Histograms vs Summaries</title>
        <description>&lt;p&gt;In many ways, histograms and summaries appear quite similar.
They both roll up many data points into a data structure for efficient processing, transmission, and storage.
They can also both be used to track arbitrary quantiles such as the median or p99 of your data.
So how do they differ? Let’s dive in.&lt;/p&gt;

&lt;h1 id=&quot;histograms&quot;&gt;Histograms&lt;/h1&gt;

&lt;p&gt;Since I just published a post about &lt;a href=&quot;/histograms/2023/05/02/why-histograms/&quot;&gt;histograms and when they are useful&lt;/a&gt;, I will only provide a quick summary here.
A histogram is a data structure which describes the distribution of a set of data points.
For example, one may collect all response times to an HTTP endpoint and describe them as a histogram with 10 bins ranging from 0 to 1000 milliseconds.
Each bin counts the number of requests that fall within its range.&lt;/p&gt;

&lt;svg class=&quot;fig-1&quot;&gt;&lt;/svg&gt;
&lt;script&gt;
  new chartXkcd.Bar(document.querySelector('.fig-1'), {
    title: 'Response Time (1260 requests)',
    xLabel: 'Milliseconds',
    yLabel: 'Requests',
    data: {
      labels: ['&lt; 10', '&lt; 20', '&lt; 30', '&lt; 50', '&lt; 75', '&lt; 100', '&lt; 200', '&lt; 300', '&lt; 500', '&lt; 750', '&lt; 1000', '1001+'],
      datasets: [{
        data: [100, 120, 150, 210, 220, 180, 130, 80, 40, 10, 5, 15],
      }],
    },
    options: { // optional
      yTickCount: 3,
      legendPosition: chartXkcd.config.positionType.upLeft
    }
  });
&lt;/script&gt;

&lt;p&gt;From this we can estimate φ-quantiles like the 90th percentile.
We know there are 1260 requests, so the 1134th-ranked (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1260 * .90&lt;/code&gt;) request represents the 90th percentile.
We can then calculate that the request would fall in the 8th bucket (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;300 &amp;lt;= x &amp;lt; 500&lt;/code&gt;) by summing the bucket counts until we exceed that rank.
Finally, using relative rank within the bucket of 24 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1134 - 1110&lt;/code&gt;), we can estimate the p90 value to be 360ms (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;300 + ((24 / 80) * (500 - 300))&lt;/code&gt;) using linear interpolation.
It is important to know that this is an &lt;em&gt;estimation&lt;/em&gt; and could be off by as much as 60ms (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;360 - 300&lt;/code&gt;), a relative error of 17% (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;60 / 360&lt;/code&gt;).
This error can be mitigated by configuring more and smaller buckets around your SLO values, but never eliminated.&lt;/p&gt;

&lt;p&gt;One important property of histograms is that they are &lt;em&gt;aggregatable&lt;/em&gt;, meaning that as long as the bucket boundaries line up, an arbitrary number of histograms can be combined into a single histogram with no loss of data or precision.
This means that an arbitrary number of hosts can report histogram data structures to a server, which can aggregate and compute quantiles from all of them as if they were reported by a single host.
By collecting histograms from 1 or more hosts over a long period of time, developers can gain a strong understanding of how their data is distributed and how that distribution changes over time.&lt;/p&gt;

&lt;h1 id=&quot;summaries&quot;&gt;Summaries&lt;/h1&gt;

&lt;p&gt;Summaries work in almost the opposite manner.
When a summary is configured it is given a φ-quantile to track, an acceptable error range, and a decay rate.
For example, a summary may track p99 ± 0.5% with a decay rate of 5 minutes.
The math is more complex so it won’t be discussed here, but one important distinction is that the value is calculated on the client before it is sent to the server.
The most important consequence of this is that summaries from multiple clients &lt;em&gt;cannot be aggregated&lt;/em&gt;.
Another disadvantage is that if you cannot query arbitrary φ-quantiles, only those which you have configured and collected in advance.&lt;/p&gt;

&lt;p&gt;Given these disadvantages, summaries do have some advantages.
First, they trade off a small performance penalty on the client for a significant reduction in transmission, storage, and server processing cost.
In our histogram example above, the distribution is represented as 12 separate timeseries: 1 counter for each bucket + 1 bucket for out of range values + a total sum of all values.
That is for a single, relatively modest, histogram with no attributes to multiply cardinality.
By comparison, the summary is only a single timeseries for the precomputed &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p99&lt;/code&gt; value.
Second, they have very low and configurable relative error rates.
In the histogram example above, we had a potential relative error of 17% where our summary is guaranteed to be within ± 0.5% accuracy.&lt;/p&gt;

&lt;h1 id=&quot;so-which-should-you-choose&quot;&gt;So which should you choose?&lt;/h1&gt;

&lt;p&gt;The disappointing answer is “it depends,” and there is no one-size-fits-all solution.
If you need to aggregate data from many sources, then histograms may be the right choice.
If you are collecting a large number of separate metrics with very strict SLOs, or your Prometheus server is particularly resource constrained, then maybe summaries are the right choice for you.
Maybe your ideal solution is a hybrid with some histograms for flexible querying and some summaries for high-accuracy, low-cost alerting.
Only you can know the ins and outs of your own system and design an observability solution around it that is accurate and flexible and fits your particular needs.
The key is knowing the strengths and limitations of the available tools so you can make informed decisions.&lt;/p&gt;

&lt;h1 id=&quot;bonus-round-nativeexponential-histograms&quot;&gt;Bonus round: native/exponential histograms&lt;/h1&gt;

&lt;p&gt;I’m planning a longer post on this so I’ll keep this short, but many of the key disadvantages of histograms are mitigated by exponential histograms, called native histograms in Prometheus.
They are available in Prometheus as an experimental feature since v2.40.0, and stable in the OpenTelemetry specification as of v1.17.0.
Exponential histograms come with several advantages:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Very efficient data collection and transmission&lt;/li&gt;
  &lt;li&gt;A constant number of timeseries created (and fewer of them) per histogram&lt;/li&gt;
  &lt;li&gt;Very low relative error rates&lt;/li&gt;
  &lt;li&gt;Automatic bucket boundaries, making them simpler to configure and use&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These advantages are accomplished by defining bucket boundaries according to a scale factor, intelligently resizing buckets as your distribution evolves, instead of the traditional method of defining explicit buckets.
If you’re not happy with the state of your current histograms and summaries, I encourage you to give exponential histograms a try.
As of this writing there are no official Prometheus docs on native histograms, but if you stay tuned I plan to add a thorough explanation of them in the coming days.&lt;/p&gt;

&lt;p&gt;Until then, here are some talks I found helpful:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://promcon.io/2022-munich/talks/native-histograms-in-prometheus/&quot;&gt;PromCon EU 2022 - Native Histograms in Prometheus - Ganesh Vernekar&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TgINvIK9SYc&quot;&gt;Kubecon EU 2023 - Prometheus Native Histograms in Production - Björn Rabenstein, Grafana Labs&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=W2_TpDcess8&quot;&gt;Using OpenTelemetry’s Exponential Histograms in Prometheus - Ruslan Kovalov &amp;amp; Ganesh Vernekar&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;edits&quot;&gt;Edits&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Mixed up the x and y axis labels on the histogram&lt;/li&gt;
  &lt;li&gt;Incorporate review feedback from OpenTelemetry blog&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Wed, 03 May 2023 22:03:00 +0000</pubDate>
        <link>https://dyladan.me/histograms/2023/05/03/histograms-vs-summaries/</link>
        <guid isPermaLink="true">https://dyladan.me/histograms/2023/05/03/histograms-vs-summaries/</guid>
        
        <category>metrics</category>
        
        <category>opentelemetry</category>
        
        <category>prometheus</category>
        
        <category>histograms</category>
        
        
        <category>Histograms</category>
        
      </item>
    
      <item>
        <title>Why Histograms?</title>
        <description>&lt;p&gt;A histogram is a multi-value counter that summarizes the distribution of data points.
For example, a histogram may have 3 counters which count the occurrences of negative, positive, and zero values respectively.
Given a series of numbers, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-9&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;6&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-1&lt;/code&gt;, the histogram would count &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; negative, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; zero, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt; positive values.
A single histogram data point is most commonly represented as a bar chart.&lt;/p&gt;

&lt;svg class=&quot;histogram-point&quot;&gt;&lt;/svg&gt;
&lt;script&gt;
  const histPoint = document.querySelector('.histogram-point')

  new chartXkcd.Bar(histPoint, {
    title: 'Positivity of numbers', // optional
    data: {
      labels: ['&lt;0', '0', '&gt;0'],
      datasets: [{
        data: [2, 1, 3],
      }],
    },
    options: { // optional
      yTickCount: 3,
      legendPosition: chartXkcd.config.positionType.upLeft
    }
  });
&lt;/script&gt;

&lt;p&gt;The above example has only 3 possible output values, but it is common to have many more in a single histogram.
A real-world application typically exports a histogram every minute that summarizes a metric for the previous minute.
By using histograms this way, you can study how the distribution of your data changes over time.&lt;/p&gt;

&lt;h1 id=&quot;what-are-histograms-for&quot;&gt;What are histograms for?&lt;/h1&gt;

&lt;p&gt;There are many uses for histograms, but their power comes from the ability to efficiently answer queries about the distribution of your data.
These queries most commonly come in some form like “what was the median response time in the last minute?”
These are known as φ-quantiles, and often are abbreviated in a shorthand like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p50&lt;/code&gt; for the 50th percentile or 0.5-quantile, also known as the median.
More generally, the φ-quantile is the observation value that ranks at number φ*N among the N observations.&lt;/p&gt;

&lt;h1 id=&quot;why-are-histograms-useful&quot;&gt;Why are Histograms useful?&lt;/h1&gt;

&lt;p&gt;A common use-case for histograms in observability is defining service level objectives (SLOs).
One example of such an SLO might be “&amp;gt;=99% of all queries should respond in less than 30ms,” or “90% of all page loads should become interactive within 100ms of first paint.”&lt;/p&gt;

&lt;p&gt;In the following chart, you can see the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p50&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p90&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p99&lt;/code&gt; response times plotted for some requests over some time.
From the data, you can see that 50% of requests are served in around 20-30ms or less, 90% of requests are served in under about 80ms, and 99% of requests are served in under around 90ms.
You can very quickly see that at least 50% of your users are receiving very fast response times, but almost all of your users are experiencing response times under 90ms.&lt;/p&gt;

&lt;svg class=&quot;hist-lines&quot;&gt;&lt;/svg&gt;
&lt;script&gt;
const histLines = document.querySelector('.hist-lines')
new chartXkcd.Line(histLines, {
    title: 'Response times', // optional
    xLabel: 'Time',
    yLabel: 'Milliseconds',
    data: {
        labels: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9', 't10'],
        datasets: [{
            label: 'p50',
            data: [25, 22, 24, 24, 25, 28, 23, 21, 21, 28, 23, 0],
        }, {
            label: 'p90',
            data: [75,72,69,78,81,62,72,82,73,75,71,72],
        }, {
            label: 'p99',
            data: [85,82,89,88,84,72,82,88,83,85,81,77],
        }],
    },
    options: { // optional
        legendPosition: chartXkcd.config.positionType.upLeft
    }
});
&lt;/script&gt;

&lt;h1 id=&quot;other-metric-types&quot;&gt;Other metric types&lt;/h1&gt;

&lt;p&gt;What if you’re already defining SLOs based on other metrics?
You may have considered defining the SLOs to be based on gauges or counters.
This approach can work, but it requires defining your SLOs before understanding your data distribution and requires non-trivial implementation at collection time.
It is also inflexible; if you decide to change your SLO from 90% of requests to 99% of requests, you have to make and release code changes, then wait for the old data to age out and the new metric to collect enough data to make useful queries.
Because histograms model data as a distribution from start to finish, they enable you to simply change your queries and get answers on the data you’ve already collected.
Particularly with exponential histograms, arbitrary distribution queries can be made with very low relative error rates and minimal resource consumption on both the client and the analysis backend.&lt;/p&gt;

&lt;p&gt;The inflexibility of not using histograms for SLOs also impacts your ability to gauge impact when your SLO is violated.
For example, imagine you are collecting a gauge that calculates the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p99&lt;/code&gt; of some metric and you define an SLO based on it.
When your SLO is violated and an alert is triggered, how do you know it is really only affecting 1% of queries, 10%, or 50%? A histogram allows you to answer that question by querying the percentiles you’re interested in.
Another option is to collect each quantile you’re interested in as a gauge.
Some systems, like Prometheus, support this natively using a metric type sometimes called a summary.
Summaries can work, but they suffer the same inflexibility as gauges and counters, requiring you to decide ahead of time which quantiles to collect.
They also cannot be aggregated, meaning that a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p90&lt;/code&gt; cannot be accurately calculated from two separate hosts each reporting their own &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p90&lt;/code&gt;.&lt;/p&gt;

&lt;h1 id=&quot;other-data-sources-and-metric-types&quot;&gt;Other data sources and metric types&lt;/h1&gt;

&lt;p&gt;You may ask, “why would I report a separate metric rather than calculating it from my existing log and trace data?”
While it is true that for &lt;em&gt;some&lt;/em&gt; use cases, like response times, this may be possible, it is not necessarily possible for &lt;em&gt;all&lt;/em&gt; use cases.
Even when quantiles can be calculated from existing data, you may run into other problems.
You need to be sure your observability backend is able to query and analyze a large amount of existing data on-line or index and analyze it at ingestion time.
If you are sampling your logs and traces or employing a data retention policy that ages data out, you need to be sure those things are not affecting derived metrics, or that they are properly re-weighted, or you risk not being able to accurately asses your SLOs.
Depending on your sampling strategy, it may not even be possible.
Using histograms is a way to avoid these subtle problems if they apply to you.&lt;/p&gt;

&lt;h3 id=&quot;edits&quot;&gt;Edits&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Incorporate review feedback from OpenTelemetry blog&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 02 May 2023 12:00:00 +0000</pubDate>
        <link>https://dyladan.me/histograms/2023/05/02/why-histograms/</link>
        <guid isPermaLink="true">https://dyladan.me/histograms/2023/05/02/why-histograms/</guid>
        
        <category>metrics</category>
        
        <category>opentelemetry</category>
        
        
        <category>Histograms</category>
        
      </item>
    
      <item>
        <title>Docker</title>
        <description>&lt;p&gt;A few weeks ago a coworker asked me to do an introductory presentation on the way we use Docker. This is an attempt at distilling my thoughts into a more consumable form. In this post I’ll cover everything from setup, to a basic dockerfile, to deployment and advanced usage.&lt;/p&gt;

&lt;h2 id=&quot;history-and-motivation&quot;&gt;History and Motivation&lt;/h2&gt;

&lt;p&gt;In the early days of computing, hardware and the environment that an application ran in was largely predictable and unchanging. Since then, computers and servers have evolved into commoditized systems with many users and manifold possible hardware and software configurations. With a modern public cloud architecture, the developer has very little control over the hardware and software that will ultimately be used to deploy production software. In many cases, the developer has no control at all. As environments became more complex, tools popped up to automate provisioning and deployment as much as possible so that an environment could be as predictable as possible, but failures occur often and when you least expect.&lt;/p&gt;

&lt;p&gt;A team where I work recently had a problem where their automated deployment script suddenly started pulling a new version of a JAR that was incompatible with the version their application was developed against, leading to a problem that occurred seemingly out of nowhere and was difficult to debug. The team has since fixed this, but the key takeaway is important. The fundamental nature of their problem was not that  the deployment script pulled the wrong version of a package, but that this was even possible in the first place.&lt;/p&gt;

&lt;h2 id=&quot;process-containers&quot;&gt;Process Containers&lt;/h2&gt;

&lt;p&gt;This may seem like a simple problem, but what developer can honestly say that they have control over every single layer of their deployment stack? For those that can, do you? What version of node/java/go are you running? Do you control it on every production system? Even all the way down to the security patch level? The answer to one of these questions is overwhelmingly likely to be no, and this is the fundamental problem that cgroups (process containers), LXC, and Docker set out to solve.&lt;/p&gt;

&lt;p&gt;Cgroups are a layer of abstraction over an operating system similar to virtualization, but without requiring a fully virtualized operating system, and LXC was the first popular tool for managing cgroups. A process in a cgroup can be given limited or unlimited memory, hard disk space, network bandwidth, or access to arbitrary hardware. A process in a cgroup may think it is bound to listen on port 8080, when in fact it is bound on port 3232 of the host system, or not bound at all. It may think the system has only 2GB of memory when it actually has 10, or it may think it has 10 when it only has 2. A process in a cgroup is entirely isolated from the underlying hardware and the rest of the operating system unless it is explicitly given permission and access.&lt;/p&gt;

&lt;h2 id=&quot;docker&quot;&gt;Docker&lt;/h2&gt;

&lt;p&gt;Docker is a management system for cgroups just like LXC. In fact, Docker used to be a wrapper around LXC. Docker takes container management to the next level with a layering file system, a public image repository, and a simple method for reproducible and fast image builds. It works by building an image in a series of layers, then it runs that image in a cgroup entirely isolated from the rest of the system. The only components that may be different between deployments are the hardware, the Linux kernel, and Docker itself.&lt;/p&gt;

&lt;h2 id=&quot;dockerfiles-and-layerfs&quot;&gt;Dockerfiles and LayerFS&lt;/h2&gt;

&lt;p&gt;Docker image layers themselves are described by commands in a Dockerfile. Each command in a Dockerfile creates another immutable layer on top of the Docker image. This is important to understand, once a layer is committed, it is permanent. Layers can only be added on top, not removed or modified. Each layer added to the Docker image creates a new Docker image. The docker image deployed to production is simply a tagged image representing that particular layer on top of all layers that came before it. Because of this, you can build new docker images on top of Docker images that you’ve already built. Below is an example of a simple Dockerfile built on top of an image from the DockerHub image repository.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;FROM node:8.4-alpine
WORKDIR /opt/helloworld
RUN apt add —-no-cache make gcc g++ python git
COPY . .
RUN npm install
EXPOSE 3000
CMD [“npm”, “start”]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;A basic Dockerfile&lt;/p&gt;

&lt;p&gt;This Dockerfile begins with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;node:8.4-alpine&lt;/code&gt; image, which is itself simply a layered docker image. Next, it creates a working directory and installs the build dependencies. After dependencies are installed, it copies the project files from the local directory into the image working directory. The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ADD&lt;/code&gt; command is special, because it hashes the contents of any files it adds before adding them and only copies files if the contents are changed. It also only breaks the Docker cache if files changed. The Docker cache will be covered later. This speeds up builds and helps with reproducibility. After these files are copied, the node dependencies are installed, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;EXPOSE&lt;/code&gt; port tells docker what port our application listens on, and the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CMD&lt;/code&gt; instruction tells Docker how to start our application.&lt;/p&gt;

&lt;h2 id=&quot;building&quot;&gt;Building&lt;/h2&gt;
&lt;p&gt;The next step after creating a docker image is building it. The docker build command runs each command in the Dockerfile in succession, each command building a new layer. The final layer is the Docker image that you will deploy to production.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker build –t helloworld .
Step 1/7 : FROM node:8.4-alpine
 ---&amp;gt; 016382f39a51
Step 2/7 : WORKDIR /opt/helloworld
 ---&amp;gt; 487d815acfa8
Step 3/7 : RUN apk add --no-cache make gcc g++ python git
 ---&amp;gt; 8396e01c1abc
Step 4/7 : COPY . .
 ---&amp;gt; 1b41e980e14e
Step 5/7 : RUN npm install
 ---&amp;gt; d46bf266b41b
Step 6/7 : EXPOSE 3000
 ---&amp;gt; b4a93ac05152
Step 7/7 : CMD [“npm”, “start”]
 ---&amp;gt; 58664ba3b045
Successfully built 58664ba3b045
Successfully tagged helloworld:latest

$ docker images
REPOSITORY   TAG           IMAGE ID       CREATED             SIZE
helloworld   latest        58664ba3b045   About a minute ago  273MB
node         8.4-alpine    016382f39a51   7 weeks ago         66.3MB
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In the above build you can see a few things. First, a hash was generated for each step in the build. This is the hash representing the docker image as it existed at that layer. Each layer can be run just like any other docker container. Second, you can see that two images show up in the docker images output. By default, docker only shows &lt;em&gt;tagged&lt;/em&gt; images. With a simple &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-a&lt;/code&gt;, you can display all of the images on the system.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker images -a
REPOSITORY   TAG           IMAGE ID       CREATED             SIZE
helloworld   latest        58664ba3b045   About a minute ago  273MB
&amp;lt;none&amp;gt;       &amp;lt;none&amp;gt;        b4a93ac05152   About a minute ago  273MB
&amp;lt;none&amp;gt;       &amp;lt;none&amp;gt;        d46bf266b41b   About a minute ago  273MB
&amp;lt;none&amp;gt;       &amp;lt;none&amp;gt;        1b41e980e14e   About a minute ago  273MB
&amp;lt;none&amp;gt;       &amp;lt;none&amp;gt;        8396e01c1abc   About a minute ago  272MB
&amp;lt;none&amp;gt;       &amp;lt;none&amp;gt;        487d815acfa8   About a minute ago  66.3MB
node         8.4-alpine    016382f39a51   7 weeks ago         66.3MB
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;caching&quot;&gt;Caching&lt;/h2&gt;

&lt;p&gt;If you look closely at the above output, you can see that the image IDs exactly match the image hashes from the build command. This is used for Docker’s caching system. The caching system is one of Docker’s hallmark features, but it also is a point of friction for many new to Docker. In broad strokes, the caching system works by hashing the next command in the Dockerfile. It then compares the hash with the hashes of all other images in the system, as well as the hashes of all layers used to build the current state. If the hashes match, that image is used rather than being rebuilt. This means that steps like compilation are skipped if the hashes match. This can be a huge time saver in many cases where build dependencies are built from source and rarely change, but it can also be the cause of major headaches when the cache doesn’t rebuild something that you want it to rebuild. Some commands like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ADD&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;COPY&lt;/code&gt; break the cache when it is appropriate, and in the advanced usage section we will go over some methods of manually breaking the cache.&lt;/p&gt;

&lt;p&gt;The caching system works because of the layered file system described above. Each command is simply layered on top of the previous image, without mutating the underlying image. This means that any build dependencies present when a layer is committed will be in the image forever. Even if they are deleted in another layer later on, they still take up space in a lower layer of the image. In the case of tools like compilers and build toolchains, this can add up to hundreds of MBs if not GBs. In the advanced usage section we will discuss some strategies for reducing the docker image size.&lt;/p&gt;

&lt;h2 id=&quot;deployment&quot;&gt;Deployment&lt;/h2&gt;

&lt;h3 id=&quot;tagging&quot;&gt;Tagging&lt;/h3&gt;

&lt;p&gt;The first step in a Docker deployment is to push your image to an image host. This can be a private image repository or a public one like Docker Hub. First, tag your image with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;repository/name:tag&lt;/code&gt; format (tag is optional and will be set to latest by default). In my case I’m going to tag the image as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dyladan/helloworld&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker tag helloworld dyladan/helloworld
$ docker images
REPOSITORY         TAG           IMAGE ID       CREATED        SIZE
dyladan/helloworld latest        58664ba3b045   7 minutes ago  273MB
helloworld         latest        58664ba3b045   7 minutes ago  273MB
node               8.4-alpine    016382f39a51   7 weeks ago    66.3MB
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;pushing&quot;&gt;Pushing&lt;/h3&gt;

&lt;p&gt;The next step is to push the image.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;## $ docker push dyladan/helloworld:latest
The push refers to a repository [docker.io/dyladan/helloworld]
388bbf91205d: Pushed
6516b07acf4f: Pushed
2e03be0e8df6: Pushed
a1548a35ad87: Pushed
0b3e54ee2e85: Mounted from dyladan/beer-guardian
ad77849d4540: Mounted from dyladan/beer-guardian
5bef08742407: Mounted from dyladan/beer-guardian
latest: digest: sha256:c2731a19724bf48f0026b400a3e0f1678e4095cb6a3b44ba88690ee65e0c6db9 size: 1786
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This pushes not only the image that we’ve built, but all of the layers used to build it. You may notice that the last three lines don’t show &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pushed&lt;/code&gt;, but show &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Mounted from dyladan/beer-guardian&lt;/code&gt;. This is because the Docker caching systems works for image repositories as well. It knows that the first three layers are the same as images already in the repository in a different repo, and skips sending them over the network. Again, the is enabled by the layering file system and the immutability of images.&lt;/p&gt;

&lt;h3 id=&quot;pulling&quot;&gt;Pulling&lt;/h3&gt;

&lt;p&gt;Next, on your production host, you pull the image from the repository.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker pull dyladan/helloworld
Using default tag: latest
latest: Pulling from dyladan/helloworld
6d987f6f4279: Pull complete
23922eede9ea: Pull complete
4c0008704272: Pull complete
119c0fce894a: Pull complete
de2f7dd96f79: Pull complete
d3a44d47c6b4: Pull complete
5131935ce65c: Pull complete
Digest: sha256:c2731a19724bf48f0026b400a3e0f1678e4095cb6a3b44ba88690ee65e0c6db9
Status: Downloaded newer image for dyladan/helloworld:latest

$ docker images -a
REPOSITORY         TAG         IMAGE ID       CREATED         SIZE
dyladan/helloworld latest      58664ba3b045   20 minutes ago  273MB
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;running&quot;&gt;Running&lt;/h3&gt;

&lt;p&gt;That’s it! Since we built a fully self-contained binary image with no external dependencies, we can simply run the image we pulled. No more downloading, installing, and configuring hundreds of dependencies on every host. Just the lightweight Docker environment and the Linux kernel. The best part is that you can run just one, or thousands of images on a host and the running images don’t even know or care. In the example below, the container listens on port 3000, but that is just the container port. On the host, it is actually listening on port 80.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker run –t –p 80:3000 helloworld
npm info using ~npm@5.3.0~
npm info using ~node@v8.4.0~
npm info lifecycle helloworld@1.0.0~prestart: ~helloworld@1.0.0~
npm info lifecycle helloworld@1.0.0~start: ~helloworld@1.0.0~
helloworld@1.0.0 start /opt/helloworld
&amp;gt; node index.js
Listening on port 3000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;advanced-usage&quot;&gt;Advanced Usage&lt;/h2&gt;

&lt;h3 id=&quot;reducing-image-size&quot;&gt;Reducing Image Size&lt;/h3&gt;

&lt;h3 id=&quot;breaking-the-cache&quot;&gt;Breaking the Cache&lt;/h3&gt;

&lt;h3 id=&quot;multi-step-builds&quot;&gt;Multi-Step Builds&lt;/h3&gt;

&lt;h2 id=&quot;docker-compose&quot;&gt;Docker Compose&lt;/h2&gt;

&lt;h2 id=&quot;kubernetes&quot;&gt;Kubernetes&lt;/h2&gt;

&lt;h2 id=&quot;todo&quot;&gt;TODO&lt;/h2&gt;
&lt;ul class=&quot;task-list&quot;&gt;
  &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Advanced Usage
    &lt;ul class=&quot;task-list&quot;&gt;
      &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Reducing image size&lt;/li&gt;
      &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Breaking the cache&lt;/li&gt;
      &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Multi-step builds&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Docker Compose
    &lt;ul class=&quot;task-list&quot;&gt;
      &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;One host&lt;/li&gt;
      &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Multiple hosts&lt;/li&gt;
      &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Docker machine&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; class=&quot;task-list-item-checkbox&quot; disabled=&quot;disabled&quot; /&gt;Kubernetes and ECS&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 31 Oct 2017 00:00:00 +0000</pubDate>
        <link>https://dyladan.me/abc/2017/10/31/docker/</link>
        <guid isPermaLink="true">https://dyladan.me/abc/2017/10/31/docker/</guid>
        
        
        <category>abc</category>
        
      </item>
    
      <item>
        <title>Asynchronous Javascript</title>
        <description>&lt;p&gt;I’m thinking about adding a new post here about the evolution of asynchronous javascript. Until that comes, maybe this will help.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/dyladan/467b096d1c46f4599ec5ddda5085e161.js&quot;&gt;&lt;/script&gt;

</description>
        <pubDate>Thu, 17 Aug 2017 00:00:00 +0000</pubDate>
        <link>https://dyladan.me/abc/2017/08/17/async-javascript/</link>
        <guid isPermaLink="true">https://dyladan.me/abc/2017/08/17/async-javascript/</guid>
        
        
        <category>abc</category>
        
      </item>
    
      <item>
        <title>The Yubikey OTP Algorithm</title>
        <description>&lt;p&gt;The yubikey is a fascinating device capable of generating passwords that
are only useful in the instant they are generated.
By the end of this post you should understand how passwords are generated,
encrypted, decrypted, parsed, and validated.&lt;/p&gt;

&lt;h2 id=&quot;first-steps&quot;&gt;First steps&lt;/h2&gt;

&lt;p&gt;Before your yubikey can generate passwords, it must be set up to generate
valid keys. Specifically, this means it needs a public ID, a private ID,
and an AES128 key. The public ID is a 12 character modhex encoded string
(6 bytes).  Modhex is basically just hexadecimal, but instead of
0123456789abcdef, it uses cbdefghijklnrtuv. The creators of yubikey decided
to use this because it avoids keys that may not be found or work differently
on international keyboards. The private ID is a regular 12 character hexadecimal
string (6 bytes). The AES128 key is a 128 bit (16 byte) random number encoded
as a 32 character hexadecimal string. You can use the application provided
by yubikey to write these values to your key, and also to send them to
yubikey’s hosted authentication service. This will be important later.&lt;/p&gt;

&lt;h2 id=&quot;generating-the-password&quot;&gt;Generating the Password&lt;/h2&gt;

&lt;p&gt;Now that your key is capable of generating passwords and the yubico
auth service is capable of validating it, we can dive into how this algorithm
works. The first thing to do is use your key to generate an OTP like this one.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;vcbindnjbrglnjnkjrbeibifjunjrugctrltdilrrler
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Note: I’ve created a yubikey just for the sake of this demo. I did not
send the info to yubico so it will not validate with their servers but you
are free to try :)&lt;/p&gt;

&lt;h2 id=&quot;decrypting-the-password&quot;&gt;Decrypting the Password&lt;/h2&gt;

&lt;p&gt;The first thing the server does when it recieves your password is decrypt it
into a useable token using the AES key we sent it earlier. You may notice that
the first 12 characters of your generated token are always the same, they are
the 12 characters used as your public id. The server uses this public ID to
look up the AES key associated with your yubikey.  This key is then used to
decrypt the rest of the password into a 32 character (16 byte) hexadecimal
token.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# split the password into the 12 character id and the 32 character payload
&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pubID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;split_otp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vcbindnjbrglnjnkjrbeibifjunjrugctrltdilrrler&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'vcbindnjbrgl'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'njnkjrbeibifjunjrugctrltdilrrler'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# convert the 32 character payload from modhex to hexadecimal
&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;modhex_to_hex&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;s&quot;&gt;'b8b98c1371748eb8ce50dcad27acca3c'&lt;/span&gt;

&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# retreive the AES key associated with the ID from the database
&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;aesKey&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pubID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;s&quot;&gt;'8754cb76d94d74fb12987a9dc8c2b9fc'&lt;/span&gt;

&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decrypted_key&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;aes_decrypt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;aesKey&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;s&quot;&gt;'b7f5c2c4f8061000388837003206bf59'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;At this point a simple CRC16 checksum is done on the decrypted token. The CRC16 must be
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0xf0b8&lt;/code&gt; or the token is invalid. The reason for this is some magic based on
how CRC16 works and doing a checksum of a checksum. Someone more knowledgeable may be
able to explain why this is.&lt;/p&gt;

&lt;h2 id=&quot;parsing-the-decrypted-token&quot;&gt;Parsing the Decrypted Token&lt;/h2&gt;

&lt;p&gt;The next thing the server must do is parse the decrypted token. This is a very simple
process and consists of splitting it up according to the following schema.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;field&lt;/th&gt;
      &lt;th&gt;# chars&lt;/th&gt;
      &lt;th&gt;# bits&lt;/th&gt;
      &lt;th&gt;description&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;uid&lt;/td&gt;
      &lt;td&gt;12&lt;/td&gt;
      &lt;td&gt;192&lt;/td&gt;
      &lt;td&gt;The uid is the private ID for your yubikey&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;useCtr&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;64&lt;/td&gt;
      &lt;td&gt;The use counter is the number of sessions your yubikey has been used&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;tstp&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;96&lt;/td&gt;
      &lt;td&gt;The timestamp is randomly seeded when you plug in your yubikey, then increments at 8hz&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;sessionCtr&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;32&lt;/td&gt;
      &lt;td&gt;The number of times your yubikey has been triggered in the current session&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;rnd&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;64&lt;/td&gt;
      &lt;td&gt;A random value to increase entropy&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;crc&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;64&lt;/td&gt;
      &lt;td&gt;A crc16 checksum of the entire token&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;validation&quot;&gt;Validation&lt;/h2&gt;

&lt;p&gt;Now that the validation server has decrypted and parsed the OTP it can validate
the password using a very simple process. After confirming that the uid is
correct, it simply makes sure, using the useCtr and sessionCtr, that this
password hasn’t been used before. Each time you power on the Yubikey, the
useCtr is incremented inside the device, then on each button press the
sessionCtr is incremented inside the device. This means that if the useCtr has
incremented, then the server knows this is a new password regardless of the
sessionCtr. If it the same, it checks the sessionCtr to make sure it has
incremented. This means it is a new button press on the same power cycle
(button used more than once without unplugging the device. If neither has
incremented or the useCtr is lower than the last used key, the server knows
this is an old password and it should be rejected.&lt;/p&gt;

&lt;h2 id=&quot;usefulness&quot;&gt;Usefulness&lt;/h2&gt;

&lt;p&gt;It is important to understand what the Yubikey is and what it is not. It is not
a replacement for passwords. It is, however, a useful addition to them. With a
simple password authentication system, passwords can be stolen, guessed, or
known by attackers. If a Yubikey is used, commonly called a second factor of
authentication, the attacker would not only have to guess your password, but
would also have to steal your physical Yubikey. Conversely, if they stole your
Yubikey it would be useless without your password. The two authentication
methods work in concert to provide a stronger guarantee of authenticity than
either could alone.&lt;/p&gt;
</description>
        <pubDate>Wed, 20 Jan 2016 17:35:00 +0000</pubDate>
        <link>https://dyladan.me/abc/2016/01/20/yubikey/</link>
        <guid isPermaLink="true">https://dyladan.me/abc/2016/01/20/yubikey/</guid>
        
        
        <category>abc</category>
        
      </item>
    
      <item>
        <title>Beer Stock Exchange</title>
        <description>&lt;ul&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;S(x)&lt;/code&gt; be the &lt;a href=&quot;https://en.wikipedia.org/wiki/Sigmoid_function&quot;&gt;sigmoid function&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; be the time period between price changes&lt;/li&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p&lt;/code&gt; be the starting price for a given beer.&lt;/li&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;s&lt;/code&gt; be the amount of $ you want to let the price “swing”. E.G a 0.5 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;s&lt;/code&gt; would let a beer that costs $3 base cost from $2.5 to $3.5&lt;/li&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c&lt;/code&gt; be the amount you want to allow any given beer’s x to change in a single trading period (I’m going to use .5).&lt;/li&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;l&lt;/code&gt; be the largest absolute value of the difference between actual sales of each beer and the average sales per beer.&lt;/li&gt;
  &lt;li&gt;Let &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; be the normalizing factor where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a = l/c&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;abusing-the-sigmoid-function-for-fun-and-profit&quot;&gt;Abusing the Sigmoid Function for fun and profit&lt;/h2&gt;

&lt;p&gt;We need to modify our sigmoid function so that we can control its min and max.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Realize &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;S(x)&lt;/code&gt; has a base price of $0.50 with a $0.50 swing.&lt;/li&gt;
  &lt;li&gt;=&amp;gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;S(x)-.5&lt;/code&gt; has a base price of $0 with a $0.50 swing.&lt;/li&gt;
  &lt;li&gt;=&amp;gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2(S(x)-.5)&lt;/code&gt; has a base price of $0 with a $1 swing.&lt;/li&gt;
  &lt;li&gt;=&amp;gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2s * (S(x)-.5) + b&lt;/code&gt; has a base price of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;b&lt;/code&gt; with a swing of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;s&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;description-of-the-algorithm&quot;&gt;Description of the algorithm&lt;/h2&gt;
&lt;p&gt;Start with your list of beers &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[b1,b2,b3,b4,b5]&lt;/code&gt;.At the beginning of the night the price for all beers is its base price (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x=0&lt;/code&gt;)
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0,0,0,0,0]&lt;/code&gt;.
At the end of each trading period, count the number of beers sold in the time period &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[135, 152, 65, 103, 201]&lt;/code&gt;.
Find the average number sold per beer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;131.2&lt;/code&gt;) and find the difference between average and actual number sold for each beer
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[3.8, 20.8, -66.2, -28.2, 69.8]&lt;/code&gt;. Normalize this against your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c&lt;/code&gt; by dividing by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; (139.6) to get &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.03, 0.15, -0.47, -0.20, 0.5]&lt;/code&gt;.
This becomes the change between the old x and the new x for each beer. If you never round, the average x will always be 0, however this
is not feasible so you may want to normalize x every few rounds to make sure your average x stays 0.&lt;/p&gt;
</description>
        <pubDate>Wed, 20 Jan 2016 17:30:00 +0000</pubDate>
        <link>https://dyladan.me/playground/2016/01/20/kbx/</link>
        <guid isPermaLink="true">https://dyladan.me/playground/2016/01/20/kbx/</guid>
        
        
        <category>playground</category>
        
      </item>
    
      <item>
        <title>The Naive Shuffle Algorithm</title>
        <description>&lt;p&gt;Aside from saving time, why are programmers always told not to write code that
has been written for us?  Short answer: you don’t know what you don’t know.&lt;/p&gt;

&lt;p&gt;Imagine you were writing an application in which you needed to shuffle a
string. Instead of looking up the standard library function, you decided to
implement it yourself because a shuffle is a simple piece of code and it would
be quicker to write it than it would be to go to the documentation and find the
right function. Besides, implementing things like this is fun right? Here is a
simple shuffle algorithm.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;join&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;If you can already see the problem with this code then congratulations, you
don’t need to read the rest of this post.  This code works by iterating through
the list and swapping the current element with another random element. If you
are not familiar with shuffle algorithms it may be difficult to see where this
code is broken. The break is so subtle that it may go years without being
detected. First, let’s see what happens when we run it 10000 times.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/unfair_shuffle.png&quot; alt=&quot;png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Looking at this image, it should be clear that the shuffle function is unfairly
favoring some permutations over others. To figure out why, the easiest
explanation requires some basic math.  For any string of length &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt;, there are
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n!&lt;/code&gt; possible permutations. In our naive shuffle algorithm, there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n^n&lt;/code&gt;
possible code paths. This is because at each of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt; elements, there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt;
possible choices for which element to swap it with (including itself).  For the
simple example &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;123&quot;&lt;/code&gt; where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n=3&lt;/code&gt;, there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3^3 = 27&lt;/code&gt; possible code paths.
With &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3! = 6&lt;/code&gt; different possible permutations of the array, it is clear that
each of the 6 possible shuffles cannot be equally represented by 27 code paths,
as 6 does not evenly divide 27.&lt;/p&gt;

&lt;p&gt;The possible permutations are as follows&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;123 132 213 231 312 321
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The possible code paths of the naive algorithms:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;123
 +- 123          - swap 1 and 1 (these are positions,
 |   +- 213      - swap 2 and 1  not numbers)
 |   |   +- 312  - swap 3 and 1
 |   |   +- 231  - swap 3 and 2
 |   |   +- 213  - swap 3 and 3
 |   +- 123      - swap 2 and 2
 |   |   +- 321  - swap 3 and 1
 |   |   +- 132  - swap 3 and 2
 |   |   +- 123  - swap 3 and 3
 |   +- 132      - swap 2 and 3
 |       +- 231  - swap 3 and 1
 |       +- 123  - swap 3 and 2
 |       +- 132  - swap 3 and 3
 +- 213          - swap 1 and 2
 |   +- 123      - swap 2 and 1
 |   |   +- 321  - swap 3 and 1
 |   |   +- 132  - swap 3 and 2
 |   |   +- 123  - swap 3 and 3
 |   +- 213      - swap 2 and 2
 |   |   +- 312  - swap 3 and 1
 |   |   +- 231  - swap 3 and 2
 |   |   +- 213  - swap 3 and 3
 |   +- 231      - swap 2 and 3
 |       +- 132  - swap 3 and 1
 |       +- 213  - swap 3 and 2
 |       +- 231  - swap 3 and 3
 +- 321          - swap 1 and 3
     +- 231      - swap 2 and 1
     |   +- 132  - swap 3 and 1
     |   +- 213  - swap 3 and 2
     |   +- 231  - swap 3 and 3
     +- 321      - swap 2 and 2
     |   +- 123  - swap 3 and 1
     |   +- 312  - swap 3 and 2
     |   +- 321  - swap 3 and 3
     +- 312      - swap 2 and 3
         +- 213  - swap 3 and 1
         +- 321  - swap 3 and 2
         +- 312  - swap 3 and 3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;It is easy to see that 123 is possible 4 times and 132 is possible 5 times out
of the 27 code paths. Assuming a good rng (all paths are equally likely), this
means 132 is more likely to be output than 123. Now let’s see the Fisher-Yates
shuffle algorithm.  It is &lt;em&gt;almost&lt;/em&gt; the same as our naive algorithm, but for one
simple change. As it iterates through the list, at each element it chooses a
random &lt;em&gt;later&lt;/em&gt; element (or itself) rather than just choosing a random element.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fisheryates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;join&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Intuitively, it would seem that this algorithm is less random. Wouldn’t it be
worse to limit yourself to only swapping with later elements? Let’s test this
algorithm the same way we tested our naive algorithm.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/fair_shuffle.png&quot; alt=&quot;png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;As seen in the example above, the output of this function is much more fair.
To see why this is, let’s go through the same math we did before.  For the
Fisher-Yates algorithm, let’s figure out how many possible code paths there
are.  At the first element, there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt; possible choices (all elements in the
array), at the second element, there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n-1&lt;/code&gt; possible choices (ignore all
earlier elements), continue this all the way until the last element.  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n *
(n-1) * (n-2) * (n-3) * ... * 2 * 1 = n!&lt;/code&gt;, which leaves us with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n!&lt;/code&gt; possible
code paths.  This is encouraging since it is the same number of possible
permutations, therefore it is at least &lt;em&gt;possible&lt;/em&gt; that every output is equally
likely. This is a strong improvement over &lt;em&gt;impossible&lt;/em&gt;.  For the simple example
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;123&quot;&lt;/code&gt; where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n=3&lt;/code&gt;, there are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3! = 3*2*1 = 6&lt;/code&gt; possible code paths.  With &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3!
= 6&lt;/code&gt; different possible permutations of the array, it is clear that 6 divides 6
and the algorithm is not yet proven broken as it was for the naive algorithm.&lt;/p&gt;

&lt;p&gt;The possible permutations are as follows&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;123 132 213 231 312 321
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The possible code paths of the Fisher-Yates algorithms:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;123
 +- 123          - swap 1 and 1
 |   +- 123      - swap 2 and 2
 |   +- 132      - swap 2 and 3
 |
 +- 213          - swap 1 and 2
 |   +- 213      - swap 2 and 2
 |   +- 231      - swap 2 and 3
 |
 +- 321          - swap 1 and 3
     +- 321      - swap 2 and 2
     +- 312      - swap 2 and 3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;It is easy to see that every possible output shows up once and is therefore
(assuming a good rng) equally likely.&lt;/p&gt;

&lt;p&gt;Download the code as a Jupyter notebook  &lt;a href=&quot;/assets/fisheryates.ipynb&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
</description>
        <pubDate>Wed, 20 Jan 2016 17:26:39 +0000</pubDate>
        <link>https://dyladan.me/abc/2016/01/20/shuffle/</link>
        <guid isPermaLink="true">https://dyladan.me/abc/2016/01/20/shuffle/</guid>
        
        
        <category>abc</category>
        
      </item>
    
      <item>
        <title>Understanding Bike Frame Geometry</title>
        <description>&lt;p&gt;Frames are a frequently misunderstood part of buying a bike.
There are tons of measurements and nobody seems to know what
they all do. If I tell you a bike has a 625mm effective top
tube, 38.1mm rake, 71.0 head tube angle, 423mm chainstay,
and 74mm trail, would you be able to tell me the handling
characteristics of that bike? I thought not. The simple truth
is that nobody really can. Some people know more about what
each of these measurements mean than others, but the only way
to know for sure how a bike is going to ride is to ride it.
That being said, there are a few simple things to look for
when looking for a bike frame.&lt;/p&gt;

&lt;h2 id=&quot;trail&quot;&gt;Trail&lt;/h2&gt;

&lt;p&gt;Trail is frequently quoted as being the composite of the rake
and head tube angle. It’s ok, I didn’t really know what that
means either. The easier way to think of it is the amount that
the wheel “trails” behind the forks.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/FGEOM.jpg&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A general rule of thumb is that a large trail will give you
more high speed stability but will not allow tight cornering.
A short trail will allow more responsive turning at the expense
of stability. A lot of manufacturers don’t give trail
as a measurement but instead give you only angle and rake.
Using angle and rake, trail can be calculated using a
&lt;a href=&quot;http://yojimg.net/bike/web_tools/trailcalc.php&quot;&gt;calculator&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Long trail gives high speed stability&lt;/li&gt;
  &lt;li&gt;Short trail allows more agility&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bottom-bracket-height&quot;&gt;Bottom Bracket Height&lt;/h2&gt;

&lt;p&gt;The bottom bracket height mostly affects stability and
balance. A lower bottom bracket means a lower center of gravity
and a more stable riding position. The tradeoff is that
a bottom bracket that is too low can cause issues with ground
clearance and pedals may hit the ground in turns. Bottom bracket
height comes down to preference. Some riders like a lower 12”
bracket because they like the low center of gravity, while
others want 13.5” because they want to be able to pedal through
turns without worrying about hitting the ground.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Low bottom bracket is more stable&lt;/li&gt;
  &lt;li&gt;High bottom bracket gives more obstacle clearance&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;chainstay-length&quot;&gt;Chainstay length&lt;/h2&gt;

&lt;p&gt;The effect of the chainstay length is one of the most important
factors when talking about the characteristics of a bike frame.
Chainstay length affects the weight distribution, wheelbase,
and rigidity of a bike frame.&lt;/p&gt;

&lt;p&gt;Proper weight distribution will cause the rider to feel more
stable on downhills, and faster on uphills because the rear tire
won’t slip and the front tire will stay solidly connected to
the ground. Longer chainstays allow the rider to put weight on the
rear tire without fear of the front tire lifting off the ground.
A chainstay that is too long, however, will make it difficult to
put enough weight on the rear tire and allow it to slip.&lt;/p&gt;

&lt;p&gt;Chainstays most obviously affects wheelbase. A longer wheelbase
will feel more stable, especially at high speeds. A short wheelbase
will feel lighter and more agile in techinical turning sections.
This is really up to the preference of the rider.&lt;/p&gt;

&lt;p&gt;The final thing a chainstay affects is rigidity. A more rigid
chainstay will more efficiently transfer energy from the pedals
to the ground. Generally, shorter chainstays are more rigid.
Long chainstays have more leverage and flex more, absorbing more
energy. These days, materials exist to allow for long chainstays
that are still very rigid, however this will make them heavier
and more expensive.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Long chainstays allow more stability and faster climbing&lt;/li&gt;
  &lt;li&gt;Short chainstays allow faster turning and more rigid frames&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 21 Jul 2015 22:23:51 +0000</pubDate>
        <link>https://dyladan.me/playground/2015/07/21/bike-frames/</link>
        <guid isPermaLink="true">https://dyladan.me/playground/2015/07/21/bike-frames/</guid>
        
        
        <category>playground</category>
        
      </item>
    
  </channel>
</rss>
