<?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 ayushsoni_7 on Medium]]></title>
        <description><![CDATA[Stories by ayushsoni_7 on Medium]]></description>
        <link>https://medium.com/@ayushsoni47.as?source=rss-5d0e9ebaa025------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Wm7-joZDOZoNSApj</url>
            <title>Stories by ayushsoni_7 on Medium</title>
            <link>https://medium.com/@ayushsoni47.as?source=rss-5d0e9ebaa025------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:31:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayushsoni47.as/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[One Repo. Multiple Clouds. Hundreds of Accounts: The Terragrunt Blueprint That Scales]]></title>
            <link>https://medium.com/@ayushsoni47.as/one-repo-multiple-clouds-hundreds-of-accounts-the-terragrunt-blueprint-that-scales-ec56f9111106?source=rss-5d0e9ebaa025------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec56f9111106</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[multicloud-management]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[iaac]]></category>
            <category><![CDATA[terragrunt]]></category>
            <dc:creator><![CDATA[ayushsoni_7]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 12:11:13 GMT</pubDate>
            <atom:updated>2026-02-23T12:11:13.330Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>At small scale, Terraform feels simple.</p><p>A few accounts. A few modules. One cloud.<br>Plans are predictable. Context lives in your head.</p><p>But scale changes the nature of the problem.</p><p>When infrastructure spans multiple environments, dozens of accounts, and eventually multiple clouds, the challenge is no longer writing Terraform code. The challenge becomes operating it safely.</p><p>I wanted one repository that could:</p><ul><li>manage multiple clouds</li><li>onboard new accounts predictably</li><li>isolate account-level changes</li><li>centralize shared logic</li><li>and make execution context obvious</li></ul><p>But before reaching that point, I struggled with:</p><ul><li>inconsistent folder structures</li><li>unclear variable ownership</li><li>drift between accounts</li><li>tooling version mismatches</li><li>and growing operational risk</li></ul><p>The friction wasn’t in the code itself.<br> It was in how the system was organized.</p><p>This article walks through the blueprint I ultimately standardized:</p><p><strong>One repo. Multiple clouds. Hundreds of accounts.</strong></p><p>A Terragrunt-based operating model designed for clarity, repeatability, and scale.</p><h3>Problem Statement</h3><p>These issues didn’t appear on day one.</p><p>Early on, everything felt manageable. A small number of accounts, a limited set of modules, and a single cloud environment made Terraform easy to operate. Plans were predictable. Context lived in memory. The system felt simple because it was small.</p><p>As the platform grew, the friction grew quietly with it.</p><p>New environments were added.<br>More accounts were onboarded.<br>Another cloud entered the picture.<br>More engineers began making changes.</p><p>Nothing failed dramatically. Instead, small inconsistencies started accumulating:</p><ul><li>Folder patterns differed slightly between accounts</li><li>Variable ownership wasn’t always obvious</li><li>Small configuration differences created plan drift</li><li>Engineers ran commands from the wrong context</li><li>Local Terraform/Terragrunt versions varied</li><li>Upgrades required touching many “almost identical” directories</li></ul><p>Individually, these issues were minor. Together, they created operational risk.</p><p>The biggest problem wasn’t syntax or module design.<br>It was confidence.</p><p>Even when the code looked correct, running it felt risky.<br>Too much context had to be remembered manually:</p><ul><li>Which account am I targeting?</li><li>Which environment am I in?</li><li>Which variables apply here?</li><li>What will this command actually touch?</li></ul><p>At scale, relying on memory is fragile.</p><p>That realization changed how I thought about infrastructure.</p><p>I didn’t need better modules.<br>I needed a structure that made the correct path obvious, reduced manual decisions, and scaled across accounts and clouds without constant reinvention.</p><p>That requirement pushed me toward a single-repo, Terragrunt-first model designed for deterministic structure and predictable execution.</p><h3>Re-thinking the Operating Model</h3><p>I tried the usual approaches first.</p><p><strong>Terraform workspaces</strong> helped with state isolation but made context fragile.<br>At scale, asking <em>“which workspace am I in?”</em> is a risk.</p><p>I evaluated other frameworks and scripting layers.<br>They improved structure slightly, but introduced new problems:</p><ul><li>hidden execution logic</li><li>inconsistent patterns between accounts</li><li>reliance on team memory</li><li>drift over time</li></ul><p>Nothing failed dramatically.<br>But nothing felt deterministic either.</p><p>The issue wasn’t Terraform.<br>It was how we operated it.</p><p>As accounts and clouds grew, the same friction kept returning:</p><ul><li>too much context to remember</li><li>too many near-identical stacks</li><li>too many manual decisions before each run</li></ul><p>That’s when the shift happened.</p><p>I stopped asking:</p><blockquote>How do we write Terraform faster?</blockquote><p>I started asking:</p><blockquote>How do we operate infrastructure safely at scale?</blockquote><p>That led to one goal:</p><ul><li>one repo</li><li>one structure</li><li>clear variable hierarchy</li><li>path-based execution</li><li>zero hidden context</li></ul><p>From there, the Terragrunt blueprint took shape.</p><h3>The Blueprint I Landed On</h3><p>I standardized the repository around a Terragrunt-first model with clear separation of responsibility.</p><p>The structure follows one rule:</p><p><strong>Same mental model across clouds.<br>Only implementation details differ.</strong></p><p>At a high level, the repository is organized into five layers:</p><ol><li><strong>Cloud Roots</strong><br> root_aws.hcl, root_azure.hcl<br> Define backend configuration, provider behavior, and global Terragrunt settings.</li><li><strong>Base Layer</strong><br> _base_aws/, _base_azure/<br> Reusable stack wiring (network, compute, platform).</li><li><strong>Template Layer</strong><br> _template_aws/, _template_azure/<br> Account scaffolding for predictable onboarding.</li><li><strong>Environment Layer</strong><br> production/, staging/<br> Environment-specific overrides and separation.</li><li><strong>Account Layer</strong><br> aws_account1/, azure_account1/<br> Isolated account-level stacks (network, eks/aks, etc.).</li></ol><p>The key idea:</p><p><strong>The path defines the execution context.</strong></p><p>If I am inside:</p><pre>production/aws_account1/network</pre><p>I know exactly what I am operating on — <strong>no workspace switching, no hidden flags, no guesswork.</strong></p><p>This structure removed ambiguity and made scaling mechanical instead of manual.</p><h3>The Exact Structure I Standardized</h3><p>Once the model was clear, I locked the structure and kept it consistent across clouds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5UN548vUMD82G_UGLiOOw.png" /></figure><h3>Why this worked</h3><ul><li>Cloud behavior isolated at root</li><li>Reusable stack wiring centralized</li><li>Account onboarding templated</li><li>Environment overrides explicit</li><li>Path = execution scope</li></ul><p>After this, structure stopped being a discussion in PRs.<br>The repository itself enforced consistency.</p><h3>Variable Layering</h3><p>To remove drift, I standardized a strict three-layer model.</p><p><strong>1. Common (cloud-wide defaults)</strong><br>common_aws.tfvars<br>common_azure.tfvars<br>Baseline settings shared across all environments and accounts.</p><p><strong>2. Environment (prod vs staging)</strong><br>env_aws.tfvars<br>env_azure.tfvars<br>Only environment-level differences: sizing, guardrails, tags.</p><p><strong>3. Account (identity + local values)</strong><br>account.tfvars<br>Account-specific details: IDs, CIDR ranges, names.</p><p>Override flow is predictable:</p><pre>Common → Environment → Account</pre><p>This made ownership obvious:</p><ul><li>defaults stay global</li><li>behavior changes per environment</li><li>identity stays local</li></ul><p>When something needs to change, I know exactly where it belongs.</p><h3>Execution Model</h3><p>Execution context comes from the path.</p><p>Running from:</p><pre>production/aws_account1/network</pre><p>targets only that account’s network in production.</p><p>No workspaces. No flags. No hidden context.</p><p>Dependencies are encoded in Terragrunt:</p><pre>network → platform (eks/aks)</pre><p>So order is handled by the system, not memory.</p><p>Typical flow per account:</p><ul><li>validate</li><li>init</li><li>plan</li><li>apply</li></ul><p>Blast radius stays scoped to the folder you run from.<br>Reviews are easier because changes are account-targeted.</p><h3>Onboarding a New Account</h3><p>Adding a new account follows the same flow every time.</p><ol><li>Create the account folder under the target environment<br> production/aws_account2 or staging/azure_account3</li><li>Copy the appropriate template<br> _template_aws/ or _template_azure/</li><li>Update only account-specific values from account.tfvars.tpl and account.hcl.tpl</li></ol><p>4. Leave common and environment layers untouched.</p><p>5. Run validate → init → plan.</p><p>That’s it.</p><p>No hunting variables.<br>No editing scattered files.<br>No hidden scripts.</p><p>At scale, consistency matters more than speed.<br>Account 50 should feel the same as account 2.</p><h3>What This Enables at Scale</h3><p>At 100+ accounts, the benefit isn’t cleaner code.<br> It’s operational repeatability.</p><p>This model enables:</p><p><strong>Scoped changes</strong></p><blockquote>Target one environment, one account, one stack — without affecting the rest.</blockquote><p><strong>Predictable upgrades</strong></p><blockquote>Defaults live in common.<br>Environment behavior lives in env.<br>Account identity stays local.</blockquote><p><strong>Multi-cloud symmetry</strong></p><blockquote>Different cloud implementations.<br>Same operating model.</blockquote><p><strong>Lower cognitive load</strong></p><blockquote>Engineers don’t memorize structure.<br>The structure explains itself.</blockquote><p>When scale increases, complexity is inevitable.<br>Ambiguity is optional.</p><p>This blueprint removes ambiguity.</p><h3>Tradeoffs</h3><p>This model scales well, but it isn’t free.</p><ul><li>More folders and files up front</li><li>Requires learning Terragrunt patterns</li><li>Cloud roots must stay aligned</li><li>Discipline is required to prevent drift</li><li>External module sources add dependency on network and repos</li></ul><p>The structure adds overhead early.<br>It pays off as account count grows.</p><p>Consistency becomes the real productivity gain.</p><h3>Conclusion</h3><p>The shift wasn’t about writing better Terraform.</p><p>It was about designing a better operating model.</p><p>By standardizing:</p><ul><li>cloud-specific roots</li><li>base and template layers</li><li>a strict variable hierarchy</li><li>path-based execution</li></ul><p>the repository became predictable.</p><p>At small scale, memory works.<br>At large scale, structure must replace memory.</p><p>This blueprint made infrastructure:</p><ul><li>easier to reason about</li><li>safer to operate</li><li>simpler to extend</li><li>consistent across clouds</li><li>At 100+ accounts, consistency is the real multiplier.</li></ul><p>This structure is designed to work well with automation on top.</p><p>You can layer any CI/CD system to:</p><ul><li>run terragrunt plan automatically on PR</li><li>scope execution by path</li><li>require manual approval before apply</li><li>promote changes from staging → production</li><li>run per-account or per-environment pipelines</li></ul><p>Because execution context is path-based, pipelines don’t need custom logic to understand scope.<br>They simply run from the folder being changed.</p><p>The repository defines <em>what</em> is affected.<br> The pipeline controls <em>when</em> it is applied.</p><p>This keeps automation simple and approvals explicit while preserving safety at scale.</p><p>Code for this setup: <a href="https://github.com/soni-ayush/terragrunt/tree/main">soni-ayush/terragrunt (main)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec56f9111106" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Divide, Disrupt, Deploy: Smarter Workload Management with Karpenter: Part II]]></title>
            <link>https://medium.com/@ayushsoni47.as/divide-disrupt-deploy-smarter-workload-management-with-karpenter-part-ii-4ea6884131e5?source=rss-5d0e9ebaa025------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ea6884131e5</guid>
            <category><![CDATA[smart-scheduling]]></category>
            <category><![CDATA[node-scaling]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[workload-distribution]]></category>
            <category><![CDATA[karpenter]]></category>
            <dc:creator><![CDATA[ayushsoni_7]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 15:23:14 GMT</pubDate>
            <atom:updated>2025-10-08T11:32:38.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>Workload-Aware Autoscaling with Karpenter: Balancing Cost and Reliability</h3><p>In <a href="https://medium.com/@ayushsoni47.as/divide-disrupt-deploy-smarter-workload-management-with-karpenter-part-i-05254d45e2d5"><strong>Part 1</strong></a>, we explored how Karpenter moves beyond traditional node-based scaling — provisioning the <em>right node for the right workload</em> with speed, cost efficiency, and policy control.</p><p>Now, in <strong>Part 2</strong>, we’ll turn that theory into practice.<br>We’ll learn how to classify workloads, map them to the right scaling strategy, and use Karpenter’s features — like capacity types, consolidation, and disruption controls — to balance <strong>cost, reliability, and performance</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwwO_MBk0OKOAXkm0DFnNw.png" /></figure><p>This part is all about turning Karpenter’s intelligence into <strong>real-world autoscaling strategy</strong> — balancing performance, reliability, and cost in one cohesive framework.</p><h3>⚙️ Workload Classification — The Foundation of Reliable Autoscaling</h3><p>To run Karpenter effectively in production, you must first <strong>understand your workloads</strong>. Not all pods are equal — some can be safely interrupted, while others demand absolute stability.<br>Classifying workloads helps you decide where to prioritize <strong>reliability, cost, and flexibility</strong>, directly guiding your NodePool, capacity, and disruption settings.</p><p>Think of it as understanding the “<strong>personality</strong>” of your applications: which ones are fragile crown jewels, and which are disposable workhorses. Once you know that, Karpenter configurations become intuitive.</p><p>Let’s look at the seven key workload dimensions every cluster should consider:</p><h4>1️⃣ Stateful vs Stateless Workloads</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*vRHc5N0vrFKuAowU9sw02Q.png" /></figure><h4>2️⃣ Single Replica vs Multi-Replica Services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*D-DHsC64toYs8UYWyhRGeg.png" /></figure><h4>3️⃣ Critical vs Non-Critical Applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*cm8rg3C7vlYaSIhKZ6QbHQ.png" /></figure><h4>4️⃣ Long-Running vs Short-Lived Jobs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*HXyJOfdXVjezn11522z4Aw.png" /></figure><h4>5️⃣ Resource-Intensive vs Lightweight Workloads</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*yxDymD414ESBPrFQKUth-w.png" /></figure><h4>6️⃣ Real-Time vs Batch Processing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*7bTQqthQoTgSl1nCdQ-n2A.png" /></figure><h4>7️⃣ Retry-Sensitive vs Retry-Tolerant Tasks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*UDn35qcFFVCeXVn-h96IPA.png" /></figure><h3>⚙️ Karpenter’s Toolkit — The Tools for Workload-Aware Autoscaling</h3><p><em>Now that you know your workload categories, let’s explore the specific Karpenter features that will help you implement the right strategy for each type.</em></p><h4>1️⃣ Capacity Type — Choosing Your Compute Strategy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*_JCdCYw8TTl-iaw4OPVpuA.png" /></figure><h4>2️⃣ Consolidation Policy — When Can Karpenter Optimize?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*H6LU_fvE3T5l9mEYBUrGsw.png" /></figure><h4>3️⃣ Disruption Controls — Your Multi-Layer Defense System</h4><h4>Pod-Level Shield: The Do-Not-Disrupt Annotation</h4><p>The ultimate protection — tells Karpenter “never voluntarily touch this specific pod.” This is your nuclear option for absolutely critical workloads.</p><h4>Service-Level Shield: Pod Disruption Budgets (PDBs)</h4><p>Kubernetes-native protection that defines availability requirements for multi-replica services. You set rules like “always keep at least 80% of my replicas running” — this gives Karpenter a “disruption budget” to work within.</p><h4>Cluster-Level Controls: Karpenter’s Native Disruption Management</h4><p><strong>Disruption Budgets</strong>: Control the blast radius of changes across your entire cluster</p><ul><li>Limit how many nodes can be disrupted simultaneously</li><li>Set different limits for different types of disruptions (routine vs emergency)</li><li>Prevent cluster-wide instability from too many concurrent changes</li></ul><p><strong>Disruption Windows</strong>: Time-based control over when optimizations can happen</p><ul><li>Schedule aggressive cost optimization during off-peak hours only</li><li>Allow routine maintenance during business hours but block major changes</li><li>Coordinate with your deployment schedules and traffic patterns</li></ul><h4>Choosing Your Protection Strategy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*ub9fworMdtl2YIGkKr7LzQ.png" /></figure><h4>4️⃣ Instance Selection &amp; Smart Placement</h4><ul><li><strong>Instance Families</strong>: Guide Karpenter toward compute-optimized or memory-optimized hardware based on your workload characteristics</li><li><strong>Resource Right-Sizing</strong>: Your pod’s resource requests directly influence which instance types Karpenter selects</li><li><strong>Geographic Control</strong>: Specify availability zones for latency requirements or compliance needs</li><li><strong>Architecture Choices</strong>: Leverage ARM-based instances (Graviton) for additional cost savings on compatible workloads</li></ul><h3>Section 4: Real-World Workload Design — When Categories Overlap</h3><p><em>Most production workloads don’t fit neatly into a single category. Here are practical examples of how to design solutions when your application spans multiple workload types, balancing reliability with maximum cost savings.</em></p><h4>1️⃣ Machine Learning Training Job</h4><p><strong>The Setup:</strong> 8-hour deep learning model training on GPU instances.</p><p><strong>Workload Categories:</strong> <strong>Long-Running</strong> + <strong>Resource-Intensive</strong> + <strong>Retry-Sensitive</strong> + <strong>Batch Processing</strong></p><p><strong>The Challenge:</strong> Need cheap GPU compute but can’t afford expensive restarts.</p><p><strong>The Solution:</strong></p><ul><li><strong>Capacity:</strong> 100% Spot instances (70–80% cost savings on expensive GPUs)</li><li><strong>Consolidation:</strong> WhenEmpty - protects running jobs without extra annotations</li><li><strong>Protection:</strong> 30-minute checkpointing handles Spot interruptions</li><li><strong>Instance Selection:</strong> GPU Spot instances with &lt;5% interruption history</li></ul><p><strong>Result:</strong> 75% cost savings with 90% job completion rate.</p><h4>2️⃣ Customer-Facing API</h4><p><strong>The Setup:</strong> Auto-scaling product API (3–50 replicas) serving live customer traffic.</p><p><strong>Workload Categories:</strong> <strong>Critical Application</strong> + <strong>Multi-Replica</strong> + <strong>Real-Time</strong> + <strong>Stateless</strong></p><p><strong>The Challenge:</strong> Critical nature needs stability, but replicas allow risk-taking.</p><p><strong>The Solution:</strong></p><ul><li><strong>Capacity:</strong> 60% On-Demand baseline + 40% Spot for scale-out</li><li><strong>Consolidation:</strong> WhenUnderutilized with conservative limits</li><li><strong>Protection:</strong> PDB minAvailable: 85% + no disruptions 9 AM-6 PM</li><li><strong>Instance Selection:</strong> General-purpose instances for predictable performance</li></ul><p><strong>Result:</strong> 35% cost savings while maintaining 99.9% SLA.</p><h4>3️⃣ ETL Data Pipeline</h4><p><strong>The Setup:</strong> Nightly data processing (2–6 hours) with memory-intensive operations.</p><p><strong>Workload Categories:</strong> <strong>Long-Running</strong> + <strong>Batch Processing</strong> + <strong>Resource-Intensive</strong> + <strong>Retry-Tolerant</strong></p><p><strong>The Challenge:</strong> Long runtime suggests protection, but batch nature allows optimization.</p><p><strong>The Solution:</strong></p><ul><li><strong>Capacity:</strong> 100% Spot during off-peak hours (10 PM — 6 AM)</li><li><strong>Consolidation:</strong> WhenEmpty - only consolidate after pipeline completes</li><li><strong>Protection:</strong> Hourly checkpointing + auto-retry on On-Demand if Spot fails</li><li><strong>Instance Selection:</strong> Memory-optimized (R-series) for data processing</li></ul><p><strong>Result:</strong> 80% cost savings with 90% first-attempt success rate.</p><h4>4️⃣ Production Database Cluster</h4><p><strong>The Setup:</strong> PostgreSQL with 1 primary + 2 read replicas serving critical application data.</p><p><strong>Workload Categories:</strong> <strong>Critical Stateful</strong> + <strong>Multi-Replica</strong> + <strong>Critical Application</strong> + <strong>Singleton Primary</strong></p><p><strong>The Challenge:</strong> Primary needs maximum protection, replicas could use cheaper compute.</p><p><strong>The Solution:</strong></p><ul><li><strong>Primary:</strong> On-Demand + do-not-disrupt + WhenEmpty</li><li><strong>Read Replicas:</strong> 70% Spot + 30% On-Demand</li><li><strong>Protection:</strong> Separate NodePools with different policies</li><li><strong>Instance Selection:</strong> Storage-optimized instances for database workloads</li></ul><p><strong>Result:</strong> 25% overall cost savings with 99.99% write availability.</p><h4>5️⃣ Microservice with Seasonal Traffic</h4><p><strong>The Setup:</strong> E-commerce recommendation service with 10x holiday traffic spikes.</p><p><strong>Workload Categories:</strong> <strong>Critical Application</strong> + <strong>Multi-Replica</strong> + <strong>Resource-Intensive</strong> + <strong>Real-Time</strong></p><p><strong>The Challenge:</strong> Critical during peak season, over-provisioned during off-season.</p><p><strong>The Solution:</strong></p><ul><li><strong>Peak Season (Nov-Dec):</strong> On-Demand only for guaranteed capacity</li><li><strong>Off-Season:</strong> Mixed 50% Spot + 50% On-Demand</li><li><strong>Protection:</strong> Dynamic PDB — conservative during peaks, aggressive during lulls</li><li><strong>Instance Selection:</strong> Memory-optimized for ML recommendation models</li></ul><p><strong>Result:</strong> 50% annual cost savings while maintaining peak performance when needed.</p><h4>6️⃣ Development Environment</h4><p><strong>The Setup:</strong> Complete dev stack (databases, APIs, frontend) used by engineering teams.</p><p><strong>Workload Categories:</strong> <strong>Non-Critical</strong> + <strong>Mixed Workload Types</strong> + <strong>Business Hours Only</strong> + <strong>Multi-Replica</strong></p><p><strong>The Challenge:</strong> Mix of stateful and stateless components, but all non-production.</p><p><strong>The Solution:</strong></p><ul><li><strong>Capacity:</strong> 100% Spot instances — interruptions acceptable</li><li><strong>Schedule:</strong> Auto-shutdown outside business hours (6 PM — 9 AM, weekends)</li><li><strong>Consolidation:</strong> WhenUnderutilized everywhere - no protection needed</li><li><strong>Protection:</strong> None — maximize cost savings over uptime</li></ul><p><strong>Result:</strong> 85% cost savings with planned downtime during off-hours.</p><h4>7️⃣ Multi-Tier Analytics Platform</h4><p><strong>The Setup:</strong> Real-time analytics with query engines, cache layer, ingestion service, and web frontend.</p><p><strong>Workload Categories:</strong> <strong>Mixed Resource Requirements</strong> + <strong>Real-Time</strong> + <strong>Horizontally-Scalable</strong> + <strong>Critical</strong></p><p><strong>The Challenge:</strong> One platform, four different resource profiles needing different optimizations.</p><p><strong>The Solution by Component:</strong></p><ul><li><strong>Query Engine:</strong> Compute-optimized (C-series) + Mixed Spot/On-Demand</li><li><strong>Cache Layer (Redis):</strong> Memory-optimized (R-series) + 70% Spot</li><li><strong>Data Ingestion:</strong> General-purpose (M-series) + Standard mixed approach</li><li><strong>Web Frontend:</strong> Burstable (T-series) + 100% Spot</li></ul><p><strong>Instance Type Savings:</strong></p><ul><li>C-series: 25% cheaper than M-series for CPU-heavy tasks</li><li>R-series: 35% cheaper than M-series for memory-heavy workloads</li><li>T-series: 60% cheaper than M-series for low-utilization services</li></ul><p><strong>Result:</strong> 45% total platform cost reduction by matching workloads to optimal instance types.</p><h3>🏗️ Best Practices &amp; Strategic Implementation</h3><p><em>Mastering Karpenter isn’t about learning every configuration option — it’s about making intelligent infrastructure decisions that align with your business priorities.</em></p><h4>1️⃣ Design with Intent, Not Defaults</h4><ul><li><strong>Critical workloads</strong>: On-Demand + Do-Not-Disrupt</li><li><strong>Scalable APIs</strong>: Mixed Spot/On-Demand + conservative PDBs</li><li><strong>Batch jobs</strong>: Spot + WhenEmpty</li><li><strong>Dev/Non-critical</strong>: Maximize cost savings with aggressive consolidation</li></ul><blockquote><em>Every decision should reflect your workload’s business impact, not just its technical needs.</em></blockquote><h4>2️⃣ Implement Strategic Boundaries</h4><ul><li><strong>Taints &amp; Labels</strong>: Prevent accidental placement of experimental workloads on production nodes</li><li><strong>NodePools</strong>: Separate cost-optimized environments from reliability-critical workloads</li><li><strong>Right-Sizing</strong>: Ensure resource-intensive jobs land on appropriately-sized instances</li></ul><blockquote><em>Boundaries prevent costly mistakes while allowing Karpenter to optimize safely.</em></blockquote><h4>3️⃣ Measure Business Impact, Not Just Metrics</h4><ul><li><strong>Startups</strong>: Track cost per feature delivered and runway extension</li><li><strong>Enterprises</strong>: Monitor SLA compliance, uptime, and operational efficiency</li><li><strong>All organizations</strong>: Correlate infrastructure changes with application performance and user experience</li></ul><blockquote><strong><em>This shifts focus from raw cluster metrics to real business outcomes.</em></strong></blockquote><h4>4️⃣ Layered Protection Strategy</h4><ul><li><strong>Pod-Level: </strong>Do-Not-Disrupt for critical singleton workloads</li><li><strong>Service-Level: </strong>Pod Disruption Budgets (PDBs) for multi-replica services</li><li><strong>Cluster-Level: </strong>Karpenter Disruption Budgets + Disruption Windows to control global impact</li></ul><blockquote><em>Multi-layered protection ensures aggressive cost optimization never breaks SLAs. Conclusion: From Reactive to Strategic</em></blockquote><h3>🎯 Conclusion — The Strategic Advantage</h3><p><strong>Karpenter isn’t just an autoscaler — it’s a strategic enabler that aligns infrastructure with business priorities.</strong></p><h4>The Shift</h4><ul><li><strong>From “How do I scale nodes?” → “How do I optimize for workloads and business value?”</strong></li></ul><h4>Context Matters</h4><p><strong>No one-size-fits-all:</strong></p><ul><li>Fintech → reliability first</li><li>Media pipelines → cost-first, tolerant of interruptions</li><li>Seasonal apps → dynamic peak/off-peak strategy</li></ul><h4>Competitive Advantage</h4><ul><li>Invest where it matters: prioritize high-value workloads</li><li>Adapt quickly: adjust scaling without over-engineering</li><li>Scale confidently: protect critical workloads while optimizing cost</li></ul><h4>Path Forward</h4><ul><li>Future autoscaling will be business-context-aware: not just CPU/memory metrics, but revenue impact, user experience, and strategic priorities.</li><li>Your next step: understand workloads deeply, design strategies around them, and let Karpenter execute intelligently.</li></ul><p><strong>Don’t just autoscale. Autoscale strategically.</strong></p><h4>🎁 Bonus: Smart Capacity Distribution</h4><p>To further optimize your workload distribution, consider implementing a custom scheduling strategy that allocates pods between On-Demand and Spot instances based on your desired percentages. This approach allows you to balance cost savings with availability, adapting to your specific requirements.</p><p>For detailed guidance on setting up such a strategy, refer to the AWS blog post: <a href="https://aws.amazon.com/blogs/containers/customizing-scheduling-on-amazon-eks/?utm_source=chatgpt.com">Customizing Scheduling on Amazon EKS</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ea6884131e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Divide, Disrupt, Deploy: Smarter Workload Management with Karpenter: Part I]]></title>
            <link>https://medium.com/@ayushsoni47.as/divide-disrupt-deploy-smarter-workload-management-with-karpenter-part-i-05254d45e2d5?source=rss-5d0e9ebaa025------2</link>
            <guid isPermaLink="false">https://medium.com/p/05254d45e2d5</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-finops]]></category>
            <category><![CDATA[workload-management]]></category>
            <category><![CDATA[scaling-with-karpenter]]></category>
            <category><![CDATA[karpenter]]></category>
            <dc:creator><![CDATA[ayushsoni_7]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 08:47:42 GMT</pubDate>
            <atom:updated>2025-10-08T11:46:57.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Karpenter is the Future of Kubernetes’ Node Autoscaling</h3><p>In Kubernetes, <strong>pods are virtual</strong>, but <strong>nodes are physical</strong>.<br>Pods represent your running applications — they request CPU, memory, or GPU resources. But pods can’t actually run on their own; they need <strong>nodes</strong>, which are the real machines (EC2 instances in AWS) that provide those resources.</p><p>Kubernetes workloads are <strong>dynamic</strong>. Pods are created, deleted, or rescheduled constantly, which means the <strong>resource needs of your cluster are never static</strong>. Without proper scaling, you risk:</p><ul><li><strong>Unschedulable pods during peak demand</strong>, causing service delays</li><li><strong>Idle nodes during low demand</strong>, wasting money</li></ul><p>This is where <strong>node autoscaling</strong> comes in — it automatically adjusts the number of nodes to match your workload, <strong>balancing cost and availability</strong>.</p><p>But here’s the problem: traditional autoscaling treats all workloads the same. Your critical database gets the same scaling logic as your development environment. Your mission-critical API receives the same cost optimization as your disposable batch jobs.</p><p><strong>This one-size-fits-all approach is broken.</strong> And it’s exactly why the future of Kubernetes’ Node autoscaling is <strong>workload-aware</strong>.</p><h3>The Traditional Approach: Cluster Autoscaler’s Limitations</h3><p>For years, the Cluster Autoscaler (CA) has been the standard tool for Kubernetes node scaling. It works by:</p><ol><li>Monitoring unscheduled pods and identifying resource shortages</li><li>Scaling node groups up or down via cloud provider APIs (for example, AWS Auto Scaling Groups)</li></ol><p>While functional, CA has architectural limitations that become expensive at scale:</p><ol><li><strong>Reactive Scaling → Extra Latency</strong><br>CA only reacts after pods are Pending, resulting in multi-step delays: CA → ASG → instance boot → pod scheduling. Scale-ups can take several minutes.</li><li><strong>Cost-Blind Decisions</strong><br>CA only ensures resource requests are met. It doesn’t optimize for price, so workloads may land on costlier nodes.</li><li><strong>Conservative Scale-Down</strong><br>Nodes aren’t removed until underutilized, and pods with local storage or strict PDBs can block deletion. Idle resources linger.</li><li><strong>Limited Spot &amp; Instance Optimization</strong><br>CA can use Spot nodes, but mixing instance types dynamically or falling back smoothly requires manual setup.</li></ol><h3>Enter Karpenter: A Workload-Driven Provisioning Model</h3><p>Karpenter flips the model from “scale node groups” to “provision the right node for the workload.”</p><p>How Karpenter fixes Cluster Autoscaler’s four limitations</p><ul><li><em>Reactive with extra latency → Direct provisioning<br></em>Karpenter skips the node-group hop and talks to the cloud API directly, so scale-ups typically happen in seconds to about a minute.</li><li><em>Cost-blind placement → Cost-aware selection<br></em>For each decision, it evaluates multiple instance families, sizes, AZs, architectures, and Spot vs On-Demand, then picks the lowest-cost option that meets your policies and the pod’s constraints.</li><li><em>Conservative scale-down → Policy-driven consolidation</em><br>It continuously finds denser, cheaper placements and consolidates nodes under two clear modes: WhenEmpty (safe retire) or WhenUnderutilized (proactive move), governed by consolidateAfter timers and disruption controls.</li><li><em>Limited Spot/cross-instance optimization → Diversified capacity with fallback<br></em>It mixes families, sizes, zones, and capacity types by default. If Spot isn’t available or is reclaimed, it can fall back to On-Demand within your rules.</li></ul><p><strong>Key capabilities (at a glance)</strong></p><ul><li>Dynamic, pod-driven provisioning<br>Watches unschedulable pods and launches exactly the capacity they require — no pre-built ASGs for every variation.</li><li>Cost- and instance-aware decisions<br>Chooses from many families/sizes/AZs/architectures and capacity types to minimize price while honoring constraints.</li><li>Efficient deprovisioning and consolidation<br>Retires empty or underutilized nodes based on policy; supports consolidateAfter, drift/expiration to keep fleets clean.</li><li>Rich scheduling constraint support<br>Respects affinity/anti-affinity, taints/tolerations, topology spread, and volume/AZ placement so workloads land where they can run.</li><li>Simplified, policy-based operations<br>Replace many node groups with a few NodePools/NodeClasses and let Karpenter handle provisioning, draining, and cleanup.</li></ul><p>What you get: faster scale-ups, lower steady-state cost through smart placement and consolidation, and simpler operations aligned to how your workloads actually behave.</p><h3>Karpenter Architecture and the Pod-to-Node Lifecycle (Made Simple)</h3><h3>Key Terminologies</h3><ul><li><strong>NodePool</strong> — Logical group of nodes with shared rules (instance families, zones, capacity types, labels/taints, disruption/consolidation policies).</li><li><strong>NodeClass</strong> — Blueprint for creating nodes (instance types, AMI, networking, architecture).</li><li><strong>NodeClaim</strong> — Karpenter’s representation of a provisioned node. Tracks pods, labels, and capacity.</li><li><strong>Disruption</strong> — Safe removal/replacement of nodes; respects PDBs, Do-Not-Disrupt annotations, and disruption windows.</li><li><strong>Consolidation</strong> — Packs workloads efficiently: removes idle nodes (<strong>WhenEmpty</strong>) or underutilized nodes (<strong>WhenUnderutilized</strong>) based on timers.</li><li><strong>Capacity Types</strong> — On-Demand, Spot, or a mix; Karpenter chooses the lowest-cost option while honoring reliability policies.</li><li><strong>Scheduling Constraints</strong> — Includes resource requests, taints/tolerations, affinity/anti-affinity, topology spread, and volume/AZ placement.</li></ul><h3>Architecture at a Glance</h3><ul><li><strong>Karpenter Controller</strong> — Runs inside your cluster, watching for unschedulable pods and deciding when to add or remove nodes.</li><li><strong>NodePools / NodeClasses</strong> — Define your rules: which instance families, zones, capacity types, labels, taints, and disruption or consolidation policies are allowed.</li><li><strong>NodeClaims</strong> — Karpenter’s representation of each provisioned node. Tracks pods, labels, and capacity for management and optimization.</li><li><strong>Cloud Provider Integration</strong> — Connects directly to AWS APIs to launch or terminate instances — no node groups required.</li><li><strong>Kubernetes Scheduler</strong> — Still handles final pod placement once a node exists.</li></ul><h3>What Happens When a Pod Needs a Node</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbY4HqC-6CQ1qEl5w-tCyg.png" /></figure><ol><li><strong>Pod Becomes Pending</strong><br>Kubernetes can’t place a pod because there’s no compatible capacity available.</li><li><strong>Karpenter Reads the Pod’s Needs</strong><br>It inspects the pod’s resource requests (CPU, memory, GPU), labels, affinity, tolerations, and topology (zones, volumes).<br>Then it finds a <strong>NodePool</strong> that allows those constraints.</li><li><strong>Karpenter Builds and Evaluates Options</strong><br>From your NodePool and NodeClass policies, Karpenter generates possible offerings — combinations of instance type × zone × capacity type (Spot or On-Demand).<br>It groups compatible pending pods together and picks the <strong>cheapest healthy option</strong> that fits your rules.<br>If capacity is missing in one AZ, it retries another type or zone automatically.</li><li><strong>Karpenter Launches the Node</strong><br>It calls the cloud provider API directly to spin up the instance with the correct AMI, networking, and bootstrap configuration.<br>No waiting for node groups or autoscaling intermediaries.</li><li><strong>Node Joins; Pods Get Scheduled</strong><br>The node boots, registers with the cluster, and inherits labels and taints from its NodePool.<br>Once it’s Ready, the Kubernetes scheduler places the pending pods, and they start running.</li></ol><h3>Continuous Optimization (Consolidation)</h3><p>After workloads stabilize, Karpenter looks for opportunities to save cost and rebalance:</p><ul><li><strong>WhenEmpty:</strong> Removes nodes that have become idle.</li><li><strong>WhenUnderutilized:</strong> Packs pods more efficiently onto fewer or cheaper nodes.</li><li><strong>consolidateAfter:</strong> Controls how long a node stays idle before Karpenter acts.</li></ul><h3>Safety Before Any Disruption</h3><p>Before removing or replacing nodes, Karpenter checks your guardrails:</p><ul><li><strong>Pod Disruption Budgets (PDBs):</strong> Keeps required replicas running.</li><li><strong>Do-Not-Disrupt Annotations:</strong> Skips protected pods.</li><li><strong>Karpenter Disruption Budgets:</strong> Limits how many nodes can change at once.</li><li><strong>Disruption Windows:</strong> Allows changes only during approved time windows.</li></ul><h3>The Paradigm Shift: From Node Management to Workload Optimization</h3><p>For years, Kubernetes users focused on nodes: how many to run, which types to pick, and when to scale. This <strong>node-first mindset</strong> worked when clusters were small and workloads predictable. But today, workloads are <strong>dynamic, heterogeneous, and business-critical</strong>. Treating every pod the same leads to inefficiencies:</p><ul><li>Critical services may suffer delays if the wrong instance type is chosen.</li><li>Cost-sensitive batch jobs may waste money if they land on high-priced nodes.</li><li>Idle resources linger while urgent pods wait for capacity.</li></ul><p><strong>Workload-aware autoscaling flips the perspective:</strong> instead of managing nodes and hoping pods fit, we <strong>focus on the workload first</strong>. Think of it as moving from “how many nodes do I need?” to “what does this pod need, and what’s the most efficient way to provide it?”</p><p>This paradigm shift enables:</p><ul><li><strong>Intent-driven provisioning:</strong> Nodes exist to satisfy workloads, not the other way around.</li><li><strong>Cost-aware placement:</strong> Critical workloads get reliable instances, opportunistic jobs use Spot or cheaper alternatives.</li><li><strong>Reduced operational complexity:</strong> Less manual node group tinkering, more automated optimization.</li></ul><h3>What’s Next: The Implementation Challenge</h3><p>Understanding the theory is one thing, <strong>implementing workload-aware autoscaling is another</strong>. Real-world clusters host thousands of pods with overlapping constraints, dynamic traffic patterns, and complex cost/reliability trade-offs.</p><p>Key implementation challenges include:</p><ul><li><strong>Workload classification at scale:</strong> How do you reliably tag or label workloads according to criticality, statefulness, and resource sensitivity?</li><li><strong>Defining scaling policies per workload type:</strong> Which workloads should prioritize speed over cost? Which can tolerate Spot interruptions?</li><li><strong>Cost vs. reliability balancing:</strong> How to ensure that aggressive consolidation or Spot usage doesn’t impact SLA-bound services?</li><li><strong>Observability and feedback loops:</strong> Making sure autoscaler decisions can be audited, debugged, and refined in production.</li></ul><p>In <strong>Part 2</strong>, we’ll explore a practical <strong>framework for workload classification</strong>, along with strategies to balance cost and reliability using Karpenter. We’ll also dive into <strong>policy examples, node configuration patterns, and real-world scaling scenarios</strong>, showing how theory translates into action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05254d45e2d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚓︎ From Port Chaos to Port Harmony: Smart TCP Routing with APISIX and TLS SNI]]></title>
            <link>https://medium.com/@ayushsoni47.as/%EF%B8%8E-from-port-chaos-to-port-harmony-smart-tcp-routing-with-apisix-and-tls-sni-909fad88712e?source=rss-5d0e9ebaa025------2</link>
            <guid isPermaLink="false">https://medium.com/p/909fad88712e</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[multi-tenant]]></category>
            <category><![CDATA[apache-apisix]]></category>
            <category><![CDATA[secure-connection]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[ayushsoni_7]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 12:28:04 GMT</pubDate>
            <atom:updated>2025-07-04T07:29:14.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>📐 Introduction</h3><p>When exposing services like databases across multiple tenants, traditional load balancers often fall short. You might need per-tenant routing, IP-based access control, and fine-grained observability — all without managing dozens of ports.</p><p>This is where <strong>Apache APISIX</strong>, an open-source API Gateway, becomes a powerful alternative. It supports <strong>stream-based TCP routing</strong>, <strong>SNI hostname matching</strong>, and <strong>IP whitelisting</strong> via Kubernetes-native CRDs.</p><p>In this post, we’ll use <strong>Mongo</strong> as an example to build a <strong>secure, multi-tenant TCP gateway</strong> using:</p><ul><li>ApisixRoute for stream-based TCP routing</li><li>ApisixTls for SNI-based TLS termination</li><li>The ip-restriction plugin for access control</li></ul><h3>🧩 Problem Statement</h3><p>In a multi-tenant SaaS architecture, each tenant often requires an isolated database instance for security, compliance, and data integrity. For example, suppose you are managing multiple MongoDB instances inside a Kubernetes cluster, one per tenant. Each MongoDB service running inside kubernetes cluster listens on the default port 27017.</p><p>You need a way to expose these tenant-specific services <strong>securely</strong>, <strong>scalably</strong>, and <strong>efficiently</strong> to internal or external clients.</p><p>However, using a traditional TCP Load Balancer creates the following challenges:</p><h3>❌ Why a Single TCP Load Balancer Is Not Enough</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LLqYhtB52DgI6-oWmGFHw.png" /></figure><h3>1. Port Explosion</h3><p>A TCP load balancer can route based only on IP + Port. Since all MongoDB services use the same default port (27017), you’ll need to assign a <strong>unique port per tenant</strong> at the load balancer level:</p><p>This becomes:</p><ul><li>Hard to <strong>track and manage</strong> as the number of tenants grows</li><li>Easy to misconfigure — one wrong port, and you’re connecting to the wrong tenant’s DB</li><li>Not scalable — most load balancers have limits on port mappings or configuration complexity</li></ul><h3>2. Poor Observability</h3><p>Load balancers don’t support detailed metrics for tenant-level traffic. You can’t tell which tenant’s connection is spiking latency or volume without external tools.</p><h3>3. Limited Access Control</h3><p>You cannot enforce <strong>tenant-specific IP whitelists</strong> on a per-connection basis using a single load balancer.</p><h3>4. No Support for SNI-Based Routing</h3><p>TCP load balancers don’t inspect TLS handshakes. Therefore, they can’t make routing decisions based on <strong>SNI (Server Name Indication)</strong> — which means you can’t multiplex traffic on a <strong>single port</strong> for multiple tenants securely.</p><h3>5. High Cost for Same Port Use Case</h3><p>If you still want every tenant to use port 27017, you will need <strong>multiple TCP load balancers</strong>—one per tenant—which is <strong>not cost-effective or scalable</strong>.</p><h3>✅ The Modern Solution: APISIX as a Smart TCP Gateway</h3><p>Instead of maintaining a fragile port-to-service mapping, APISIX allows you to:</p><ul><li>Route based on <strong>SNI hostnames</strong> (e.g., tenant1.internal.tech)</li><li>Use a <strong>single port</strong> (27017) for all tenants</li><li>Terminate TLS and enforce <strong>IP-based access control</strong></li><li>Keep the routing configuration <strong>declarative and GitOps-friendly</strong></li></ul><p>This is ideal for platforms where MongoDB (or any TCP service) is offered per-tenant and securely accessed via internal tools or scripts.</p><h3>🧰 Load Balancer vs API Gateway</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBupeQy96gQX0RqIFq_5Rg.png" /></figure><h3>🌐 What is Apache APISIX?</h3><p><strong>Apache APISIX</strong> is a high-performance API Gateway that supports both <strong>L7 and L4 routing</strong>. With native Kubernetes support, you can manage traffic using declarative resources.</p><h4>ApisixRoute</h4><p>Defines how APISIX should route incoming traffic. It supports:</p><ul><li>HTTP routes (paths, headers)</li><li>Stream (TCP) routes based on SNI and port</li><li>Plugin configurations (like IP filtering)</li></ul><h4>ApisixTls</h4><p>Binds TLS certificates to hostnames (SNI) so that APISIX can terminate TLS connections and forward traffic based on hostname.</p><h3>🔐 What is TLS and TLS Termination?</h3><p><strong>TLS (Transport Layer Security)</strong> is a cryptographic protocol that secures communication between clients and servers. It operates on <strong>Layer 4 (TCP)</strong> and <strong>Layer 7 (HTTP)</strong> depending on the application.</p><ul><li><strong>TLS Termination</strong> means decrypting the TLS connection at the edge (e.g., gateway or proxy) before forwarding the plain traffic to the backend.</li><li>This enables <strong>APISIX</strong> to inspect SNI (Server Name Indication) from the TLS handshake and apply routing logic.</li></ul><h3>Why not terminate TLS at the Load Balancer?</h3><ul><li>Most LBs do not inspect SNI for TCP-level traffic.</li><li>You lose flexibility and tenant isolation.</li><li>TLS termination at APISIX gives full control over routing and plugins.</li></ul><h3>🚀 Use Case: Multi-Tenant Mongo (as Example TCP Service)</h3><p>We run isolated MongoDB instances for each tenant inside Kubernetes. Each service uses the same port (27017).</p><p>We want to:</p><ul><li>Use a <strong>single shared port</strong></li><li>Route traffic based on <strong>SNI hostnames</strong></li><li>Allow access only from <strong>specific internal IPs</strong></li><li>Configure everything declaratively using Helm</li></ul><h3>🔧 Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wfqStRbYcP5dVeX-LHXFA.png" /></figure><h4>🧾 ApisixRoute Manifest Explained</h4><pre>apiVersion: apisix.apache.org/v2        # Use APISIX CRD v2<br>kind: ApisixRoute                       # CRD for defining route<br>metadata:<br>  name: tenant1-database-route<br>  namespace: tenant1     # Route exists in tenant&#39;s namespace<br>spec:<br>  stream:<br>    - name: mongo-tcp-proxy            # Unique name for the stream route<br>      protocol: TCP                    # Protocol is TCP (not HTTP)<br>      match:<br>        host: tenant1.mongo.database.com  # Match incoming SNI<br>        ingressPort: 27017            # Match LB port traffic<br>      backend:<br>        serviceName: mongodb          # Internal service to forward traffic<br>        servicePort: 27017            # Port of internal MongoDB<br>      plugins:<br>        - name: ip-restriction        # Plugin for IP-based access control<br>          enable: true<br>          config:<br>            whitelist:<br>              - 10.228.0.0/16         # Only allow this CIDR range</pre><h4>🔐 ApisixTls Manifest Explained</h4><pre>apiVersion: apisix.apache.org/v2        # APISIX TLS CRD<br>kind: ApisixTls                         # Defines TLS termination config<br>metadata:<br>  name: database-tls<br>  namespace: tenant1                    # Namespace where APISIX runs<br>spec:<br>  hosts:<br>    - tenant1.mongo.database.com  # Hostname to bind cert to<br>  secret:<br>    name: tls-cert  # TLS cert secret name<br>    # namespace of secret can crate a single tls cert for *.mongo.database.com<br>    namespace: apisix </pre><p>This tells APISIX to:</p><ul><li>Watch for incoming traffic with SNI tenant1.mongo.database.com</li><li>Terminate TLS using the secret tls-cert</li><li>Forward decrypted traffic based on ApisixRoute</li></ul><h3>🔍 Testing the Setup</h3><p>From an internal whitelisted IP:</p><pre>mongosh &quot;mongodb://tenant1.mongo.database.com:27017/?tls=true&quot;</pre><p>Connection will succeed only if:</p><ul><li>TLS is terminated at APISIX with correct cert (from ApisixTls)</li><li>SNI matches configured route</li><li>Source IP is in whitelist</li></ul><h3>✅ Benefits</h3><p>✔️ One port, many tenants via SNI</p><p>✔️ IP-restricted access to sensitive services</p><p>✔️ GitOps-friendly with Helm + CRDs</p><p>✔️ TLS termination enables routing + observability</p><p>✔️ Extendable to any TCP service (PostgreSQL, Redis, etc.)</p><h3>🚀 Conclusion</h3><p>With APISIX, we’ve created a flexible, secure TCP gateway that scales with our multi-tenant platform. By combining TLS, SNI-based routing, and IP whitelisting, we can expose services like MongoDB in a way that’s both <strong>safe</strong> and <strong>operationally simple</strong>.</p><p>If you’re building a multi-tenant SaaS platform or want to modernize TCP routing in Kubernetes, this architecture is worth adopting.</p><h3>💬 Let’s Connect</h3><p>Feel free to reach out on <a href="https://www.linkedin.com/in/ayush-soni-811b91137/">LinkedIn</a> if you want to discuss this pattern, share feedback, or explore ideas around Kubernetes, DevOps, or platform engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909fad88712e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>