<?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 Jacek Domagalski on Medium]]></title>
        <description><![CDATA[Stories by Jacek Domagalski on Medium]]></description>
        <link>https://medium.com/@domagalski-j?source=rss-e92c114e9195------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BIR4ruEPEHlQtxPfxYxwWQ.png</url>
            <title>Stories by Jacek Domagalski on Medium</title>
            <link>https://medium.com/@domagalski-j?source=rss-e92c114e9195------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:51:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@domagalski-j/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[AWS ALB returns 503 for Istio enabled pods]]></title>
            <link>https://domagalski-j.medium.com/aws-alb-returns-503-for-istio-enabled-pods-a6942383143c?source=rss-e92c114e9195------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6942383143c</guid>
            <dc:creator><![CDATA[Jacek Domagalski]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 16:21:21 GMT</pubDate>
            <atom:updated>2025-10-16T09:08:16.642Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying a service mesh solution like Istio in the Kubernetes cluster brings many benefits, however it increases the complexity of the entire setup and makes troubleshooting of potential issues more difficult than before. One of the most common problems people experience after adding an Istio sidecar to the cluster are 5xx errors. I can’t count the amount of different articles, blog posts or github issues flying around that tries to address 500 errors with Istio. The point is that there is no silver bullet to eliminate those errors, as different scenarios require different mitigation techniques. This article will cover one of the issues we experience for services that were Istio sidecar enabled and were exposed directly via AWS Application Load Balancer.</p><h3>TL;DR;</h3><p>Even if Istio documentation doesn’t mention that istio ingress gateway is a mandatory component in the mesh, I highly recommend to add it if you use AWS load balancer controller. AWS ALB is a component that resides outside of the Kubernetes cluster and doesn’t follow the state of the pods — it continues to send a traffic to a istio-proxy sidecar even if the pod gets into “Terminating” state. As a result 503 errors can be observed.</p><h3>SETUP</h3><p>Before I describe what the issue was, let’s take a look at the following diagram to understand the testing scenario. We used “echo” application which is just a silly http service. The deployment of an “echo” contains 2 replicas and a service of NodePort type. To expose the service we used <a href="https://github.com/kubernetes-sigs/aws-load-balancer-controller">AWS load balancer controller</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgBVmkyzaE0UETZJWiUD3A.png" /></figure><p>Istio service mesh contains various components, Istio Ingress Gateway being one of them. Nevertheless it’s not included in the presented scenario, so let me elaborate on why this piece of the puzzle is missing. <br>First of all, Istio ingress gateway is not a mandatory component and non of the Istio best practices documentation clearly says it should be used to forward ingress traffic. Yes, it would bring all the cool features of Istio at the edge of your cluster, but it’s not mandatory to install it. <br>Secondly, migrating to the Istio service mesh is a complex process which should be approached on a step by step basis. It’s much easier to enable Istio sidecar for the given pods as the first migration step, and then switch the traffic to the Istio ingress gateway at the next phase. And this is exactly the moment when you may encounter the issues.</p><h3>Into the details</h3><h4>HTTP connection flow</h4><p>Let’s take a look at a diagram presenting how HTTP connection works in the described setup.</p><blockquote>Using plain HTTP instead of HTTPS between ALB and k8s pods is definitely not the best practice, however I used it for the purposes of this article, as it helps to demonstrate the whole concept.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKFnhN9O2im74mz97uyOpQ.png" /></figure><p>As AWS ALB is a Layer 7 proxy, it terminates a HTTP request to perform various operations like a TLS certificate validation, adding custom headers (e.g. x-forwarded-for) and route traffic to an appropriate destination. Once HTTP request from a client is processed, ALB establishes upstream TCP connection to forward traffic towards the destination. My point is to highlight the fact that HTTP session between a client and ALB is independent from the connection established between ALB and a k8s pod. <br>When Istio sidecar is enabled, it modifies iptables rules of the k8s node in such a way that traffic addressed to the application container is intercepted by Istio, also Istio runs Envoy in the background which is another Layer 7 proxy so TCP connection between ALB and Envoy is established. The last step is to establish connectivity between Envoy and the application that runs in the main container of the pod — in our case an “echo” app. <br>As a result when client sends a HTTP request, 3 separate connections are established (each of them marked with a different color on the diagram above)— one between a user and ALB, second between ALB and the sidecar (Envoy proxy) and last between sidecar and application running in the main container.</p><h4>Reveal the issue</h4><p>To be able to simulate user traffic and visualize the problem I used <a href="https://locust.io/">Locust</a>. I started the stress tests and restarted the deployment (containing 2 pods) of an echo app. The results are presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aURhIIAg2_HsuTbVskjThg.png" /></figure><p>503 errors start to occur exactly when I restarted the deployment. The first thought I had was to double check if an “echo” app performs a graceful shutdown on receiving the SIGTERM- it did. Next, I decided to verify if Istio is the component responsible for that unexpected behaviour. The test couldn’t be any simpler — I disabled the Istio sidecar on an echo app and run Locust test one more time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*5P_g2ayb8OF5r5HB37qLaA.png" /></figure><p>This time no 503 errors. So why does the Istio break the connection between client and application during the deployment process?</p><h4>Pod termination process</h4><p>A prerequisite to understand the issue is to know exactly what happens when a pod is being terminated during the redeployment process. <a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace">This great article from google</a> explains it in more details. As you can see the first step of a termination process is to exclude the terminating pod from the endpoint list of the corresponding service, so no traffic is redirected to that pod any more. If this is true, why can we see such a high number of 503 errors when the pod is being deleted? Why are the requests from ALB being redirected by the k8s nodes to the pod that is in a termination state?</p><h4>HTTP Connection persistence</h4><p>If we would go back to early ages of HTTP 1.0 adoption, the process of sending and receiving the HTTP would look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*rF6fP2ZNH91cl8SwOdGWuw.png" /><figcaption><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x">https://developer.mozilla.org/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x</a></figcaption></figure><p>Every HTTP session would have its own TCP connection — once the HTTP response is delivered the TCP connection is closed. Another HTTP request opens a new TCP connection and so on and so forth. <br>If that’s the case, then in our scenario every request from the user would establish a new TCP session to ALB, then load balancer would open a new TCP session to the Istio proxy and finally, Istio would establish a session with an echo app so the HTTP request is delivered. In that sequence of events there is no room for 503 errors, because when ALB tries to open a new TCP session, traffic gets redirected by k8s nodes only to the healthy echo pods — terminating pod is not on the endpoint list so it can’t participate in the selection process of the destination target. <br>But things have changed since HTTP 1.0.</p><p>HTTP 1.1 introduced the concept of connection persistence, which is the default in this HTTP standard. What it means is that the source and the destination establish a TCP connection upon sending a HTTP request. After a HTTP response is delivered to the source, the connection is kept open waiting for more HTTP traffic. The connection is closed once there is no more HTTP traffic and an idle time expiries. An idle time varies between different implementations e.g. Envoy uses 60min for TCP idle timeout as the default. <br>This mechanism increases the performance by eliminating the need of establishing and tearing down the TCP connection for every single HTTP request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*2wOf6m75z2Y5fbNiTbxnog.png" /><figcaption><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x">https://developer.mozilla.org/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x</a></figcaption></figure><p>In fact, multiple TCP connections between source and destination can be opened at the same time, creating a so called “connection pool”. Consider the diagram below to see how a TCP connection pool may look like in our scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNpGRMDpL8JqPeAbucSWDA.png" /></figure><p>Different colours of TCP pipes suggest that all the TCP connections between client and ALB, ALB and Envoy, Envoy and an application are independent of each other. Those connections are established and kept open to be reused for next HTTP session.</p><p>In our scenario, when a new HTTP request arrives to an ALB, and the TCP connection from an ALB to istio-proxy sidecar is already present, the process of selecting a healthy pod from the endpoint list of particular services doesn’t occur — the connection is already there and will be used to forward the HTTP traffic. Selecting the pod / endpoint happens only during the establishing of a new TCP connection.</p><p>If the above is true, then regardless whether an Istio is in use or not, how can any HTTP application perform a graceful termination process while TCP connections from the clients are open and the HTTP traffic is constantly flowing?<br> Stopping any HTTP service requires the mechanism which tells the other side of the wire that it should close all the TCP connections and establish the new ones if needed, as the service will stop operating very soon.</p><h4>Graceful shutdown and HTTP Connection: Close</h4><p>What graceful shutdown of a web application does, amongst others things, is to leverage the “HTTP Connection: Close” header to notify the client that the TCP connection will be terminated. This forces the client to establish a new connection. Establishing a totally new end to end TCP connection would solve our problem, if an AWS ALB established a new connection to an echo pod for the first request that arrives from the client to ALB after the pod started the termination process, it wouldn’t hit the terminating pod as it wasn’t on the kubernetes endpoint list any more. However, in our case, sending the “HTTP Connection: Close” header by an echo app doesn’t necessarily mean the user or ALB closes the connection to the pod that the message originated from. The HTTP standard defines a concept of hop-by-hop headers explained in <a href="https://nathandavison.com/blog/abusing-http-hop-by-hop-request-headers">this article</a>. The “Connection” header is treated as a hop-by-hop header which means that the Layer 7 proxy won’t propagate this header downstream. This is at least how the Envoy behaves — see <a href="https://github.com/envoyproxy/envoy/issues/14910">corresponding discussion on github</a>.</p><p>This explains why the setup without Istio sidecar works as expected — the pod goes into the termination state and the pod is removed from the endpoint list, then the application running in the container starts to send the “Connection: Close” HTTP headers that reaches AWS ALB. The load balancer closes all the connections that it gets “Connection: Close” for and it starts to establish new connections. As a result the new TCP connection is forwarded to another, healthy pod which is present on the k8s endpoint list — this way the user won’t see any 503 errors on his side.</p><p>When Istio sidecar is added to the picture, an application sending the “HTTP Connection: Close” headers reaches the Envoy first. At this stage Envoy will start the termination of the TCP connection between itself and the application, however it won’t pass the “Connection: Close” further to AWS ALB. As a result the connection between AWS ALB and the Envoy remains open and the HTTP requests from the user arrives to the ALB, eventually reaching the Istio sidecar proxy of a terminating pod. At this stage the connections between application and Envoy are being terminated and Envoy can’t establish new TCP connections to the echo app (graceful shutdown of the web application disables the ability to accept any new connections). As the traffic can’t reach the main container, an Envoy returns a 503 to the ALB and that’s how the end user sees the errors. <br>Once the application finishes sending the “HTTP Connection: Close” and terminates all the TCP connections to an Envoy, Istio sidecar starts its own graceful shutdown process (holding off termination of istio sidecar is not the default setting of the Istio mesh— see the “Bonus section” at the end of the article to get more details about this). At this stage Istio sidecar terminates all the connections to the ALB, once this is completed, ALB must establish new connections to the echo service, selecting only the healthy pods. When all the connections between ALB and an Istio sidecar are terminated, the client stops getting 503 errors and the traffic is back to normal.</p><h3>SOLUTION</h3><p>The problem may be solved by hiding an application behind the Istio Ingress Gateway. The Istio Ingress Gateway is a set of additional Envoy proxies deployed in their own pods, that accept the traffic from AWS ALB. The diagram below represents the setup with Istio ingress gateways in use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K96NA59_Sox0EgghREe-0Q.png" /></figure><p>The key to see how this helps to solve the issue is to understand how an Envoy processes each HTTP request it receives. You may find the detailed description in <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/life_of_a_request">Envoy docs</a>, however the key takeaway is highlighted below:</p><blockquote>The most important HTTP filter is the router filter which sits at the end of the HTTP filter chain. When decodeHeaders is invoked on the router filter, the route is selected and a cluster is picked. The request headers on the stream are forwarded to an upstream endpoint in that cluster. The <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/http_routing#arch-overview-http-routing">router</a> filter obtains an HTTP <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/connection_pooling#arch-overview-conn-pool">connection pool</a> from the cluster manager for the matched cluster to do this.</blockquote><blockquote>Cluster specific <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/overview#arch-overview-load-balancing">load balancing</a> is performed to find an endpoint. The cluster’s circuit breakers are checked to determine if a new stream is allowed. A new connection to the endpoint is created if the endpoint’s connection pool is empty or lacks capacity.</blockquote><p>In other words, when a HTTP request is sent by the ALB and received by an Envoy (ingress gateway), at the end of the packet processing, Envoy <strong>will check the list of the endpoints that it can forward the request to</strong>. This is the key difference between the ALB sending a HTTP request to the pod and the Envoy (ingress gateway) sending the same request. An Envoy is a component that sits in the k8s cluster and it constantly tracks the list of the endpoints for each service. The moment when a pod enters a termination state and is removed from the k8s endpoint list, the Envoy removes it from its list of endpoints as well. And remember, this happens before the application goes into a graceful shutdown. As a result, the first HTTP request that arrives to the Istio Ingress Gateway after the application pod starts its termination process, is redirected to the healthy pods that belong to the service of our application, resulting in a lack of 503 errors.</p><h4>Istio Ingress Gateway termination</h4><p>The obvious question that comes to a mind is: <br>“Doesn’t the presented solution shift the issue from an application pod to the ingress gateway pod and what will happen during the deployment of Istio Ingress Gateway?” <br>The “Bonus section” at the end of this article explains why the Istio acting as a sidecar should hold off its own graceful shutdown until the main container exits properly. But with an Istio Ingress Gateway this is not the case — there is no sidecar. Envoy is a main container and doesn’t need to wait for the other containers to exit. Upon receiving the SIGTERM it immediately starts the graceful shutdown, closing the upstream and downstream connections at the same time. Since the TCP connections to the ALB got terminated, the ALB must use the connection pool to the healthy pods or establish a new connection upon receiving HTTP traffic from the user. Doing so is only possible with the pods available on the k8s endpoint list and at this point the terminating Istio ingress pod is not there anymore.</p><p>To sum up, even if the Istio Ingress Gateway is not a mandatory component in the Istio service mesh, I would highly recommend to use it if any HTTP proxy is deployed in front of the Kubernetes cluster.</p><h3>Bonus section</h3><h4>Why does the Istio sidecar hold off its graceful shutdown?</h4><p>When a pod is getting terminated, all the containers running in a pod gets a SIGTERM a the same time. If an Istio sidecar is enabled on the pod this behavior may be another root cause of the errors. If an Envoy exits before the application container, the application may not finish sending HTTP responses or some other in-progress operations as expected. That’s why it’s important to force Istio to wait until an application container in the pod finishes its graceful shutdown first. A full description of this scenario and its possible solutions is beyond the scope of this article. To read more about Istio termination order, follow <a href="https://github.com/istio/istio/issues/7136">this github discussion</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6942383143c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Istio rate limits for egress traffic]]></title>
            <link>https://domagalski-j.medium.com/istio-rate-limits-for-egress-traffic-8697df490f68?source=rss-e92c114e9195------2</link>
            <guid isPermaLink="false">https://medium.com/p/8697df490f68</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[rate-limit]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[istio]]></category>
            <dc:creator><![CDATA[Jacek Domagalski]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 15:19:14 GMT</pubDate>
            <atom:updated>2021-05-27T08:36:11.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTvsbt1czskCIYEP8twapQ.jpeg" /></figure><blockquote>This post has been edited and adjusted according to the changes in EnvoyFilter object in Istio 1.7. See <a href="https://istio.io/latest/news/releases/1.7.x/announcing-1.7/upgrade-notes/?_ga=2.56158499.968618608.1605035628-542410480.1587540472#envoyfilter-syntax-change">release notes</a> and corresponding <a href="https://discuss.istio.io/t/envoyproxy-rate-limit-not-working-in-istio-1-7/8122/2">blog post.</a></blockquote><p>Recently we got blocked by one of our external service providers due to the high amount of calls to their service from our apps deployed on k8s cluster. To avoid being blocked again we had to follow a simple rule; don’t do more than 80k requests per day. <br>Since our stack contains apps written in different languages like Java and Python, it sounds reasonable to introduce rate limit on the infrastructure level instead of trying to add it to the code of individual microservice. What’s more, that was one of the reasons why we decided to use Istio as a service mesh; it supports rate limiting out of the box. At least that was something we read in the docs, but it turned out that it’s not as easy to implement it as we initially though. Mainly because Istio deprecated the support for a rate limiter configuration via mixer policy since version 1.5 ( see the <a href="https://istio.io/latest/docs/tasks/policy-enforcement/rate-limiting/">docs</a>):</p><blockquote>The mixer policy is deprecated in Istio 1.5 and not recommended for production usage.<br>Consider using <a href="https://www.envoyproxy.io/docs/envoy/v1.13.0/intro/arch_overview/other_features/global_rate_limiting">Envoy native rate limiting</a> instead of mixer rate limiting. Istio will add support for native rate limiting API through the Istio extensions API.</blockquote><p>I don’t mind using the“Envoy native rate limiting” approach, however I failed to find any examples on how to use it for egress traffic. Although, there were a few docs, blog posts and examples, but all of them reference limiting ingress traffic, not egress. What’s more, all the envoy configs were a bit blurry for a person like myself, who hasn’t worked much with an Envoy before, therefore modifying and adjusting those to my needs took me a while.</p><p>Hopefully this article will shed some light on how an Envoy works and how to configure it from Istio to limit egress traffic.</p><h3>Stack</h3><p>In the following examples I used Kubernetes 1.18 and Istio 1.10.0.</p><h3>Istio / Envoy rate limit architecture</h3><p>Something that is not obvious at first glance is that Envoy doesn’t have its own rate limiting mechanism. It uses an external service that can do the rate limiting, and all the Envoy does, is to forward the particular HTTP requests to that service and wait for a response. If the rate limit service responses with HTTP 200 then traffic is forwarded by Envoy and if the response is HTTP 429 the request is blocked by Envoy and the same HTTP code ( 429 ) is returned to the sender. <br>This strategy to use an external service limiter gives a lot of flexibility; you can use different implementations of rate limit service including the one you may write on your own that will suit your specific needs. <br>The Envoy team did a great job in providing a <a href="https://github.com/envoyproxy/ratelimit">rate limit service </a>that works with an Envoy proxy. RateLimit counts the number of each HTTP call and compares it with a configured quota (max value) to make a decision if the request should be forwarded or blocked. By storing a count of each call in cache engine (Redis), it’s possible to have more than one instance of RateLimit added to the stack.<br>The following diagram presents the architecture that we will use in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*gmZJ3D32Ij68PygBik55NQ.png" /></figure><ol><li>Application container tries to establish connection to an external service e.g. <a href="http://edition.cnn.com/">http://edition.cnn.com</a> — I will use that domain as an example for rate limit configuration. It’s selected on purpose as it serves both http and https and is used in the Istio docs that I will refer to in the following chapter where I’ll try to explain https rate limiting</li><li>Traffic is intercepted by istio-sidecar and Enovy configuration points it to the rateLimit service. This service is also deployed in k8s and has 2 pods associated</li><li>Traffic gets to one of the RateLimit pods</li><li>Number of calls to particular endpoints are stored in Redis. RateLimit informs Redis about each new call and also fetch total number of calls to specific endpoint</li><li>Number of calls is received from Redis and RateLimit pod can make a decision if it’s within configured limit or above it</li><li>Base on that decision RateLimit sends response to Envoy — either HTTP 200 (blue line) or HTTP 429 (red line)</li><li>Only if HTTP 200 is returned from RateLimit, Envoy forwards traffic to the External Service e.g. <a href="http://edition.cnn.com/">http://edition.cnn.com</a></li></ol><h3>First things first — understanding Envoy</h3><p>My first attempt to configure rate limiter was to take an examples provided by folks in one of the <a href="https://github.com/istio/istio/issues/22068">Github issues</a>. However for a person who never worked with Envoy before those examples are difficult to understand. So I started to read <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/intro">Envoy docs</a> to have at least a basic idea of how it works. Going through all the docs is a pain, so let me just point out the most relevant <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/intro/terminology">terminology</a> Envoy uses:</p><blockquote><strong>Downstream</strong>: A downstream host connects to Envoy, sends requests, and receives responses.</blockquote><blockquote><strong>Upstream</strong>: An upstream host receives connections and requests from Envoy and returns responses.</blockquote><blockquote><strong>Listener</strong>: A listener is a named network location (e.g., port, unix domain socket, etc.) that can be connected to by downstream clients. Envoy exposes one or more listeners that downstream hosts connect to.</blockquote><blockquote><strong>Cluster</strong>: A cluster is a group of logically similar upstream hosts that Envoy connects to. Envoy discovers the members of a cluster via <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/service_discovery#arch-overview-service-discovery">service discovery</a>. It optionally determines the health of cluster members via <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/health_checking#arch-overview-health-checking">active health checking</a>. The cluster member that Envoy routes a request to is determined by the <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/overview#arch-overview-load-balancing">load balancing policy</a>.</blockquote><p>At the beginning I was confused what the Envoy <strong>cluster</strong> is.To make it simpler we can assume that in istio, each k8s service is added as an Envoy <strong>cluster </strong>to its configuration. If Envoy wants to reach out to one of your services configured in k8s, it will do so by creating a <strong>cluster</strong> that refers to a given service.<br>Let’s see how above terminology items look like in our Istio mesh. I’ve deployed some testing pod called “bastion-box” that will simulate my source application; the one that we will try to put a limit on. Bastion-box pod has istio-sidecar enabled, so let’s display envoy listeners of that istio-sidecar:</p><pre>istioctl proxy-config listener bastion-box-7449bfcbb9-59r4c                                                                                                                                                                                <br>ADDRESS            PORT      TYPE                                                                                                                                                                                                             <br>100.64.0.1         443       TCP                                                                                                                                                                                                              <br>100.64.0.10        53        TCP                                                                                                                                                                                                              <br>100.71.25.131      6379      TCP                                                                                                                                                                                                              <br>100.71.47.104      15012     TCP                                                                                                                                                                                                              <br>100.67.52.222      15443     TCP                                                                                                                                                                                                              <br>10.40.4.77         10250     TCP                                                                                                                                                                                                              <br>10.40.3.162        10250     TCP                                                                                                                                                                                                              <br>100.65.131.143     27017     TCP                                                                                                                                                                                                              <br>100.71.47.104      443       TCP                                                                                                                                                                                                              <br>100.67.52.222      443       TCP                                                                                                                                                                                                              <br>10.40.3.63         10250     TCP                                                                                                                                                                                                              <br>100.68.252.181     3306      TCP                                                                                                                                                                                                              <br>10.40.3.56         10250     TCP                                                                                                                                                                                                              <br>10.40.4.124        10250     TCP                                                                                                                                                                                                              <br>10.40.4.28         10250     TCP                                                                                                                                                                                                              <br>100.67.112.196     443       TCP                                                                                                                                                                                                              <br>10.40.3.244        10250     TCP                                                                                                                                                                                                              <br>0.0.0.0            10255     HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            8181      HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            9200      HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            9092      HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            80        HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            5672      HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            10252     HTTP+TCP                                                                                                                                                                                                         <br>0.0.0.0            4194      HTTP+TCP                                                                                                                                                                                                         <br>100.69.202.9       443       HTTP+TCP                                                                                                                                                                                                         <br>100.68.41.43       443       HTTP+TCP<br>100.67.190.6       15672     HTTP+TCP<br>100.69.167.19      9090      HTTP+TCP<br>0.0.0.0            8085      HTTP+TCP<br>100.65.194.27      8444      HTTP+TCP<br>100.67.190.6       4369      HTTP+TCP<br>0.0.0.0            8080      HTTP+TCP<br>0.0.0.0            9091      HTTP+TCP<br>0.0.0.0            9153      HTTP+TCP<br>0.0.0.0            10249     HTTP+TCP<br>0.0.0.0            2181      HTTP+TCP<br>100.64.182.240     389       HTTP+TCP<br>100.67.190.6       25672     HTTP+TCP<br>100.66.242.43      8444      HTTP+TCP</pre><p>My first thought was that Envoy, like any other service, listens on one particular port, therefore I will see a single listener. So why are there so many listeners configured? To explain this let’s refer to <a href="https://istio.io/latest/docs/ops/diagnostic-tools/proxy-cmd/#deep-dive-into-envoy-configuration">istio-docs</a>:</p><blockquote>If you query the listener summary on a pod you will notice Istio generates the following listeners:</blockquote><blockquote>A listener on 0.0.0.0:15006 that receives all inbound traffic to the pod and a listener on 0.0.0.0:15001 that receives all outbound traffic to the pod, then hands the request over to a virtual listener.</blockquote><blockquote>A virtual listener per service IP, per each non-HTTP for outbound TCP/HTTPS traffic.</blockquote><blockquote>A virtual listener on the pod IP for each exposed port for inbound traffic.</blockquote><blockquote>A virtual listener on 0.0.0.0 per each HTTP port for outbound HTTP traffic.</blockquote><p>That should explain why there are so many listeners. However, since we try to limit egress traffic, let’s focus on the last sentence— we will be connecting to <a href="http://edition.cnn.com/">http://edition.cnn.com/</a> on port 80, so our traffic will go via listener 0.0.0.0:80. Let’s see how configuration of that listener looks (the output is shortened for better clarity).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e637da3ef0ae4281404046401a84b828/href">https://medium.com/media/e637da3ef0ae4281404046401a84b828/href</a></iframe><p>There are 2 important things to notice:</p><ul><li>line 22; envoy.http_connection_manager — you may read a full description of it <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/http_connection_management#arch-overview-http-conn-man">here</a>. This is basically part of the Envoy, that describes how to handle HTTP traffic. That HTTP traffic handling rules are called httpFilters — example of httpFilter may be external authentication, CORS handling, fault injection or <strong>rate limiting. </strong>By default the rate limiting http filter is not enabled on our listener, so one of our tasks will be to add it there. Full list of httpFilters may be found <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/http_filters">here</a>.</li><li>line 30; routeConfigName — name of the routing configuration of Envoy which is the set of rules that Envoy should follow during traffic forwarding. In other words, should Envoy use some specific httpFilter when it forwards traffic to any particular domain? We would like the Envoy to use rateLimit filter, right? So <strong>route </strong>is the place where we’ll say we want to limit the traffic going to <a href="http://edition.cnn.com/">http://edition.cnn.com/</a></li></ul><p>Let’s see how that route config looks for our bastion-box pod (I took single route as an example as an output may be pretty long):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd5d365bf3a5f0a91102b630c003e0d5/href">https://medium.com/media/cd5d365bf3a5f0a91102b630c003e0d5/href</a></iframe><p>From the long output I took one route as an example which points to my grafana service in monitoring namespace. The most important lines are:</p><ul><li>line 8 — specify list of domains that will match this particular route</li><li>line 27 — cluster — when the domain is matched, where should envoy forward the traffic to?</li></ul><p>We see that traffic hitting domain “prometheus-operator-grafana.monitoring.svc.cluster.local” will be forwarded to cluster “outbound|80||prometheus-operator-grafana.monitoring.svc.cluster.local”.</p><p>Let’s see if that cluster even exists:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647fca7c60b557bdac600fe341e9ebb0/href">https://medium.com/media/647fca7c60b557bdac600fe341e9ebb0/href</a></iframe><p>Cool, it’s there — do you remember when I mentioned that “clusters” in Enovy are created automatically based on k8s service? That’s why I see my grafana cluster on the list — it’s one of the services I have implemented in monitoring namespace. But if you take a look at route config one more time you will notice there are no routes to domains external for k8s e.g. google.com or <a href="http://edition.cnn.com/">http://edition.cnn.com</a>. What’s more, there are no such clusters on the cluster list, so configuring a route to a non-existing cluster won’t be possible. That’s why we need to add a new cluster for our testing domain <a href="http://edition.cnn.com/">http://edition.cnn.com</a> later on.</p><h3>RateLimit service setup</h3><p>To be able to configure rate limiting, first we need to have a rateLimit service. I will use the one provided by Envoy team available <a href="https://github.com/envoyproxy/ratelimit">here</a>. Unfortunately I haven’t found any reasonable helm chart that helps in deploying this service to k8s. I decided to take <a href="https://github.com/softonic/go-ratelimit-chart/tree/master/templates">this one</a> as en example and adjust it to my needs (original one didn’t start rateLimit properly and doesn’t have statsd sidecar which is needed to export metrics of rateLimit to prometheus). You can find the chart I used on <a href="https://github.com/jdomag/helm-envoy-rateLimit">my github</a>. <br>Before you launch a chart you need to apply redis settings in values.yaml. For testing purposes I deployed redis in k8s cluster in the same namespace I’ll deploy the rateLimit service. Mandatory part is also adjustment of configuration of rateLimit app. You may check out the documentation <a href="https://github.com/envoyproxy/ratelimit#configuration">here</a> — I find those docs really good, but let me highlight one item that may be confusing. The top level configuration of rateLimit is a “domain” which has nothing to do with a domain which you try to apply a rate limit for. RateLimit “domain” is just a name for the set of rules that will be applied. So it can be anything and I will name it “my-rules”. Remember that name though, as we need to configure Istio to refer to this particular set of rules. So the config part of my helm chart looks like below. We will get to the key-value part of it later on.</p><pre>config: |-<br>  ---<br>  domain: my-rules<br>  descriptors:<br>    - key: generic_key<br>      value: edition.cnn.com<br>      rate_limit:<br>        unit: hour<br>        requests_per_unit: 3</pre><p>After chart deployment we can see that each pod has 2 containers; one with the rateLimit app and one with statsd exposing the metrics if you want to scrape them later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*4HROJHstBVLmmVzWG1jmqw.png" /></figure><h3>Let’s configure it — istio configuration</h3><p>In previous chapters we defined couple of problems that needs to be solved to configure rate limiting in Istio:</p><ul><li>there is no envoy cluster for services/domain external to our service mesh e.g. <a href="http://edition.cnn.com/">http://edition.cnn.com</a> or <a href="http://google.com/">http://google.com</a></li><li>there is no Envoy route to the external domains that we can apply some rules to (i.e. rate limiting)</li><li>even if we had a cluster and a route, we need to add an additional http filter to envoy to tell it how to modify http traffic for us</li><li>since Envoy uses an external service to handle rate limiting, we need to point it to that external service, so it knows where to send a traffic for rate limiting assessment</li></ul><p>Let’s start from the bottom and tell Envoy where our rateLimit service is ( by adding new Envoy cluster) and add a HTTP rate limit filter that will point to it.</p><p>Istio can manipulate Envoy configuration by adding EnvoyFilter objects to the k8s cluster — full spec of EnvoyFilter can be found <a href="https://istio.io/latest/docs/reference/config/networking/envoy-filter/">here</a>. Let’s apply the following EnvoyFilter manifest to the same namespace where my source pod “bastion-box” is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/323cbe9ba799a1d2d8d13e0af521bdad/href">https://medium.com/media/323cbe9ba799a1d2d8d13e0af521bdad/href</a></iframe><p>At the beginning of the file we can see the “workloadSelector” which allows us to select which source pods will be affected by our change. You may leave it blank if you want to apply the change for every istio enabled pod, but I decided to affect a single testing pod; bastion-box. Then we added 2 Envoy configuration patches; cluster named “rate_limit_cluster” that points to “ratelimit.default.svc.cluster.local:8081” and HTTP filter that points to this cluster. Each part has a matching section that selects appropriate pieces of Envoy config and patching section that defines what we would like to change/add there.<br>Keep in mind that “domain” in HTTP filter config is not the destination HTTP domain, but the domain defined in the rateLimit service — see previous chapter to find out about rateLimit domain definition. <br>Also take a look at “failure_mode_deny” parameter — it defines what Envoy should do with traffic that is pointed to rateLimit service when that service is not available for any reason. I prefer to deny such a traffic and returns HTTP 500 to the source, because I can easily catch and follow those errors, otherwise traffic that suppose to be rate limited may be forwarded to the destination without us knowing that the rateLimit service was broken in the first place. <br>Let’s see the result of applying the above. <br>First we added a new filter to our listener:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47a2a674aa15561ab42b23d3aae07f9/href">https://medium.com/media/a47a2a674aa15561ab42b23d3aae07f9/href</a></iframe><p>As we can see a new filter called “envoy.rate_limit” has been added to the listener configuration. This filter defines the rules on how to modify the traffic; all HTTP requests that this filter will be applied against should be sent to “rate_limit_cluster” and match the set of rules ( rate limit domain) “my-rules”. Moreover when “rate_limit_cluster” is not available, traffic should be blocked. <br>So far so good; but how does the Envoy knows what “rate_limit_cluster” is? That’s the second part of our manifest — cluster definition. Let’s see how it looks in Envoy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d130fe5b5330758f50d1640d953b1547/href">https://medium.com/media/d130fe5b5330758f50d1640d953b1547/href</a></iframe><p>It’s nothing more than pointing it to the k8s service of our rate limit app. Actually this step could be omitted as Istio will detect rateLimit service automatically and configure clusters for us, but I prefer to select my own name for the cluster, plus I think it helps in understanding the whole concept.</p><p>Good, now our Envoy knows how to reach rateLimit service, so let’s now configure which traffic should be actually rate limited. First, we need our external domain <a href="http://edition.cnn.com/">http://edition.cnn.com</a> to show up as an Envoy cluster. Istio implements a special type of object that allows us to add an external services to the Istio mesh — <a href="https://istio.io/latest/docs/reference/config/networking/service-entry/">ServiceEntry</a>. Adding ServiceEntry has multiple benefits and one of them is that destinations defined in ServiceEntry will be treated like internal k8s services — which means Envoy will automatically add a cluster definition for that service.<br>Let’s try to add the following ServiceEntry:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c18b2465c5577c67815afaf08defcead/href">https://medium.com/media/c18b2465c5577c67815afaf08defcead/href</a></iframe><p>The file is straight forward and doesn’t require much explanation, but let me highlight the fact that edition.cnn.com works on both http and https and we want both protocols to work. Firstly we focus on HTTP as it’s easier to configure rate limiting for it, however in the last chapters I will present a method how to handle HTTPS traffic as well.</p><p>Let’s verify if the Envoy cluster has been added to our side-car proxy configuration as expected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0819646ab3088182b3ad1c0f776cb18/href">https://medium.com/media/c0819646ab3088182b3ad1c0f776cb18/href</a></iframe><p>So far so good. Let’s verify if the corresponding route has been added as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/298b4f41d31c49745028b5ae601b6939/href">https://medium.com/media/298b4f41d31c49745028b5ae601b6939/href</a></iframe><p>It looks like almost all the problems, we defined at the beginning, are solved by now; we added rateLimit service to the cluster and we pointed Envoy to it, we applied HTTP filter that is able to forward traffic to rateLimit service and its proper domain, we added external http/https domain to our istio mesh which caused Envoy to configure proper cluster and route for us. The last piece of the puzzle is to tell Envoy that every request which goes from the bastion-box to <a href="http://edition.cnn.com/">http://edition.cnn.com</a> must be rate limited. The Envoy route is the place where we can apply HTTP filters and modify the traffic. So let’s try to apply our HTTP filter (envoy.rate_limit) to a route pointing to <a href="http://edition.cnn.com/">http://edition.cnn.com</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0555ab3e54389ab5e726fcee4e8ae381/href">https://medium.com/media/0555ab3e54389ab5e726fcee4e8ae381/href</a></iframe><p>To describe above yaml let me break it down into two pieces. First part “applyTo” works like a selector — it selects the Envoy object you want to modify. Second part “patch:” adds rate limit configuration. You can see below how the manifest is mapped to the Envoy route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBs6cY10bgAj4XUNTR7XKw.png" /></figure><p>As you may read in <a href="https://github.com/envoyproxy/ratelimit#configuration">rateLimit service docs</a>, rateLimit uses key-value pairs to apply rate limiting rules. Istio/Envoy role is to assign the correct keys and corresponding values to the traffic being sent to rateLimit service. To see all the options of configuring those keys (descriptors) you may visit <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#config-route-v3-ratelimit-action">Envoy docs</a>. To make things simpler I just assigned the following key value pair to all the traffic that goes to <a href="http://edition.cnn.com/">http://edition.cnn.com</a>:</p><blockquote>generic_key: edition.cnn.com</blockquote><p>Usage of generic_key descriptor sets name of the key to “generic_key” automatically and as far as I know it can’t be modified. The value of that key may be anything you want — I simply used the domain name, but it could also be “my-super-value”, although you need to make sure your rateLimit service configuration matches that key and value. In my case the rateLimit config looks like below.</p><pre>domain: my-rules<br>descriptors:<br>  - key: generic_key<br>    value: edition.cnn.com<br>    rate_limit:<br>      unit: hour<br>      requests_per_unit: 3</pre><p>At this point we should be all set and ready to test the rate limiting.</p><h3>Testing</h3><p>To test it I will exec into my source pod; bastion-box and access <a href="http://edition.cnn.com/">http://edition.cnn.com</a> a few times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*VJRAr6zi9jhb-Kes2x3nEw.png" /></figure><p>I successfully accessed the domain 3 times and after that my request had been blocked with a HTTP 429 response. After the configured timeout expires (we set it to 1 hour), bastion-box will be able to access <a href="http://edition.cnn.com/">http://edition.cnn.com</a> again (for 3 times).</p><h3>How to rate limit HTTPS traffic?</h3><p>In previous chapters we took <a href="http://edition.cnn.com/">edition.cnn.com</a> as a domain we applied a rate limit for. It works on both http and https which makes it a perfect example to highlight a problem and reproduce it. <br>When Envoy receives a HTTP traffic it reads HTTP headers and maps it to certain key-value pairs (descriptors), however when the source app connects to the destination domain by HTTPS all the HTTP headers are encrypted by SSL. For that reason Envoy can’t read HTTP headers and apply a rate limit filter on it.<br>A solution to that problem could be to configure the source app to use plain HTTP to connect to destination, apply rate limiting for that traffic on Envoy side and configure Envoy to convert it to HTTPS before sending it outside a cluster. We covered the firsts steps in this article and the last part can be achieved by one of the Istio functionalities called Egress TLS Origination. Hopefully I will find more time to write a separate post about limiting HTTPS traffic where I can cover all the details, but the<a href="https://istio.io/latest/docs/tasks/traffic-management/egress/egress-tls-origination/"> Istio docs for Egress TLS Origination</a> are very useful and can be a good start.</p><h3>Conclusion</h3><p>A while ago Istio deprecated rate limiting configuration directly from Istio, leaving its users with an option to implement it directly in Envoy. This may be achieved by leveraging EnvoyFilter and ServiceEntry CRDs defined by Istio, however usage of EnvoyFilter object to manipulate Envoy config doesn’t sound right and may introduce some risks. The ability to integrate nicely a rate limit with an Istio profile and simplifying the whole concept is on the Istio development road map, unfortunately at the time of writing this article they have not announced yet which Istio release will bring that functionality.</p><p>Hopefully this article helped a few of you and shed some light on the rate limiting concept in Envoy proxy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8697df490f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>