<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tamás Kornai on Medium]]></title>
        <description><![CDATA[Stories by Tamás Kornai on Medium]]></description>
        <link>https://medium.com/@tkornai?source=rss-79d5e58567aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1-RiK-Vo_iOg77gP.jpg</url>
            <title>Stories by Tamás Kornai on Medium</title>
            <link>https://medium.com/@tkornai?source=rss-79d5e58567aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:41:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tkornai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Kubernetes crime story]]></title>
            <link>https://medium.com/prezi-engineering/https-engineering-prezi-com-a-kubernetes-crime-story-2e8d75a77630?source=rss-79d5e58567aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e8d75a77630</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[nat]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Tamás Kornai]]></dc:creator>
            <pubDate>Thu, 03 Oct 2019 15:49:27 GMT</pubDate>
            <atom:updated>2019-10-03T15:49:27.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>The crime</h3><p>The problem with having a great monitoring system is that you notice problems you couldn’t notice before. This is exactly what happened to us when we migrated our Nginx based reverse proxy to Kubernetes: we noticed that tail latency (p99) got somewhat higher for a few of our services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9MIqztQONHdZaSLz6SutQ.png" /><figcaption>Increased p99 latencies start on 7/24</figcaption></figure><p>In the past, we monitored the average response times. As the latency bump only affected the tail end, we’d most certainly have missed this issue. But with the awesome monitoring we have today we fired alerts on it. So now we had a problem to solve. Thanks, Prometheus!</p><h3>The investigation</h3><p>Higher tail latencies were visible for services that do many sequential service-to-service calls. We could reproduce the issue with stress testing, but we had absolutely no clue for what might have caused it. The only change we did was that we started to run the reverse proxy on shared Kubernetes worker nodes instead of dedicated ElasticBeanstalk machines. They were the same containers in similar private VPC subnets consuming about the same amount of resources.</p><p>So what can you do in a case like this? Our idea was to extend our investigation toolkit and introduce tracing so we can better understand why long requests take long. The easiest way seemed to be to integrate with AWS X-Ray, and we were not disappointed: after about two days we had traces flowing in.</p><p>And the slow traces looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzFDbFpAqA9vGkmGh846aQ.png" /><figcaption>A trace showing a 1.3 second duration</figcaption></figure><p>This is the call sequence:</p><blockquote>smartgateway → prezipage → smartgateway → presentationservice</blockquote><p>Smartgateway is the above mentioned reverse proxy. The first request on smartgateway is a user request, whereas the second is a service-to-service call from prezipage to presentationservice. In our current architecture service-to-service remote calls are also passing through the proxy.</p><p>For some reason, it took a full second for the remote call to get from smartgateway to presentationservice. Once the request appeared on presentationservice it only took 12.8 ms to serve it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TV-YvcfPlSUYTM8hHLXmw.png" /><figcaption>This is a segment from the same trace from above. Presentationservice itself answered quickly.</figcaption></figure><p>Interestingly enough, the delay was always exactly 1 second or (less frequently) 3 seconds. We wanted to further validate that it is the build-up of the outgoing TCP connection that takes long. So we introduced a custom attribute on the traces that took the value of <em>$upstream_connect_time</em> from <a href="http://nginx.org/en/docs/http/ngx_http_upstream_module.html#variables">http://nginx.org/en/docs/http/ngx_http_upstream_module.html#variables</a>. As it turned out, the assumption was valid, we could observe the expected upstream connection time delays.</p><h3>The offender</h3><p>At this point, we felt that we are onto something and turned to google for more pointers. Luckily enough, the search term “kubernetes slow outgoing connections” returns this great article as the first result: <a href="https://tech.xing.com/a-reason-for-unexplained-connection-timeouts-on-kubernetes-docker-abd041cf7e02">https://tech.xing.com/a-reason-for-unexplained-connection-timeouts-on-kubernetes-docker-abd041cf7e02</a></p><p>In this post, the author explains how they tracked down a timeout issue with the exact same characteristics. It’s a great read with crystal clear explanations, so you should go and read it. We will wait here until you do.</p><h3>The verdict</h3><p>So welcome back!</p><p>I trust you have read the article, but let me just give a very short and high-level summary. When a pod has to connect to an external service (by external I mean a service with a public IP), the outgoing packet will need to go through a source network address translation (SNAT) operation. By default, this is happening on the worker node, configured by iptables rules. There is a race condition in the underlying Netfilter module though. Sometimes SYN packages are dropped when we try to insert new connection tuples into the conntrack table, leading to 1 or 3 seconds connection timeouts. (If the previous few sentences did not make sense, then reading the referenced article one more time might be a good idea.)</p><p>So let’s discuss how our problem was different.</p><p>We are using AWS EKS, so the networking stack is different from what is described in the article. The proposed solution to change the port allocation algorithm to fully-random is unfortunately not yet available on EKS. The <a href="https://github.com/aws/amazon-vpc-cni-k8s">amazon-vpc-cni-k8s</a> plugin does support that setting:</p><blockquote>AWS_VPC_K8S_CNI_RANDOMIZESNAT=prng</blockquote><p>But unfortunately, the iptables version that comes with the official AMI does not. Luckily there is another option that we can use:</p><blockquote>AWS_VPC_K8S_CNI_EXTERNALSNAT=true</blockquote><p>With that option, we can turn off SNAT altogether on the node. You can read the slightly misleading documentation <a href="https://docs.aws.amazon.com/eks/latest/userguide/external-snat.html">here</a>.</p><p>Why is it misleading? There is an open PR explaining it: <a href="https://github.com/awsdocs/amazon-eks-user-guide/pull/53">https://github.com/awsdocs/amazon-eks-user-guide/pull/53</a></p><h3>The redemption</h3><p>After we applied the <em>AWS_VPC_K8S_CNI_EXTERNALSNAT</em> environment variable on 8/15, latency numbers returned to the baseline that we had before the reverse proxy migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CKL3O2TzyGerEfBe4Asrw.png" /><figcaption>Latencies normalizing after 8/15</figcaption></figure><p>(One can observe some latency improvements from 8/10. This was happening because we just threw more resources at the problem. We started more pods on more nodes for the service so a single pod got less traffic hence making the concurrency issue less frequent.)</p><h3>The moral of the story</h3><p>Observability is key when debugging a complex system, like Kubernetes. By adding tracing we could better understand the characteristics of slow requests. With that information at hand, we got very close to the root of the problem: we just needed a single lucky search query and a great article explaining what we are staring at. For the actual solution, we still had to wrap our head around how SNAT works, dive deep into Amazon Kubernetes (EKS) internals and understand the role of what the amazon-vpc-cni-k8s plugin plays. Hopefully, with the solution provided above and with the yet-to-be-improved documentation, we can help some fellow engineers on their Kubernetes journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e8d75a77630" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prezi-engineering/https-engineering-prezi-com-a-kubernetes-crime-story-2e8d75a77630">A Kubernetes crime story</a> was originally published in <a href="https://medium.com/prezi-engineering">Prezi Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prometheus Unchained]]></title>
            <link>https://medium.com/prezi-engineering/prometheus-unchained-331b7ab8737?source=rss-79d5e58567aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/331b7ab8737</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tamás Kornai]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 00:57:52 GMT</pubDate>
            <atom:updated>2019-07-06T08:40:11.045Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a war story about a leaky abstraction and it takes us on a journey through several layers of technology: we’ll start with Grafana and Prometheus, touch Django, Gunicorn, Python and — spoiler alert — wrap up with C.</p><p>A big shout-out is due to <a href="https://github.com/davidguerreroprezi">David Guerrero</a> who did the bulk of this investigation.</p><h3>The Set</h3><p>Prezi is building its new monitoring stack on Prometheus. So far our experience is good: it’s fast, it’s stable and it’s scaling well. But we are primarily a Python/Django house — and they are not yet first-class citizens in the Prometheus world. That world is ruled by Go.</p><p>To use a mixed metaphor: by going a bit off-road we quickly hit a roadblock.</p><h3>The Spike</h3><p>So we already had a few services instrumented, Prometheus was happily scraping metrics and we had a generic Grafana dashboard set up for <a href="https://www.weave.works/blog/the-red-method-key-metrics-for-microservices-architecture/">RED metrics</a>. When we suddenly spotted something unexpected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nJikjxIjvMHmXcXh" /></figure><p>That is that nasty spike for status codes around 22:14. This is not what we wanted to see there. Because this is what we wanted to see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMYruEugiR3P3034" /></figure><blockquote>Two different dashboards?</blockquote><blockquote>Wait a minute! How come you have a good graph and a bad graph? Well, it’s easy: we have two Prometheus instances scraping (fancy Prometheus lingo for collecting) data from each instrumented service for high availability. One instance is showing the good data, only the other one was bogus. If you refresh Grafana, you will either get the data from one or the other.</blockquote><p>So where does this spike come from? Let’s examine the source data. This is how the given graph is defined:</p><pre>environment_name_code:service_http_requests:rate30s{<br>  environment_name=~&quot;${environment_name:regex}&quot;<br>}</pre><p>Where environment_name_code:service_http_requests:rate30s is a recording rule that stands for:</p><pre>sum by(environment_name, service_name, code) (<br>  rate(django_http_responses_total_by_status{<br>    code=~&quot;.+&quot;,<br>    environment_name=~&quot;.+&quot;<br>  }[30s])<br>)</pre><blockquote>About recording rules</blockquote><blockquote>But what is a Prometheus recording rule? For the sake of this discussion, we can think of them as (probably time consuming) calculations that are periodically executed by Prometheus and their results are stored. So if we want to show the results on dashboards we only need to execute the expensive calculation once.</blockquote><p>So let’s check the source data for django_http_response_total_by_status{code=&quot;200&quot;}:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fLf6jH6VgFPXA6B-" /></figure><p>Hah! There it is! Prometheus is showing UTC, so it’s 20:14, and it’s not a spike but a deep and narrow pit. It only became a spike because of the recording rule. When Prometheus calculates rate from a counter value, it expects that consecutive values are always just getting higher, never lower. The only time it can get lower is when there is a reset (e.g. process restart). A reset means that we start over counting from 0. Prometheus thinks that we suddenly jumped from 0 to a big number, hence the spike!</p><p>Anyway, we can see that there was an intermittent value error for one counter on one instance, let’s track down what caused it.</p><h3>Multiprocessing</h3><p>Let’s cover the basics quickly. How can we serve more parallel requests on a single server with the famously single-threaded Python? The answer is two-fold. First, we use Gunicorn as the application server, which forks multiple (in our example four) parallel processes and distributes incoming requests between those processes. Second, each process is using the <a href="http://www.gevent.org/">gevent</a> lib, which is almost like threading: when there is a blocking IO happening during request handling then execution can be yielded to another request.</p><p>Luckily we don’t need to care about the second, it’s only multiprocessing that’s important for this discussion.</p><p>The way Prometheus scrapes data is that it periodically calls the /metrics endpoint for each service node. But we have multiple processes running, how can we keep shared counters (<a href="https://prometheus.io/docs/concepts/metric_types/">or gauges or histograms</a>) for them? The <a href="https://github.com/korfuri/django-prometheus">django-prometheus</a> lib (that we used until we forked it to <a href="https://github.com/prezi/django-exporter">django-exporter</a>) offers two <a href="https://github.com/prezi/django-exporter/blob/master/documentation/exports.md">solutions</a>. One is to have a per process /metrics endpoint on different ports, the other is to have it exported for the multiple processes globally. We are using the second approach, as figuring out what is the port-range that we should scrape for metrics is a harder problem (the number of Gunicorn processes depends on the number of cores a node has, which is unknown in advance in the era of ephemeral spot instances).</p><p>But how is the second approach actually implemented? For that, we have to look into the <a href="https://github.com/prometheus/client_python">prometheus/client_python</a> lib (that is used by the django-prometheus lib). The answer is in multiprocess.py. Each process is storing its metrics in memory mapped files and when we collect them, the metrics are just <a href="https://github.com/prometheus/client_python/blob/18017c62a282bf3fb275aaee6564fb2248c85a8d/prometheus_client/multiprocess.py#L27">merged from those files</a>.</p><h3>Reproducing the issue</h3><p>Arguably the most important part of this whole investigation was when David managed to reproduce the issue, by copying the relevant parts of the <a href="https://github.com/prometheus/client_python/blob/8586b8de002eb8dd0aff27d9b43a06f56a57ebcb/prometheus_client/core.py">source file</a>.</p><p>The script is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ba3433db5badc8daf286efd4e5ee06/href">https://medium.com/media/d2ba3433db5badc8daf286efd4e5ee06/href</a></iframe><p>If you run it in two copies, one with the--writer flag, you will see some output like this from the reader process:</p><pre>(-3262.0, 0.0, 3262.0)<br>(3264.0, 3264.0, 0.0)<br>(-3382.0, 0.0, 3382.0)<br>(3384.0, 3384.0, 0.0)<br>(-4059.0, 0.0, 4059.0)<br>(4062.0, 4062.0, 0.0)<br>(-4477.0, 0.0, 4477.0)<br>(4478.0, 4478.0, 0.0)</pre><p>Which tells us that whenever we read the wrong value, it isn’t an arbitrary number but always 0. Based on that, our first idea was to introduce some special value for 0 (namely b&#39;\xff\x00\x00\x00\x00\x00\xff\xff&#39;, an invalid 64 bit double value in the IEEE-754 standard) and whenever we read an actual 0 we just retry the read. This was working okay-ish, the problem was patched around.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59c16c95830262a0fc179e8d7c8c70ca/href">https://medium.com/media/59c16c95830262a0fc179e8d7c8c70ca/href</a></iframe><p>But then we started to experiment and noticed something very strange. The code was never actually hitting the read retry branch. From the full changeset it was enough to just redefine _pack_double as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/133342fa5523df722e18751839d97e21/href">https://medium.com/media/133342fa5523df722e18751839d97e21/href</a></iframe><p>Just with that simple change, the issue went away.</p><p>I’d suggest spending a few minutes thinking about why. The answer is below.</p><blockquote>Who is the murderer?</blockquote><blockquote>I believe the solution is that the assignment operator is atomic, so if we calculate the packed value first and then assign it to the buffer, everything works as expected.</blockquote><blockquote>But when we call the struct.pack_into() function, there is a short period when the buffer is set to 0:</blockquote><blockquote><a href="https://github.com/python/cpython/blob/48c8bf21f97aeb124dbd48bf2bdec1ab4ebc5202/Modules/_struct.c#L1563">https://github.com/python/cpython/blob/48c8bf21f97aeb124dbd48bf2bdec1ab4ebc5202/Modules/_struct.c#L1563</a></blockquote><blockquote>There goes the leaky abstraction.</blockquote><blockquote>The fix is merged upstream: <a href="https://github.com/prometheus/client_python/pull/315">https://github.com/prometheus/client_python/pull/315</a></blockquote><p>That’s all folks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=331b7ab8737" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prezi-engineering/prometheus-unchained-331b7ab8737">Prometheus Unchained</a> was originally published in <a href="https://medium.com/prezi-engineering">Prezi Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>