<?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 Luca Mattivi on Medium]]></title>
        <description><![CDATA[Stories by Luca Mattivi on Medium]]></description>
        <link>https://medium.com/@leen15?source=rss-cb8a1d86e1ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*avexSNylU3HOYjowdBHp2Q.jpeg</url>
            <title>Stories by Luca Mattivi on Medium</title>
            <link>https://medium.com/@leen15?source=rss-cb8a1d86e1ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:33:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leen15/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[Vibecoding is great, but do you really trust the result?]]></title>
            <link>https://medium.com/@leen15/vibecoding-is-great-but-do-you-really-trust-the-result-50caa93166c0?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/50caa93166c0</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[vibe-coding-tools]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[lovable]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 10:50:00 GMT</pubDate>
            <atom:updated>2025-11-05T10:50:00.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Te4Mr50NzJCXoGl-W7lBQ.png" /><figcaption>Is it vibecoding or blindcoding?</figcaption></figure><p>In the last few months, I’ve been vibecoding more often.<br>And honestly, it’s one of the most satisfying moments in my work.<br>You enter the flow, ideas move, you build fast, and things start taking shape in front of your eyes.</p><p>With tools like Lovable, Claude and others, that feeling gets even stronger.<br><strong>You are not just imagining anymore, you are actually creating.</strong><br>And everything looks good.</p><p>Then you stop, look at what you built, and one question hits you:</p><blockquote>Do I actually trust this?</blockquote><p>And I don’t mean “it works when I click it”.<br>That’s just the beginning.</p><p>I mean: <strong>will it hold up when real users, real traffic, real data, and real consequences show up?</strong></p><h3>The problem is not writing. It is understanding.</h3><p>AI makes you feel powerful.<br>You write a prompt and suddenly you have an app.</p><p>And if you are a junior, or not even a developer, it is easy to think:</p><blockquote>It works, so it must be good.</blockquote><p>But sometimes you simply <strong>do not have the right tools yet to evaluate what you got</strong>.<br>That is not a judgment. It is normal.<br>Before, you did not need to evaluate it. Today, you do.</p><p>Two things happen here:</p><p><strong>Pygmalion effect: </strong>You trust the result because you feel you created it.</p><p><strong>Confirmation bias: </strong>You focus only on signs that confirm everything is fine.</p><p>The UI responds nicely, nothing breaks, it feels good.</p><blockquote><strong>But software is not UI.<br>Software is what happens when someone pushes it, abuses it, scales it, challenges it, or tries to bypass it.</strong></blockquote><p>A demo is not a product.<br>“Works now” is not the same as “works when it matters”.</p><h3>A simple example that explains everything</h3><p>Imagine AI generates a clean signup flow, onboarding, and redirects automatically into the app.</p><p>Smooth, elegant, satisfying.</p><p>Then one day you open the code and see something like:</p><pre>// auto login after signup<br>POST /autologin { email }</pre><p>If someone knows your email, they can log in as you.<br> No token.<br> No additional check.<br> Nothing.</p><p>Not bad intent. Not laziness.<br>Just lack of awareness in that moment.</p><blockquote>And AI does not know your context or your responsibilities.<br>It gives you a shortcut that feels correct from a UX perspective.</blockquote><p>Beautiful, until the wrong person tries it.</p><h3>When Dunning Kruger meets prompting</h3><p>We live in a moment where anyone can build something that works.<br>Amazing.</p><p>But here is the trap:</p><blockquote>“Works” starts feeling like “I understand it”.</blockquote><p><strong>The learning curve did not disappear.<br>It just became invisible.</strong></p><p>And if you do not notice it, <strong>you start confusing magic with mastery</strong>.</p><p>You do not need to be an architect today.<br>You just need enough awareness to ask:</p><p>“Do I get what is happening here, at least at a high level?”</p><p><strong>Because if you do not understand it, you do not truly own it.</strong></p><h3>Vibecoding is not magic. It is collaboration.</h3><blockquote>Real vibecoding is not writing a giant prompt and hoping for the best.<br>That is hope-driven development.</blockquote><p>The real version is iterative:</p><ul><li>This works, but is it safe?</li><li>What edge cases am I ignoring?</li><li>What happens if usage doubles?</li><li>Am I trusting this or understanding it?</li></ul><p>It is like working with a very fast, very creative colleague.<br>They move you forward.<br><strong>But you stay at the wheel.</strong></p><h3>It is not only about developers</h3><p>If you work in product, until recently <strong>your creativity flowed through a tech team</strong>.<br>Sometimes it felt slow, but <strong>it protected you from certain mistakes</strong>.</p><p>Now you can prototype yourself.<br>And that is beautiful.</p><p>But a polished demo is not a real product.<br>You understand that only when responsibility arrives:</p><ul><li>Real users</li><li>Real data</li><li>Real risk</li></ul><blockquote>AI has democratized creation.<br>It has not democratized understanding at the same pace.</blockquote><p>We need more awareness, not less enthusiasm.</p><h3>How I deal with this</h3><p>I use AI every day.<br>It helps me think, build, iterate.</p><p>But then I:</p><ul><li>pause</li><li>reread everything</li><li>add tests</li><li>try to break what I built</li><li>ask uncomfortable questions instead of celebrating speed</li></ul><p><strong>Not because I distrust the tools.<br>But because I respect what I am building.</strong></p><h3>Conclusion</h3><p><strong>Keep vibecoding.</strong><br>It is fun, creative, energizing.<br>It gets you moving faster than ever.</p><p>But remember:</p><blockquote>It is not enough that it works.<br>You need to be able to say, even at a basic level:<br>“I understand why this works, and what happens if it breaks.”</blockquote><p>The important difference is not between who uses AI and who does not.<br>It is between those <strong>who build, and those who ask the machine to build instead of them</strong>.</p><p>Creativity is here.<br>Responsibility is here too.<br>Putting them together is where the real work starts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50caa93166c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if you could migrate your frontend without telling anyone? We did.]]></title>
            <link>https://medium.com/1000farmacie/what-if-you-could-migrate-your-frontend-without-telling-anyone-we-did-804042517148?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/804042517148</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubenetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 16:11:53 GMT</pubDate>
            <atom:updated>2025-06-04T16:11:53.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQSV7grO872ELpn0qZdVhQ.png" /><figcaption>Two roads for the same destination</figcaption></figure><h3>Introduction</h3><p><strong>Can you migrate your entire frontend to a new stack without freezing development or triggering downtime?</strong></p><p>That was the challenge we faced in <a href="https://www.1000farmacie.it/">1000Farmacie</a> when moving from a Next.js frontend to a fullstack Ruby on Rails setup.<br>But instead of treating this as a big-bang rewrite, we took a different approach: migrating the site <em>route by route</em>, while continuing our normal deploy rhythm (<strong>4–5 releases a day</strong>).</p><p>In this post, I’ll show how we pulled it off using AWS CloudFront, Application Load Balancer, Kubernetes, and a bit of Terraform and CDK8s automation — <strong>without disrupting our workflow or our users</strong>.</p><h3>Our starting point</h3><p>We started with a fairly standard architecture:</p><ul><li><strong>Frontend</strong>: built in Next.js for historical reasons — we expected it to help with SEO and dynamic content, but in practice, those advantages never really materialized.</li><li><strong>Backend</strong>: Ruby on Rails, exposing APIs consumed by the frontend.</li></ul><p>The decision to migrate the frontend to Rails was based on internal needs — simplifying the stack, improving integration between teams, a more efficient caching system, and making rendering more consistent. That said, this post isn’t about <em>why</em> we switched, but <em>how</em> we made it happen without breaking everything.</p><h3>Managing traffic during a gradual migration</h3><p>Rebuilding a live site while keeping it fully operational is never simple. In our case, the key challenge was managing traffic between the new Rails frontend and the legacy Next.js app.</p><p>Sure, Kubernetes gives you all kinds of ways to split and control traffic, but we wanted something that wouldn’t add unnecessary complexity or change our existing routing logic too much for a one time process.</p><p>Since we already had an <strong>AWS Application Load Balancer (ALB)</strong> in place, we decided to use it as our main traffic orchestrator — lightweight, flexible, and already battle-tested.</p><h3>Testing in Production, without risk</h3><p>We didn’t want this migration to interfere with our normal release flow. Every section we migrated needed to be tested first — ideally, in production — without exposing untested pages to all users.</p><p>That’s where <strong>header-based traffic splitting</strong> came in. <br>By routing traffic conditionally using ALB annotations and custom HTTP headers like X-fullstack-10, we could:</p><ul><li>deploy new sections as part of our standard pipeline;</li><li>test them manually by passing headers from the browser or CLI;</li><li>and slowly ramp them up to more users, without touching the app code.</li></ul><h3>Conditional routing with ALB Ingress</h3><p>We implemented header-based routing using <strong>ALB Ingress annotations</strong>, allowing us to target specific percentages of traffic to the new frontend by simply adding a custom header.</p><p>Here’s how it worked in practice. For each traffic percentage (1%, 5%, 10%, etc.), we created a separate ALB action and condition, entirely driven by custom headers:</p><pre>alb.ingress.kubernetes.io/actions.fullstack-10-routing: &gt;<br>  {<br>    &quot;type&quot;:&quot;forward&quot;,<br>    &quot;forwardConfig&quot;:{<br>      &quot;targetGroups&quot;:[<br>        { &quot;serviceName&quot;:&quot;web-service&quot;, &quot;servicePort&quot;:3000, &quot;weight&quot;:10 },<br>        { &quot;targetGroupArn&quot;:&quot;...&quot;, &quot;weight&quot;:90 }<br>      ],<br>      &quot;targetGroupStickinessConfig&quot;:{ &quot;enabled&quot;:false }<br>    }<br>  }<br><br>alb.ingress.kubernetes.io/conditions.fullstack-10-routing: &gt;<br>  [<br>    {<br>      &quot;field&quot;:&quot;http-header&quot;,<br>      &quot;httpHeaderConfig&quot;:{<br>        &quot;httpHeaderName&quot;:&quot;X-fullstack-10&quot;,<br>        &quot;values&quot;:[&quot;true&quot;]<br>      }<br>    }<br>  ]</pre><p>Thanks to <strong>CDK8s</strong>, generating this setup for multiple traffic splits took few lines of code:</p><pre>for (const weight of [1, 5, 10, 20, 50, 100]) {<br>  const feWeight = 100 - weight;<br>  this.environment.ingressAnnotations[`alb.ingress.kubernetes.io/actions.fullstack-${weight}-routing`] = JSON.stringify({<br>    type: &quot;forward&quot;,<br>    forwardConfig: {<br>      targetGroups: [<br>        {<br>          serviceName: serviceWWW.serviceName,<br>          servicePort: serviceWWW.servicePort,<br>          weight: weight,<br>        },<br>        ...(feWeight &gt; 0 ? [{<br>          targetGroupArn: FEtargetGroupArn,<br>          weight: feWeight<br>        }] : [])<br>      ],<br>      targetGroupStickinessConfig: { enabled: false }<br>    }<br>  });<br>  this.environment.ingressAnnotations[`alb.ingress.kubernetes.io/conditions.fullstack-${weight}-routing`] = JSON.stringify([<br>    {<br>      field: &quot;http-header&quot;,<br>      httpHeaderConfig: {<br>        httpHeaderName: `X-fullstack-${weight}`,<br>        values: [&quot;true&quot;]<br>      }<br>    }<br>  ]);<br>  this.ingressServices.push({<br>    hosts: [hostWWW],<br>    serviceName: `fullstack-${weight}-routing`,<br>    servicePort: -1<br>  });<br>}</pre><p>We could now test any page in production, just by adding a header. And once we were confident, we moved forward.</p><h3>Dynamic CDN routing with CloudFront</h3><p>CloudFront sits at the edge and was the first layer to decide <em>where</em> to send traffic.</p><blockquote>To control that routing, we used Terraform to define which paths should go to which versions of the frontend — all dynamically.</blockquote><p>Here’s what that looked like:</p><pre>dynamic &quot;ordered_cache_behavior&quot; {<br>  for_each = toset([<br>    &quot;/checkout/*&quot;, &quot;/account/*&quot;, &quot;/products/*&quot;<br>  ])<br>  content {<br>    allowed_methods          = [&quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot;]<br>    cache_policy_id          = data.aws_cloudfront_cache_policy.default.id<br>    cached_methods           = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    compress                 = true<br>    origin_request_policy_id = data.aws_cloudfront_origin_request_policy.default.id<br>    path_pattern             = ordered_cache_behavior.value<br>    target_origin_id         = &quot;fullstack-100&quot;<br>    viewer_protocol_policy   = &quot;redirect-to-https&quot;<br>  }<br>}</pre><p>The origin_id was also generated dynamically:</p><pre>dynamic &quot;origin&quot; {<br>  for_each = toset([<br>    &quot;fullstack-1&quot;,<br>    &quot;fullstack-5&quot;,<br>    &quot;fullstack-10&quot;,<br>    &quot;fullstack-20&quot;,<br>    &quot;fullstack-50&quot;,<br>    &quot;fullstack-100&quot;,<br>  ])<br>  content {<br>    connection_attempts = 3<br>    connection_timeout  = 10<br>    domain_name         = var.origins[&quot;backend&quot;]<br>    origin_id           = origin.value<br>    custom_origin_config {<br>      http_port                = 80<br>      https_port               = 443<br>      origin_keepalive_timeout = 60<br>      origin_protocol_policy   = &quot;https-only&quot;<br>      origin_read_timeout      = 60<br>      origin_ssl_protocols     = [&quot;TLSv1.2&quot;]<br>    }<br>    custom_header {<br>      name  = format(&quot;X-%s&quot;, origin.value)<br>      value = &quot;true&quot;<br>    }<br>  }<br>}</pre><p>This way, CloudFront determined the target origin for each path, and the origin passed the corresponding header (e.g. X-fullstack-10) to the ALB, which handled the actual split.</p><h3>Steady rollout, clean cutoff</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aY14-H8etU6HpfZzIxjCg.png" /><figcaption>Diagram of the traffic</figcaption></figure><p>This setup gave us full control with <strong>zero impact on developer velocity</strong>:</p><ul><li>New sections were released as part of our normal CI/CD process (4–5 deploys a day);</li><li>Manual testing was easy — add the header and check behavior in production;</li><li>Once stable, we added the path to CloudFront via Terraform to gradually shift traffic.</li></ul><p>We repeated this process until all routes were hitting X-fullstack-100. At that point:</p><ul><li>we removed all X-fullstack-* routing logic from ALB and CloudFront;</li><li>pointed everything directly to the new fullstack origin;</li><li>and pulled the plug on our old Next.js frontend — clean and final.</li></ul><h3>Final thoughts</h3><p>This wasn’t just a rewrite. It was a <strong>controlled evolution</strong>. No big bang, no frozen pipelines, no “dark launch.”</p><p>Instead of freezing development or rewriting everything behind a feature flag, we leaned on the infrastructure we already had.</p><p><strong>With CloudFront, ALB, CDK8s and Terraform working together, we migrated the frontend without impacting development, without user disruption, and without losing our minds.</strong></p><p>It worked — quietly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=804042517148" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1000farmacie/what-if-you-could-migrate-your-frontend-without-telling-anyone-we-did-804042517148">What if you could migrate your frontend without telling anyone? We did.</a> was originally published in <a href="https://medium.com/1000farmacie">1000Farmacie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Risk of Running WordPress on Kubernetes: Debugging an Unexpected Downtime Issue]]></title>
            <link>https://medium.com/1000farmacie/the-hidden-risk-of-running-wordpress-on-kubernetes-debugging-an-unexpected-downtime-issue-e810bf4fb577?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/e810bf4fb577</guid>
            <category><![CDATA[503-service-unavailable]]></category>
            <category><![CDATA[503]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[downtime]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 11:02:32 GMT</pubDate>
            <atom:updated>2024-12-02T11:02:32.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kz5V4Oou67konWraoh2sEA.jpeg" /></figure><p>At <a href="https://www.1000farmacie.it/">1000Farmacie</a>, we recently migrated our entire infrastructure to <strong>Kubernetes</strong>, including a range of critical systems. One of the workloads we moved was a WordPress blog, which runs across multiple pods for high availability (HA). Despite this careful setup, after a couple of months we encountered a persistent issue with it: intermittent downtime. After extensive debugging, we discovered the root cause: <em>an overlooked interaction between Kubernetes health checks and WordPress’s behavior during updates.</em></p><h3><strong>Debugging the issue</strong></h3><p>When the downtime began, we initially suspected issues related to resource allocation or external systems like the database and file system. Here’s the process we followed to debug the problem:</p><p>1. <strong>Random Downtime</strong>: The issue was particularly difficult to debug because the downtime occurred randomly, both during the day and night, which made it hard to pinpoint. Sometimes, the downtime would require us to manually restart the pods, but this would only temporarily resolve the issue. Additionally, investigating during downtime was challenging, as doing so could potentially extend the downtime further. As a result, we had to limit real-time investigation until the issue was less disruptive.</p><p>2. <strong>Investigating Resources</strong>: After noticing the downtime, we checked the resource usage on Kubernetes, including CPU, memory, and network traffic. We tried increasing pod limits to cover potential traffic peaks or issues caused by plugins, but these actions didn’t solve the problem. With high availability and autoscaling in place, resources didn’t seem to be the issue.</p><p>3. <strong>Database and File System</strong>: Our database runs on AWS RDS and our file system is shared via EFS across pods. We investigated potential issues such as high DB load or excessive I/O operations on EFS. Both were ruled out, as neither exhibited signs of stress.</p><p>4. <strong>Health Check Failures</strong>: After further investigation, we noticed that Kubernetes was repeatedly restarting the WordPress pods due to health check failures. This led us to believe the issue was related to the health check configuration.</p><p>5. <strong>Manual Update Testing</strong>: The breakthrough came when I manually triggered a WordPress update. During the update, WordPress switched to maintenance mode and returned a 503 status code, causing Kubernetes to mark the pod as unhealthy and restart it. We discovered that maintenance mode was automatically disabled only after a brief period, which explained why the issue occurred randomly.</p><h3><strong>The breakthrough</strong></h3><p>The issue became clear: WordPress’s maintenance mode <strong>triggered a 503 status code on all endpoints during updates</strong>, which Kubernetes interpreted as a failure. This caused unnecessary container restarts, preventing the update from completing.</p><p>Since WordPress was running on multiple pods, this behavior caused inconsistent service across the pods, which amplified the downtime. The update cycle continued without resolution, as WordPress would attempt to retry the update after a delay.</p><h3><strong>Why this happens</strong></h3><p>WordPress does not provide a health check endpoint out of the box. When it enters maintenance mode during updates, it returns a <strong>503 status code </strong>for all its endpoints. <em>Kubernetes, seeing this as a failure, restarts the pods, which disrupts the update process.</em></p><p>However, there is one exception: the wp-admin/install.php endpoint. This endpoint remains functional during maintenance mode and validates key components like the database connection, making it suitable for Kubernetes health checks.</p><h3><strong>The solution</strong></h3><p>To solve this problem, we configured Kubernetes to use the wp-admin/install.php endpoint for health checks instead of the default WordPress endpoints. This allows updates to proceed without triggering unnecessary container restarts.</p><p><strong>Steps to Implement:</strong></p><p>1. <strong>Modify Health Check Probes</strong>: Update the Kubernetes readiness and liveness probes to use wp-admin/install.php.</p><p>2. <strong>Disable Automatic Updates</strong> <em>(optional)</em>: If updates aren’t urgent, manually manage them to avoid unexpected restarts.</p><p>3. <strong>Leverage Helm Charts</strong>: If you’re using the Bitnami Helm chart for WordPress, this solution is already implemented, making it a quick fix.</p><p>By aligning health checks with WordPress’s behavior, we were able to eliminate the risk of downtime during updates.</p><h3><strong>Conclusion</strong></h3><p>While WordPress remains a powerful tool for building websites, running it on modern infrastructure like Kubernetes requires understanding and adapting to its behavior. The lack of a built-in health check endpoint by Wordpress and its reliance on maintenance mode during updates can lead to unexpected downtime, especially in high-availability environments.</p><p>By using the wp-admin/install.php endpoint for health checks — or leveraging pre-configured solutions like the Bitnami Helm chart — you can prevent unnecessary restarts and ensure your WordPress site remains operational during updates. I hope this insight helps others avoid the issues we encountered during our transition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e810bf4fb577" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1000farmacie/the-hidden-risk-of-running-wordpress-on-kubernetes-debugging-an-unexpected-downtime-issue-e810bf4fb577">The Hidden Risk of Running WordPress on Kubernetes: Debugging an Unexpected Downtime Issue</a> was originally published in <a href="https://medium.com/1000farmacie">1000Farmacie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to handle HAProxy log format]]></title>
            <link>https://medium.com/@leen15/how-to-handle-haproxy-log-format-33daa87ce7f1?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/33daa87ce7f1</guid>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[haproxy]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 13:02:00 GMT</pubDate>
            <atom:updated>2024-04-24T13:05:17.069Z</atom:updated>
            <content:encoded><![CDATA[<p>During our migration from <a href="https://www.smartdomotik.com/2019/03/01/migrating-from-rancher-1-to-rancher-2-and-k8s-our-story-part-1/">Rancher1 to Rancher2 and K8S</a>, we also moved our reverse proxies from nginx to HAProxy.</p><p>Nobody of us is an expert of HAProxy, so we studied a lot how it works and how to fix issues using it.<br>There is an important thing that we would like to share, and it’s about logs generated by HAProxy.</p><p>For us it’s very important to handle properly the log format, because we have external monitoring tools that ingest logs and allow us to make use of them (dashboards, alerts, error analytics, …).</p><h3>Custom log format</h3><p>The default log format could be not enough for you, and you would like a custom log format that can satisfy your needs.</p><p>In our case, we have two different log formats:</p><ul><li>The first one is a basic log format, with only the request url, the response status, time taken and few other things</li><li>The second one, is a specific custom log format, with lots of information very useful for critical services and for debugging</li></ul><p>The second one is of course the most interesting, and it looks like this:</p><pre>&lt;30&gt;Mar 13 14:06:24 haproxy[6]: 13/Mar/2020:14:06:24 +0000 client_ip=&quot;xxx.xxx.xxx.xxx&quot; lb=10.42.1.0 container=10.42.3.158 response_status=200 path=HEAD /api/v1/endpoint HTTP/1.1 auth_token=&quot;&quot; client_key=&quot;&quot; response_time=8 total_time=8 bytes=391 user_agent=&quot;python-requests/2.22.0&quot; host=&quot;apiurl.domain&quot; body=&quot;&quot; accept_language=&quot;&quot;</pre><p>Here we have lots of useful information:</p><ul><li>client_ip: The ip address of the client</li><li>lb: The Load Balancer where traffic is coming</li><li>container: The container that elaborated the request</li><li>response_status: The status code of the response</li><li>path: The requested URL</li><li>auth_token: If the user is authenticated, we can identify it and follow its requests</li><li>client_key: If the client application is one of ours, here we have a key to identify it</li><li>response_time: The time taken by the service to elaborate the request</li><li>total_time: The time taken by all the infrastructure to answer to the request</li><li>bytes: The size of the response</li><li>user_agent: The user agent of the client</li><li>host: The hostname requested</li><li>body: The body of the request sent</li><li>accept_language: the locale of the client</li></ul><p>How can we create a custom log like this?</p><h4>Create the custom log format</h4><p>HAProxy has lots of attributes that can be used in your custom log format, but some of them are not enabled by default, so you have to do a bit of work to have it in your logs.</p><p>Let’s see what we have to set in haproxy.cfg in order to have the log format above:</p><pre>capture request header X-Forwarded-For len 20<br>    capture request header authorization len 80<br>    capture request header X-Client-Auth len 80<br>    capture request header User-Agent len 400 <br>    capture request header Host len 150 <br>    http-request capture req.body len 10000<br>    capture request header Accept-Language len 10 <br>    <br>    log-format &quot;%trg client_ip=%{+Q}[capture.req.hdr(0)] lb=%ci container=%si response_status=%ST path=%r auth_token=%{+Q}[capture.req.hdr(1)] client_key=%{+Q}[capture.req.hdr(2)] response=%Tr total_time=%Tt bytes=%U user_agent=%{+Q}[capture.req.hdr(3)] host=%{+Q}[capture.req.hdr(4)] body=%{+Q}[capture.req.hdr(5)] accept_language=%{+Q}[capture.req.hdr(6)]&quot;</pre><p>This could be a bit difficult to understand 🙂</p><p>The important thing is the log-format instruction, here we have our string with the format that we want.</p><p>All variables like %… are standard, you can find a list <a href="https://cbonte.github.io/haproxy-dconv/2.1/configuration.html#8.2.4">here</a> (always read carefully the documentation, most of times what you need is there!)</p><p>The log format doesn’t have a <em>“standard pattern”</em>, you can have it as are most comfortable with, for us it’s better to have a string that identify every printed value.<br>The capture requests above the log-format instruction are used to grab custom data, and you have to specify if they are headers or something else (like the body).<br>Every capture request uses a slot in a capture.req.hdr array, so the order of your definitions is the order where you’ll find the value in the array.<br>The command %{+Q} is used to put the value (declared with square brackets) between double quotes.</p><h3>Body logging</h3><p>One of the most useful thing when debugging applications is to have the body request in logs.<br>In the section above we already added the body in the log format, but we found two different issues with this.</p><p>The first issue is about the length of the body: We spend couple of hours trying to understand why we have empty body in logs or truncated body, and finally we found the reason, in the <a href="https://cbonte.github.io/haproxy-dconv/2.1/configuration.html#3.1-log">documentation</a>:</p><pre>&lt;length&gt; is an optional maximum line length. Log lines larger than this value<br>         will be truncated before being sent. The reason is that syslog<br>         servers act differently on log line length. All servers support the<br>         default value of 1024, but some servers simply drop larger lines<br>         while others do log them. If a server supports long lines, it may<br>         make sense to set this value here in order to avoid truncating long<br>         lines. Similarly, if a server drops long lines, it is preferable to<br>         truncate them before sending them. Accepted values are 80 to 65535<br>         inclusive. The default value of 1024 is generally fine for all<br>         standard usages. Some specific cases of long captures or<br>         JSON-formatted logs may require larger values.</pre><p>And here we are, the max line length is 1024, also if you set len 10000 in the capture request.</p><p>In order to increase this value, you have to set the desired length in the log instruction:</p><pre>log stdout len 10000 daemon debug</pre><p>The second issue, is about carriage returns in the body request.<br>If a client sends a request with carriage returns in the body, you will have something like this in log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NEeApkYjibrMeIQU.png" /></figure><p>As you can see, you don’t have a single log for every request, instead it’s split into multiple lines, causing most of analyzing tools to not properly decode this log.</p><p>Fortunately, HAProxy has a VERY NICE <a href="https://cbonte.github.io/haproxy-dconv/2.1/configuration.html#7.3.1">functionality</a> that allows to make operations on all variables and attributes that are between square brackets.<br>So in our case, we used the <strong>regsub</strong> function on the body value:</p><pre>body=%{+Q}[capture.req.hdr(5),regsub(\n,\\n,g)]</pre><p>And now the log will be on a single line.<br><em>Keep in mind that this operation impacts only the attribute in log, it will not alter the original request.</em></p><h3>Conclusion</h3><p>HAProxy is a really good Load Balancer and Reverse Proxy.<br>We are really happy to moved away from nginx.<br>As always, we write this post to share issues we found and how we fixed it.</p><p>If you need it we also created a <a href="https://github.com/Leen15/haproxy-stats-visualizer">Stats Visualizer</a> for HAProxy.<br>We hope this can be helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33daa87ce7f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL cluster migration made simple]]></title>
            <link>https://treatwell.engineering/postgresql-cluster-migration-made-simple-38d996171a44?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/38d996171a44</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[aurora]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[eks-cluster]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 10:59:18 GMT</pubDate>
            <atom:updated>2023-11-16T14:07:34.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4fs88IpWm1tiEP4AIbb4w.png" /><figcaption>An expressive oil painting of an elephant jumping between two planets</figcaption></figure><h3>Intro</h3><p>In a company’s lifetime, growth also means being able to easily migrate between different systems. However, this can be challenging when dealing with stateful systems like PostgreSQL.</p><p>In Treatwell we migrated from bare-metal servers to AWS cloud infrastructure, as detailed in a previous story:</p><p><a href="https://treatwell.engineering/vpn-tunnels-how-we-used-them-to-migrate-our-platform-to-aws-66b5db2a74ad">VPN Tunnels: how we used them to migrate our platform to AWS</a></p><p>During that migration, we followed a <strong>lift-and-shift </strong>approach, changing the base Kubernetes platform while keeping the same structure and machine performance.<br>This did not involve migrating to cloud-managed services.</p><p>After this initial challenge, we gradually <strong>migrated to cloud-managed services</strong>, achieving a “stateless” EKS cluster — a critical step for our blue/green strategy during any cluster upgrade.</p><p>During this process, the main PostgreSQL cluster became the most delicate stateful workload to move due to its critical role in our platform and its substantial size.</p><blockquote><strong><em>Disclaimer</em></strong><em>: To use the built-in logical replication as explained in this article, PostgreSQL ≥ 10 is required on the source system.</em></blockquote><h3>Context</h3><p>Let’s briefly look at the context, explaining both source and destination systems.</p><h4>Source K8S PostgreSQL</h4><p>The source system is a PostgreSQL cluster running on Kubernetes, with one primary and two read-only replicas.</p><p>It operates in an <strong>AWS EKS cluster</strong>, and each instance runs on a r6i.8xlarge node, using EBS disks with io2 class on the primary and gp3 class on readers (this storage setup has some limitations, but it’s a good balance between costs and performances).</p><p>PostgreSQL is running version 14.5.</p><h4>Destination Aurora PostgreSQL</h4><p>After much research, we chose <strong>Aurora</strong> over RDS because it would better fit our needs.</p><p>We selected the most similar database instance, db.r6g.8xlarge, with the nearest PostgreSQL version, 14.8.</p><p>We opted for <strong>Aurora I/O Optimised </strong>to skip the storage topic and save costs compared to provisioned IOPS.</p><h4>Intra-system communication</h4><p>Both the source and destination systems run in the same AWS account, requiring minimal tweaks to Security Groups for proper communication.</p><p>If direct communication is not possible, an alternative is discussed in the article about <a href="https://treatwell.engineering/">how we used VPNs to migrate other systems to AWS</a>.</p><h3>Migration possibilities</h3><p>For a PostgreSQL — PostgreSQL migration in RDS/Aurora, AWS provides <a href="https://docs.aws.amazon.com/dms/latest/sbs/chap-manageddatabases.postgresql-rds-postgresql.html">several options</a>:</p><ul><li>pg_dump &amp; pg_restore</li><li>Managed tools such as AWS DMS</li><li>Hybrid approach combining the two options above</li></ul><p>Due to the database size and the importance of our product to provide optimal uptime, we discarded thepg_dump &amp; pg_restoreoption as it would result in more than <strong>10 hours of downtime</strong>. <br>Although we explored <strong>AWS DMS, encountering multiple issues </strong>and an extensive <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html#CHAP_Source.PostgreSQL.Limitations">limitations list</a> led us to consider another approach.</p><p>The AWS DMS system uses the PostgreSQL CDC (change data capture) feature provided by <a href="https://www.postgresql.org/docs/14/logical-replication.html">native logical replication</a>. So, <strong>we explored using the built-in logical replication for the entire process</strong>, with <a href="https://www.postgresql.org/docs/14/logical-replication-restrictions.html">fewer restrictions</a> than AWS DMS. <br>All of them are easily workaround-able, such as:</p><ul><li><strong>DDL commands are not replicated</strong>: we will block those changes in our codebase for the migration period</li><li><strong>Sequence data is not replicated</strong>: we will align all available sequences just before switching to the new database</li><li><strong>Large objects are not replicated</strong>: we don’t use them</li></ul><p>DMS uses it only to keep the data up to date, but the <strong>Logical Replication allows to do a full data migration from scratch</strong>, keeping the right constraints on tables and keeping monitored the process for the entire duration.</p><h3>Execution</h3><p>In this section, we’ll cover each migration step as we followed them.</p><h4>Setting right parameters</h4><p>The logical replication requires wal_level = &#39;logical&#39; set on the source system.<br>To speed up the initial data migration, we increased some settings related to replication itself: max_replication_slots = 15, max_wal_senders = 16 and max_worker_processes = 14.</p><p>These settings can be checked at runtime with:</p><pre>SELECT name, setting <br>  FROM pg_settings <br>WHERE name IN (<br>      &#39;wal_level&#39;, <br>      &#39;max_worker_processes&#39;, <br>      &#39;max_replication_slots&#39;, <br>      &#39;max_wal_senders&#39;<br>);</pre><blockquote>Since a database migration is not something easy and it obviously brings risks, It’s recommended to mirror the source PostgreSQL configuration in the destination system.</blockquote><h4>Ensure connectivity</h4><p>Within the same K8S Namespace as the source Postgres instance, a new deployment (toolbox) was created, and connectivity between the two systems was checked.</p><h4>Expose the source database to Aurora</h4><p>The source database needs to be exposed and directly accessible from the target cluster. <strong>We created a specific Kubernetes service</strong> for this migration:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: database-nodeport-service<br>  namespace: database-namespace<br>spec:<br>  selector:<br>    postgres/cluster: database<br>    postgres/role: primary<br>  ports:<br>    - name: p5432<br>      protocol: TCP<br>      port: 5432<br>      targetPort: 5432<br>      nodePort: 30432<br>  type: NodePort<br>  sessionAffinity: None<br>  externalTrafficPolicy: Cluster<br>  internalTrafficPolicy: Cluster</pre><p>We then edited the <strong>AWS security group</strong>, allowing Aurora to reach the source Postgres instance in Kubernetes.<br>This can be done by adding an <strong>Inbound Rule</strong> for the 30432 port, with a meaningful description such as “Allow Aurora to access K8S PG instance”:</p><pre>aws ec2 authorize-security-group-ingress \<br>--group-id sg-1234567890abcdef0 \<br>--ip-permissions &#39;[<br>{<br>  &quot;IpProtocol&quot;: &quot;tcp&quot;, <br>  &quot;FromPort&quot;: 30432, <br>  &quot;ToPort&quot;: 30432, <br>  &quot;IpRanges&quot;: [<br>    {<br>      &quot;CidrIp&quot;: &quot;sg-018a76217e6911189&quot;, <br>      &quot;Allow Aurora to access K8S PG instance&quot;<br>    }<br>  ]<br>}]&#39;</pre><p>We then used this command from the toolbox pod to check the connectivity (where 10.x.x.x is the node IP, in our case the EC2 instance):</p><pre>psql -U postgres -h 10.x.x.x -p 30432</pre><h4>Destination database creation</h4><p>The Aurora cluster was already up &amp; running on AWS, so we created the required database:</p><pre>psql -U postgres -h 10.x.x.x -p 30432 -c &quot;CREATE DATABASE database_name&quot;;</pre><p>The database is empty, and since <strong>logical replication won’t replicate the schema, we did it manually</strong>. From the toolbox pod, we copied the current schema:</p><pre>pg_dump database \<br>  -U postgres \<br>  -h local-database-service \<br>  --schema-only &gt; schema.sql</pre><p>and uploaded it into Aurora:</p><pre>psql -U postgres -h new-database.example.org -d database &lt; schema.sql</pre><h4>Logical replication, publication and subscription</h4><p>With the two systems ready to communicate, we created a <a href="https://www.postgresql.org/docs/14/logical-replication-publication.html">publication</a> on the source database:</p><pre>psql -U postgres \<br>     -h local-database-service \<br>     -d database \<br>     -c &quot;CREATE PUBLICATION my_publication1 FOR ALL TABLES;</pre><p>Next, we moved to the destination database, creating the relative <a href="https://www.postgresql.org/docs/14/logical-replication-subscription.html">subscription</a>:</p><pre>psql -U postgres \<br>     -h new-database.exaple.org \<br>     -d database \<br>     -c &quot;CREATE SUBSCRIPTION my_subscription1 <br>          CONNECTION &#39;host=10.x.x.x <br>                    port=30432 <br>                    dbname=database <br>                    user={user} <br>                    password={PASSWORD}&#39; <br>          PUBLICATION my_publication1;&quot;</pre><p>This creates a subscription to the recently created publication, along with a replication slot. If everything went well, the result of the query should inform you with a message similar to: NOTICE: created replication slot &quot;my_subscription1&quot; on publisher.</p><p><strong>Please note that the crucial flag </strong><a href="https://www.postgresql.org/docs/current/sql-createsubscription.html#SQL-CREATESUBSCRIPTION-WITH-COPY-DATA"><strong>copy_data</strong></a><strong> is enabled by default, so replication will automatically start copying all the data to the destination.</strong></p><h4>Check replication status</h4><p>Once the subscription was created, we started checking the replication status. Here are a couple of useful queries:</p><pre>-- CHECK REPLICATION SLOTS (on source)<br>SELECT * FROM pg_stat_replication WHERE application_name != &#39;walreceiver&#39;;<br><br>-- CHECK REPLICATION STATE (on the destination)<br>-- srsubstate code: i = initialize, d = data is being copied, f = finished table copy, s = synchronized, r = ready (normal replication)<br>SELECT srsubstate, COUNT(1) <br>FROM pg_catalog.pg_subscription_rel subs <br>JOIN pg_catalog.pg_class relmap ON subs.srrelid = relmap.oid <br>GROUP BY 1;<br>-- ENSURE ALL TABLES ARE IN &#39;r&#39; STATE<br>SELECT subs.*,relmap.relname <br>FROM pg_catalog.pg_subscription_rel subs <br>JOIN pg_catalog.pg_class relmap ON subs.srrelid = relmap.oid<br>WHERE srsubstate &lt;&gt; &#39;r&#39;;</pre><h4>Switch to the new PostgreSQL</h4><p>When the logical replica finished moving data and was synchronized with the primary instance (check the queries above!), <strong>we were ready to do the actual migration</strong>.</p><p>Before it, it’s advisable to <a href="https://www.postgresql.org/docs/current/sql-analyze.html">ANALYZE</a> the most important tables to let PostgreSQL be ready to start with up-to-date statistics:</p><pre>-- CHECK ANALYZE STATUS<br>SELECT schemaname, relname, last_autoanalyze, last_analyze <br>FROM pg_stat_all_tables <br>WHERE schemaname = &#39;public&#39; <br>ORDER BY 3 ASC;<br><br>-- FORCE ANALYZE IN A SINGLE TABLE<br>ANALYZE my_table;</pre><p><em>During this process, we also switched the traffic for read-only replicas to Aurora, as they didn’t require additional work to use them.</em></p><p>As mentioned earlier, as a limitation of logical replication, <strong>sequences are not replicated</strong>. So, <a href="https://wiki.postgresql.org/wiki/Fixing_Sequences">a script is needed to align them.</a> This command will prepare a SQL query to do it:</p><pre>psql -Atq -U postgres -h new-database.example.com -d database -c &quot;SELECT <br>    &#39;SELECT SETVAL(&#39; ||<br>       quote_literal(quote_ident(sequence_namespace.nspname) || &#39;.&#39; || quote_ident(class_sequence.relname)) ||<br>       &#39;, COALESCE(MAX(&#39; ||quote_ident(pg_attribute.attname)|| &#39;), 1) ) FROM &#39; ||<br>       quote_ident(table_namespace.nspname)|| &#39;.&#39;||quote_ident(class_table.relname)|| &#39;;&#39;<br>FROM pg_depend <br>    INNER JOIN pg_class AS class_sequence<br>        ON class_sequence.oid = pg_depend.objid <br>            AND class_sequence.relkind = &#39;S&#39;<br>    INNER JOIN pg_class AS class_table<br>        ON class_table.oid = pg_depend.refobjid<br>    INNER JOIN pg_attribute <br>        ON pg_attribute.attrelid = class_table.oid<br>            AND pg_depend.refobjsubid = pg_attribute.attnum<br>    INNER JOIN pg_namespace as table_namespace<br>        ON table_namespace.oid = class_table.relnamespace<br>    INNER JOIN pg_namespace AS sequence_namespace<br>        ON sequence_namespace.oid = class_sequence.relnamespace<br>ORDER BY sequence_namespace.nspname, class_sequence.relname;&quot; -o set_sequencies.sql</pre><p>At this point, we shut down the PGBouncer connected to the old primary instance. <br><strong>The downtime started. </strong><br>First, we waited a little bit to let all updates be propagated by the logical replication.</p><p>Then, we aligned the sequences on Aurora, using the script we created earlier:</p><pre>psql -U postgres \<br>     -h new-database.exaple.org \<br>     -d database \<br>     -f set_sequencies.sql</pre><p>To check that sequences are properly aligned, here are some useful SQL commands:</p><pre>SELECT last_value FROM my_table_id_seq;<br>SELECT max(id) FROM my_table;</pre><p>If everything is fine, the new database is ready to serve the traffic.</p><p><strong>We switched the PGBouncer to the new database endpoint, and the system was up again.</strong></p><p>We then dropped the logical replication subscription:</p><pre>psql -U postgres \<br>     -h new-database.example.org \<br>     -d database <br>     -c &quot;DROP SUBSCRIPTION my_subscription1;&quot;</pre><p>In our case, <strong>the downtime lasted 4 minutes during the night</strong>, only a few web requests were lost, and failed asynchronous jobs were re-enqueued.</p><h3>Clean up</h3><p>After the migration, we shut down the old database cluster. It was as if it never happened to our platform.</p><h3>Credits</h3><p>A huge thank you to <a href="https://medium.com/@arizz96">Alessandro Rizzo</a>, who helped me in this adventure (and in all the pasts!).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38d996171a44" width="1" height="1" alt=""><hr><p><a href="https://treatwell.engineering/postgresql-cluster-migration-made-simple-38d996171a44">PostgreSQL cluster migration made simple</a> was originally published in <a href="https://treatwell.engineering/">Treatwell Product Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically scale your Rails application with HPA]]></title>
            <link>https://treatwell.engineering/automatically-scale-your-rails-application-with-hpa-25506ef04a19?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/25506ef04a19</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[hpa]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[sidekiq]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 08:14:53 GMT</pubDate>
            <atom:updated>2023-08-23T08:29:45.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WG2FVY0ooe66qytSM4P-Hg.jpeg" /></figure><p>Scalability is something we need to face when the application grows over time, and the easy solution to accomplish it is to add more replicas to our K8S deployments.</p><blockquote><em>Nice and easy, but at the same scale costs grow, and that’s not what we want.</em></blockquote><p>During 2023, in Treatwell, we replaced our bare metal servers with AWS cloud instances (check <a href="https://treatwell.engineering/vpn-tunnels-how-we-used-them-to-migrate-our-platform-to-aws-66b5db2a74ad">VPN Tunnels: how we used them to migrate our platform to AWS</a> to read more on how we managed to do it), and having a cloud provider allowed high elasticity when talking about instance spin up and shutdown. Obviously, all of this is at a different cost, but there’s a high margin of saving if the application scale is always adequate to the traffic, without overpowering our system when not needed.</p><p>Our SaaS application traffic depends on business hours, in particular on beauty industry working days and hours, and in the majority of cases, there’s high traffic from Tuesday morning to Saturday evening (beauty salons are usually closed during Sunday and Monday).</p><figure><img alt="1-week application web traffic where 16 Jul 2023 is Sunday" src="https://cdn-images-1.medium.com/max/700/0*9QSNXGDCVgi3NC-G.png" /><figcaption>1-week application web traffic where 16 Jul 2023 is Sunday</figcaption></figure><h3>Current application structure</h3><p>The Treatwell SaaS application we wanted to scale is a Ruby on Rails application using Puma as the web server, Sidekiq for asynchronous jobs execution, PostgreSQL as the database, and Redis for the cache.</p><blockquote>We’re covering just the Rails application side of things in this article, but it’s strongly recommended to check and adjust PostgreSQL and Redis connection settings if needed to keep up with the load.</blockquote><p>Everything is running in a Kubernetes cluster, managed by an Infrastructure-as-a-Code application we maintain internally.</p><h3>Kubernetes HPA</h3><p>Kubernetes provides <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizontal Pod Autoscaler</a> (HPA), an internal tool that allows automatic horizontal scaling of deployments, acting on replicas count. Its configuration requires one or more metrics to be used and a target value to be met.<br>Once configured, the desired number of replicas is calculated with the following formula:</p><pre>desiredReplicas = ceil[currentReplicas * ( currentMetricValue / <br>desiredMetricValue )]</pre><h3>Metric collector</h3><p>We’re using Prometheus to collect our application base metrics (CPU, memory, disk, network), but for this task, we need to go further: <strong>we need custom metrics.</strong></p><p>Why? Because usually HPA uses metrics about the CPU and memory.<br>This unfortunately doesn’t fit with our needs.<br>For asynchronous jobs for example you could have workers that are designed to use lots of CPU and memory for intensive work. So they are not metrics that we can use. <br>Due to this, we didn’t need to have only a custom metric exporting system for our workloads, but we also needed to let HPA use it, because this is not something available out of the box.</p><p>After some research and tries with different tools (like <a href="https://github.com/kubernetes-sigs/prometheus-adapter">prometheus-adapter</a>, which needed a very complex configuration), we went for the <a href="https://github.com/zalando-incubator/kube-metrics-adapter"><strong>kube-metrics-adapter</strong></a><strong> project by Zalando</strong>, which allows a clean usage of custom metrics for HPA.</p><p>It’s easily deployable with an helm chart, but keep attention that it misses required APIService to run (one for <strong>custom</strong> and one for <strong>external</strong> metrics):</p><pre>---<br>apiVersion: apiregistration.k8s.io/v1<br>kind: APIService<br>metadata:<br>  name: v1beta1.custom.metrics.k8s.io<br>spec:<br>  group: custom.metrics.k8s.io<br>  groupPriorityMinimum: 100<br>  insecureSkipTLSVerify: true<br>  service:<br>    name: kube-metrics-adapter<br>    namespace: monitoring<br>  version: v1beta1<br>  versionPriority: 100<br>---<br>apiVersion: apiregistration.k8s.io/v1<br>kind: APIService<br>metadata:<br>  name: v1beta1.external.metrics.k8s.io<br>spec:<br>  group: external.metrics.k8s.io<br>  groupPriorityMinimum: 100<br>  insecureSkipTLSVerify: true<br>  service:<br>    name: kube-metrics-adapter<br>    namespace: monitoring<br>  version: v1beta1<br>  versionPriority: 100</pre><p>At this point, the adapter for custom Prometheus metrics was available and ready to be used for our HPAs.</p><h3>Metric exporter</h3><p>To properly configure HPA metrics’ queries to scale the Rails application, some Rails-specific metrics are needed. Luckily, there is the <a href="https://github.com/discourse/prometheus_exporter"><strong>prometheus_exporter</strong></a><strong> gem </strong>that allows Prometheus metrics exporting and comes with a lot of prebuilt ones.</p><p>After installing it, we followed the guide available for this gem:</p><pre># Middleware initializatio in application.rb<br>require &#39;prometheus_exporter&#39;<br>require &#39;prometheus_exporter/middleware&#39;<br># This reports stats per request like HTTP status and timings<br>app.middleware.unshift PrometheusExporter::Middleware<br><br># Puma configuration<br>on_worker_boot do<br>  require &#39;prometheus_exporter&#39;<br>  require &#39;prometheus_exporter/instrumentation&#39;<br>  PrometheusExporter::Instrumentation::ActiveRecord.start(<br>    custom_labels: { type: &#39;puma_worker&#39; },<br>    config_labels: %i[database host]<br>  )<br>end<br>after_worker_boot do<br>  require &#39;prometheus_exporter&#39;<br>  require &#39;prometheus_exporter/instrumentation&#39;<br>  # optional check, avoids spinning up and down threads per worker<br>  PrometheusExporter::Instrumentation::Puma.start unless PrometheusExporter::Instrumentation::Puma.started?<br>end<br><br># Sidekiq initializer<br>require &#39;prometheus_exporter&#39;<br>require &#39;prometheus_exporter/instrumentation&#39;<br>config.server_middleware do |chain|<br>  chain.add PrometheusExporter::Instrumentation::Sidekiq<br>end<br>config.death_handlers &lt;&lt; PrometheusExporter::Instrumentation::Sidekiq.death_handler<br>config.on(:startup) do<br>  PrometheusExporter::Instrumentation::ActiveRecord.start(<br>    custom_labels: { type: &#39;sidekiq&#39; },<br>    config_labels: %i[database host]<br>  )<br>  PrometheusExporter::Instrumentation::Process.start type: &#39;sidekiq&#39;<br>  PrometheusExporter::Instrumentation::SidekiqProcess.start<br>end<br>at_exit do<br>  PrometheusExporter::Client.default.stop(wait_timeout_seconds: 10)<br>end</pre><p><strong>We also created a Rails task that runs in a dedicated workload,</strong> that collects generic statistics about Sidekiq queues; this prevents having a lot of duplicated data points, that would occur in the case of letting each Sidekiq worker to export the same queue metrics.<br>Every worker will however export its own metrics (jobs timings, memory used etc)</p><pre># frozen_string_literal: true<br>desc &#39;Export queues and stats from Sidekiq&#39;<br>task sidekiq_metrics: :environment do<br>  require &#39;prometheus_exporter&#39;<br>  require &#39;prometheus_exporter/instrumentation&#39;<br>  require &#39;prometheus_exporter/server&#39;<br><br>  server = PrometheusExporter::Server::WebServer.new(bind: &#39;0.0.0.0&#39;, port: 9394, verbose: true)<br>  server.start<br>  PrometheusExporter::Client.default = PrometheusExporter::LocalClient.new(collector: server.collector)<br>  PrometheusExporter::Metric::Base.default_prefix = &#39;ruby_&#39;<br>  PrometheusExporter::Instrumentation::SidekiqQueue.start(all_queues: true)<br>  PrometheusExporter::Instrumentation::SidekiqStats.start<br>  sleep<br>end</pre><p>We configured our IaC application to let each pod that exports metrics have a sidecar container collecting and exposing them to Prometheus:</p><pre>- name: metrics-container<br>  image: uala/prometheus_exporter<br>  resources:<br>    limits:<br>      cpu: 50m<br>      memory: 32Mi<br>    requests:<br>      cpu: 50m<br>      memory: 32Mi<br>  livenessProbe:<br>    httpGet:<br>      path: /ping<br>      port: 9394<br>      scheme: HTTP<br>    timeoutSeconds: 3<br>    periodSeconds: 10<br>    successThreshold: 1<br>    failureThreshold: 5<br>  readinessProbe:<br>    httpGet:<br>      path: /ping<br>      port: 9394<br>      scheme: HTTP<br>    timeoutSeconds: 3<br>    periodSeconds: 10<br>    successThreshold: 2<br>    failureThreshold: 5<br>  startupProbe:<br>    httpGet:<br>      path: /ping<br>      port: 9394<br>      scheme: HTTP<br>    timeoutSeconds: 1<br>    periodSeconds: 2<br>    successThreshold: 1<br>    failureThreshold: 5</pre><p>And its relative service with Prometheus scraping configuration:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: deployment-metrics-service<br>  namespace: default<br>  annotations:<br>    prometheus.io/path: /metrics<br>    prometheus.io/port: &#39;9394&#39;<br>    prometheus.io/scrape: &#39;true&#39;<br>spec:<br>  ports:<br>    - name: &#39;9394&#39;<br>      protocol: TCP<br>      port: 9394<br>      targetPort: 9394<br>  selector:<br>    app: default-deployment-a1b2c3d4<br>  clusterIP: 172.20.xx.xx<br>  clusterIPs:<br>    - 172.20.xx.xx<br>  type: ClusterIP</pre><blockquote><em>Metrics collecting is now a thing, let’s move on and make use of them.</em></blockquote><h3>HPA configuration</h3><p>Using the <a href="https://github.com/zalando-incubator/kube-metrics-adapter"><strong>kube-metrics-adapter</strong></a>, an HPA object is composed as follows:</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: deployment-hpa<br>  namespace: default<br>  annotations:<br>    metric-config.external.deployment-custom-metric-1.prometheus/interval: 15s<br>    metric-config.external.deployment-custom-metric-1.prometheus/prometheus-server: http://prometheus.kube-system.svc.cluster.local:9090<br>    metric-config.external.deployment-custom-metric-1.prometheus/query: ...<br>spec:<br>  scaleTargetRef:<br>    kind: Deployment<br>    name: deployment<br>    apiVersion: apps/v1<br>  minReplicas: ...<br>  maxReplicas: ...<br>  metrics:<br>    - type: External<br>      external:<br>        metric:<br>          name: deployment-custom-metric-1<br>          selector:<br>            matchLabels:<br>              type: prometheus<br>        target:<br>          type: Value<br>          value: ...<br>  behavior:<br>    scaleUp:<br>      stabilizationWindowSeconds: 120<br>      selectPolicy: Min<br>      policies:<br>        - type: Percent<br>          value: 50<br>          periodSeconds: 60<br>        - type: Pods<br>          value: 2<br>          periodSeconds: 60<br>    scaleDown:<br>      stabilizationWindowSeconds: 120<br>      selectPolicy: Max<br>      policies:<br>        - type: Pods<br>          value: 1<br>          periodSeconds: 60</pre><p>In metadata we can configure the metric(s) used, as long as the Prometheus polling interval and the server address.<br>The spec contain the definition of the HPA itself, so the referenced Deployment , the metric(s) used (by metric name) with the wanted target value and a scale behaviour , used to fine-tune the scale window and size.</p><h3>Web traffic scalability</h3><p>As we saw at the beginning of this article, our web traffic has a predictable curve during the week, and it’s quite stable during the day after the initial growth when clients connect, so we leveraged on puma_max_threads and puma_thread_capacity metrics to scale it, setting an upper limit of 80 (that corresponds to 80% total usage of Puma threads available), resulting in this query:</p><pre>round(<br>  (<br>    sum by (kubernetes_name) (ruby_puma_max_threads{kubernetes_namespace=&quot;default&quot;, kubernetes_name=&quot;deployment-metrics-service&quot;}) - <br>    sum by (kubernetes_name) (ruby_puma_thread_pool_capacity{kubernetes_namespace=&quot;default&quot;, kubernetes_name=&quot;deployment-metrics-service&quot;}) <br>  ) / <br>  sum by (kubernetes_name) (ruby_puma_max_threads{kubernetes_namespace=&quot;default&quot;, kubernetes_name=&quot;deployment-metrics-service&quot;}) <br>  * 100 <br>)</pre><p>In our experience with this Rails application, we noticed that when overloading the web server, response time quickly increases, so we added a second metric based on http_request_duration_seconds , setting an upper limit of 100 (that corresponds to 100ms of response time), resulting in this query:</p><pre>round(<br>  avg by(kubernetes_name) (ruby_http_request_duration_seconds{kubernetes_namespace=&quot;default&quot;, kubernetes_name=&quot;deployment-metrics-service&quot;}) <br>  * 1000<br>)</pre><h3>Asynchronous jobs scalability</h3><p>While web traffic is quite stable during the day, asynchronous job queues are different: some of them depend on cron tasks or external events, and their traffic is unpredictable; others mimic the web traffic situation, meaning that more web traffic enqueued more jobs, so the load between the two is related.</p><p>For the first group of queues, we went for sidekiq_queue_latency_seconds (<em>“The number of seconds between oldest job being pushed to the queue and current time.”</em>), and setting an upper limit of 20 (that corresponds to 20 seconds of latency), resulting in this query :</p><pre>round(<br>  avg by(queue) (ruby_sidekiq_queue_latency_seconds{kubernetes_namespace=&quot;default&quot;, queue=&quot;queue-name&quot;}),<br>  1<br>)</pre><p>The usage of the latency works well with spikes of load but produces a high number of scales up and down where the traffic is more stable during a larger time window. To properly scale them, in addition to the latency , we added a query that monitors the capacity usage of the queue, using sidekiq_process_busy and sidekiq_process_concurrency , setting an upper limit of 100 (that corresponds to 100% usage of queue workers’ capacity), resulting in this query :</p><pre>round(<br>  sum(avg_over_time(ruby_sidekiq_process_busy{kubernetes_namespace=&quot;default&quot;, queues=&quot;queue&quot;}[5m])) /<br>  sum(avg_over_time(ruby_sidekiq_process_concurrency{kubernetes_namespace=&quot;default&quot;, queues=&quot;queue&quot;}[5m]))<br>  * 100,<br>  1<br>)</pre><h3>Behavior of HPA</h3><p>The behavior node in HPA allows fine-tuning of the scale-up and scale-down actions over the deployment. Multiple <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/#scaling-policies">policies</a> can be set, based on the number of Pods or by replica Percent ; when more than one policy is set, the priority of them can be set with selectPolicy .</p><p>A special mention must go to the stabilizationWindowSeconds , which approximates a rolling maximum, and avoids having the scaling algorithm frequently remove pods only to trigger recreating an equivalent pod just moments later.</p><p>This has been really helpful to stabilise our workloads avoiding to much fluctuation.</p><h3>Results</h3><p>We can see HPA in action for both Sidekiq and Puma workloads in the following screenshots.</p><p>First one is HPA enabled for Sidekiq workers, based only on queue latency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mdXY-IB054Njem1Y.png" /><figcaption>Sidekiq HPA based on queue latency only</figcaption></figure><p>This one instead is a HPA enabled for Sidekiq workers using also a second metrics about the RPM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*alExeQuFexYkJY_F.png" /><figcaption>Sidekiq HPA based on queue latency and stabilized with RPM</figcaption></figure><p>Finally, the HPA running with our Puma servers: as you can see the workers scales up based on the RPM, keeping the response time under the limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1B9DR0IjqiAc7CDb.png" /><figcaption>Puma HPA based on RPM</figcaption></figure><p>By utilising Horizontal Pod Autoscaling (HPA) in our workloads, the number of required replicas has been significantly reduced during periods of low demand.<strong> This directly led to a reduction in the number of instances needed, effectively decreasing our monthly costs by 35–40%</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25506ef04a19" width="1" height="1" alt=""><hr><p><a href="https://treatwell.engineering/automatically-scale-your-rails-application-with-hpa-25506ef04a19">Automatically scale your Rails application with HPA</a> was originally published in <a href="https://treatwell.engineering/">Treatwell Product Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VPN Tunnels: how we used them to migrate our platform to AWS]]></title>
            <link>https://treatwell.engineering/vpn-tunnels-how-we-used-them-to-migrate-our-platform-to-aws-66b5db2a74ad?source=rss-cb8a1d86e1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b5db2a74ad</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[tailscale]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cluster]]></category>
            <dc:creator><![CDATA[Luca Mattivi]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 15:56:25 GMT</pubDate>
            <atom:updated>2023-06-08T15:56:25.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*ZHw7JHMeLJFyJhAIVzDYhQ.png" /></figure><h3>Intro</h3><p>Since the beginning of Uala, we always focused on using the best and latest technology available. We’re proud to said that we used <strong><em>Docker</em></strong> when it was in beta, adopted <strong><em>Rancher</em></strong> since the first version, and later transitioned to <strong><em>Kubernetes</em></strong> once we felt confident in our ability to manage it (v1.15).</p><p>Initially, <strong>we relied on bare-metal servers </strong>(using Hetzner), which meant that we had to handle every aspect of our on-premises infrastructure without any easy solutions.</p><p>However, as our company grew, including the significant merger with Treatwell, in last years we reached the top of the market in our business domain.</p><blockquote>Scalability and availability quickly became the two main priorities on the platform side.</blockquote><p>Considering the existing platform team at Treatwell’s familiarity with AWS, we made the decision at the end of 2022 to <strong>migrate everything from bare-metal servers to AWS</strong>.</p><p>This transition presented us with a challenge: <strong>How could we move our infrastructure to AWS without any downtime or negative impact on productivity?</strong></p><h3>The Challenge with High Traffic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*eiqZuo0IR6M9eJMi1eWuXw.jpeg" /></figure><p>Our platform experiences <strong>high traffic 24/7</strong> and consists of <strong>multiple terabyte-sized databases</strong>.</p><blockquote>A big-bang approach to migration was not feasible, so we needed to find another way.</blockquote><p>While several services enable <strong>communication between different clusters</strong>, most of them are complex and <strong>directly rely on the underlying network</strong> of the cluster. <br>Since we lacked confidence in those solutions, <strong>we had to explore other options.</strong></p><p>We considered using a <strong>VPN as a potential solution</strong>. However, after attempting this approach, we quickly realized that managing a VPN at that scale was chaotic, especially given that <strong>containers are not VPN-friendly</strong>.</p><p>After extensive research, we discovered <a href="https://tailscale.com/"><strong>Tailscale</strong></a>, a <strong>user-friendly tool for VPN management</strong>.</p><h3>VPN Tunnels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mTmc5CHBccabX3TnvMLctw.jpeg" /></figure><p>What distinguishes Tailscale from a standard VPN is its effortless setup. <strong>Everything works out of the box</strong>, offering perfect network management. It can detect connection failures and automatically reconnect, and we found that <strong>it works flawlessly with containers</strong>.</p><p>Nevertheless, relying on a third-party service introduces external dependencies, which is something we usually avoid. <br>Fortunately, <strong>the Tailscale client is </strong><a href="https://github.com/tailscale/tailscale"><strong>open source</strong></a>, and there is a great project called <a href="https://github.com/juanfont/headscale"><strong>Headscale</strong></a> (supported by Tailscale) that aims to make the <strong>server part open source as well</strong>.</p><p>With Tailscale, we found a way to establish communication between different components, but <strong>we were still far from achieving our goal</strong>.</p><blockquote>We can use Tailscale to create multiple VPN Tunnels.</blockquote><h3>VPN performance</h3><p>To ensure a seamless migration without impacting the platform, we needed to verify the performance and stability of the communication.</p><p>Two factors affected these aspects: <strong>relays and resources.</strong></p><p>Initially, when we attempted to replicate our main Postgres database, we encountered a <strong>significant decrease in network speed</strong>, only achieving 20MB/s.</p><p>After investigating and debugging Tailscale, we discovered that <strong>we were using a </strong><a href="https://tailscale.com/glossary/2020-04-02-relay/"><strong>Tailscale Relay</strong></a>, which introduced substantial latency between the two clients.</p><p>This was expected since the clients couldn’t communicate directly and required a relay to establish a connection.</p><p>Unfortunately, this was not an acceptable solution for us. However, after conducting tests, we realized that enabling the hostNetwork option on one of the vpn-client pods resolved the issue. It allowed for a <strong>direct connection between the two clients</strong>.</p><p>After making this adjustment, we tested again, but the bandwidth remained too low, reaching only about 60MB/s.</p><p>The solution was straightforward this time: to accommodate higher bandwidth, <strong>the vpn-clients required more resources</strong>.</p><blockquote>Through further testing and optimization, we achieved a <strong>stable bandwidth of 150MB/s with a latency of 5–6ms</strong> for each vpn-tunnel.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*66FHpKJgCay3-ScYnbGpgA.png" /><figcaption>Bandwidth of a VPN-Tunnel</figcaption></figure><blockquote>With the performance requirements met, we were ready to proceed.</blockquote><h3>Practice in Kubernetes</h3><p>To simplify management, <strong>we created a </strong><a href="https://github.com/Leen15/tailscale"><strong>custom Docker image</strong></a> that facilitated <strong>proxying one or more services in either direction through Tailscale</strong>.</p><p>For example, our <strong>main Postgres instance needed to persist on the old cluster until the final promotion</strong> of a new replica (scheduled for the last day of migration). Additionally, <strong>we had to expose it in the new cluster</strong> so that every service could write to it, and new replicas could be created and kept aligned with it. <br>The following schema illustrates our approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*3PjlRr5hnae3F-qZSoH_1Q.png" /><figcaption>Example of the database communication with Tailscale</figcaption></figure><blockquote>While we knew how to utilize VPN tunnels in Kubernetes, we needed to integrate them into our Infrastructure as Code (IaC) to ensure easy usage during the migration.</blockquote><h3>Integrating VPN Tunnels with IaC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*NASyYKhonQPrFhFjAcqk3g.jpeg" /></figure><p>Our migration plan involved creating a new namespace where all the Tailscale clients would run. We then <strong>remapped the application services to the Tailscale clients</strong> within that namespace. Consequently, <strong>at the application level, the migration would be transparent</strong>. Each time we moved an application to the new cluster, the Kubernetes services would point to the migrated application without requiring any changes.</p><p>Here’s how we accomplished this using <a href="https://cdk8s.io/"><strong>cdk8s</strong></a>, the IaC tool we employ.</p><p>Firstly, we created a <strong>new component</strong> for the Tailscale client:</p><pre>export class TailscaleClient extends Core.StatefulSet {<br>  constructor(scope: Construct, id: string, options: TailscaleClientOptions) {<br>    const proxyEnvs : EnvVar[] = [];<br>    proxyEnvs.push(<br>      { name: &quot;TAILSCALE_HOSTNAME&quot;, value: options.tailscaleHostname! }<br>    )<br>    if (options?.proxies) {<br>      options.proxies.forEach(proxy =&gt; {<br>        const destinationPort = (proxy.destination.endsWith(&#39;.svc.cluster.local&#39;))<br>                                  ? proxy.servicePort<br>                                  : proxy.port;<br><br>        proxyEnvs.push(<br>          {<br>            name: `PROXY_HOST_${proxy.port}`,<br>            value: `${proxy.destination}:${destinationPort}:${proxy.dnsServer}`<br>          }<br>        );<br><br>        new KubeService(scope, `${id}-${proxy.port}-service`, {<br>          spec: {<br>            type: &quot;ClusterIP&quot;,<br>            ports: [<br>              {<br>                port: proxy.servicePort,<br>                name: proxy.servicePort.toString(),<br>                targetPort: IntOrString.fromNumber(destinationPort)<br>              }<br>            ],<br>            selector: { app: Names.toLabelValue(scope, { extra: [id] }) }<br>          }<br>        });<br>      });<br>    }<br><br>    const tailscaleStateVolume : PersistentVolumeClaimTemplate = {<br>      metadata: {<br>        name: &quot;state&quot;,<br>      },<br>      spec: {<br>        storageClassName: options.storageClassName,<br>        accessModes: [&quot;ReadWriteOnce&quot;],<br>        resources: {<br>          requests: {<br>            storage: Quantity.fromString(options.volumeStorage ?? &quot;1Gi&quot;)<br>          }<br>        }<br>      }<br>    }<br><br>    super(scope, id, {<br>      ...options,<br>      name: id,<br>      image: options.image ?? &quot;leen15/tailscale:1.38.4-dns-server&quot;,<br>      serviceType: options.serviceType ?? &quot;Headless&quot;,<br>      envs: [<br>        ...(options.envs || []),<br>        ...proxyEnvs<br>      ],<br>      securityContext: {<br>        capabilities: {<br>          add: [&#39;NET_ADMIN&#39;]<br>        },<br>        privileged: false<br>      },<br>      hostNetwork: options.hostNetwork,<br>      volumeMounts: [<br>        {<br>          name: tailscaleStateVolume.metadata?.name || &quot;&quot;,<br>          mountPath: &quot;/var/lib/tailscale&quot;<br>        },<br>      ],<br>      volumeClaimTemplates: [<br>        tailscaleStateVolume,<br>      ]<br>    });<br>  }<br>}</pre><p>This allowed us to <strong>define a new VPN client</strong> using a YAML configuration:</p><pre>vpn-tunnel:<br>  enabled: true<br>  namespace: vpn-tunnel-aws-staging-indianred<br>  workloadsProps:<br>  - name: vpn-client-be-admin<br>    enabled: true<br>    options:<br>      replicas: 1<br>      storageClassName: gp2<br>      rollingStrategy: StopStart # need to stop first for unattach the volume<br>      volumeStorage: 1Gi<br>      labels:<br>        vpn: client<br>      tailscaleHostname: aws-staging-indianred-client-be-admin<br>      proxies:<br>      - port: 801<br>        servicePort: 80<br>        # web-lb-internal-service.be-admin-env-staging:80<br>        destination: hetz-dev-envs-client-be-admin<br>        dnsServer: 100.100.100.100<br>      - port: 802<br>        servicePort: 80<br>        destination: web-lb-service.be-admin-env-staging.svc.cluster.local<br>        dnsServer: 172.20.0.10<br>      - port: 803<br>        servicePort: 80<br>        destination: web-lb-internal-service.be-admin-env-staging.svc.cluster.local<br>        dnsServer: 172.20.0.10</pre><p><em>What happened here?</em></p><p>We defined a <strong>new vpn-client</strong> for each namespace and specified <strong>a list of services</strong> to be mapped by the <strong>internal proxy</strong> of the vpn-client.</p><blockquote>This setup allowed <strong>every vpn-client to operate in both directions</strong>.</blockquote><p>In the provided example, port 801 was used to expose the port 801 of another vpn-client (running in the hetzner cluster) within the current aws cluster. A new Kubernetes service would be created to expose this on port 80, eliminating the need for any application-level changes. <br>The dnsServer parameter was used to enable the internal proxy of the vpn-client to resolve the destination, in this case, the Headscale dns-server. <br>The other two ports (802 and 803) were used to expose two internal services to the other vpn-client, relying on the cluster dns-server for resolution.</p><p><em>How did we use this client?</em></p><p><strong>We set the service of a not yet migrated application to point to it:</strong></p><pre>beAdmin:<br>  namespace: be-admin-env-staging<br>  workloadsProps:<br>  - name: web<br>    enabled: false<br>  - name: web-lb<br>    enabled: false<br>  - name: web-internal<br>    enabled: false<br>  - name: web-lb-internal<br>    enabled: false<br>  - name: traffic-black-hole<br>    enabled: false<br>  - name: web-lb-internal-service<br>    enabled: true<br>    ingressExtHost: vpn-client-be-admin-801-service.vpn-tunnel-aws-staging-indianred.svc.cluster.local</pre><p><em>The </em><em>ingressExtHost parameter is an alias to create the service with an </em><em>ExternalName.</em></p><p>Consequently, <strong>any other application</strong> that needed to communicate with the web-lb-internal application <strong>interacted directly with the vpn-client</strong>, which then forwarded the traffic to the other cluster.</p><h3>Conclusion</h3><p>We moved every service <strong>one by one</strong>, creating <strong>multiple VPN tunnels</strong> to expose every service in the related cluster that needed to communicate with other services. We also <strong>forwarded the traffic from the old cluster using VPN tunnels</strong> until the DNS records were fully switched.</p><p>This approach enabled us to <strong>migrate our entire platform to a different cluster in another cloud provider</strong> without <strong>any downtime or issues</strong> for end users. <br>Throughout the migration, our developers could seamlessly operate on the applications, ensuring the same development experience as always.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b5db2a74ad" width="1" height="1" alt=""><hr><p><a href="https://treatwell.engineering/vpn-tunnels-how-we-used-them-to-migrate-our-platform-to-aws-66b5db2a74ad">VPN Tunnels: how we used them to migrate our platform to AWS</a> was originally published in <a href="https://treatwell.engineering/">Treatwell Product Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>