<?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 Nagulesh on Medium]]></title>
        <description><![CDATA[Stories by Nagulesh on Medium]]></description>
        <link>https://medium.com/@nagulesh03?source=rss-5c20ebe6a9c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dw3T7hurY6Ni17tS_okFfg.png</url>
            <title>Stories by Nagulesh on Medium</title>
            <link>https://medium.com/@nagulesh03?source=rss-5c20ebe6a9c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:12:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nagulesh03/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[Your EC2 Is 80% Idle and ECS Keeps Launching New Instances — Here’s How ENI Trunking Fixed It]]></title>
            <link>https://medium.com/@nagulesh03/your-ec2-is-80-idle-and-ecs-keeps-launching-new-instances-heres-how-eni-trunking-fixed-it-1a30c3044893?source=rss-5c20ebe6a9c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a30c3044893</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Nagulesh]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 04:01:01 GMT</pubDate>
            <atom:updated>2026-11-26T09:18:55.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L0aKDPXZu1plD1waIqicQ.jpeg" /></figure><p><em>A real client problem — 32 GB of memory, only 3 tasks running, and new instances spinning up for every deployment. Here’s what was wrong and exactly how ENI trunking fixed it.</em></p><h3>The Problem That Started Everything</h3><p>The setup looked completely normal on paper. An ECS cluster backed by EC2 instances, each with 32 GB of memory. Each task required only 2 GB of memory and no specific CPU reservation. Simple math — the instance should comfortably run 15 to 16 tasks.</p><p>But that’s not what was happening.</p><p>Three tasks placed. Then ECS started spinning up a brand new EC2 instance for the fourth task. Then the fifth. Then the sixth. Each task on its own instance, each with 30 GB of memory sitting completely unused. The cluster was burning money on idle compute while the existing instance had more than enough resources to host every single task.</p><p>I checked the ECS console. Memory? Available. CPU? Available. Health checks? Passing. The cluster looked healthy. Everything looked fine.</p><p>But ECS was still refusing to place more than 3 tasks on a single instance.</p><h3>The Real Culprit: ENIs, Not Memory</h3><p>This is the part most tutorials skip. When you use awsvpc network mode in ECS — which is the default and recommended mode for most production setups — every single ECS task gets its own dedicated <strong>Elastic Network Interface (ENI)</strong>. Not shared. One task, one ENI.</p><p>And EC2 instances have a hard limit on how many ENIs can be attached.</p><p>For a c5.large, the default ENI limit is 3. The primary network interface takes up slot 1. That leaves exactly 2 ENIs for tasks. So regardless of how much memory or CPU is available, ECS cannot place more than 2 tasks on a c5.large — the ENI slots are full.</p><p>My client was running r6g.xlarge instances — Graviton2, ARM-based, 4 vCPUs, 32 GB memory. The ENI limit for r6g.xlarge is 4 total. Subtract 1 for the primary interface, and you get 3 task slots. Not 15. Not 16. Three.</p><p>That was the entire problem. Not memory. Not CPU. ENIs.</p><blockquote><strong><em>The “Before” State:</em></strong><em> ECS console showing the cluster — EC2 instances listed with only 2–3 tasks each, while memory utilization shows 10–15% used and memory available shows 28–30 GB remaining. This is the gap that makes no sense until you understand ENI limits.</em></blockquote><p>EC2 Machines are limited to the number of ENI’s:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNKvIkPwY6-Iv8CP3UlldQ.png" /></figure><p>You can see that 2 EC2 machines are launched but there is no CPU or Memory utilization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRttZLSYv4TpEUfucLRvbA.png" /></figure><h3>What Is awsvpc Network Mode?</h3><p>Before diving into the fix, it helps to understand why awsvpc mode exists and why it creates this constraint.</p><p>In awsvpc mode, each ECS task gets:</p><ul><li>Its own private IP address</li><li>Its own ENI attached to the EC2 instance</li><li>Its own security group assignment</li><li>Full VPC networking — Flow Logs, Security Groups, VPC-level isolation</li></ul><p>This is powerful. Each task is network-isolated from every other task on the same instance. You can apply different security groups to different tasks on the same host. You get per-task VPC visibility. It is the foundation for AWS App Mesh, service mesh architectures, and zero-trust networking inside ECS.</p><p>The tradeoff is ENI consumption. Each task requires one ENI slot on the host instance.</p><p><strong>Default ENI limits per instance type (without ENI trunking):</strong></p><ul><li>t3.micro → 2 ENIs → 1 task slot after primary</li><li>t3.small → 3 ENIs → 2 task slots</li><li>c5.large → 3 ENIs → 2 task slots</li><li>c5.xlarge → 4 ENIs → 3 task slots</li><li>m5.large → 3 ENIs → 2 task slots</li><li>m5.2xlarge → 4 ENIs → 3 task slots</li><li>r6g.large → 3 ENIs → 2 task slots</li><li><strong>r6g.xlarge → 4 ENIs → 3 task slots ← my client&#39;s instance</strong></li><li>r6g.2xlarge → 4 ENIs → 3 task slots</li><li>r6g.4xlarge → 8 ENIs → 7 task slots</li></ul><p>For my client — running a memory-light workload where each task only needed 2 GB on a 32 GB r6g.xlarge — even the most memory-rich Graviton instance would hit its ENI ceiling long before it used more than a fraction of available memory.</p><blockquote><strong><em>Task Definition Network Mode:</em></strong><em> ECS task definition showing </em><em>networkMode: &quot;awsvpc&quot; in the JSON view. This is the setting that triggers per-task ENI allocation and connects directly to the ENI limit problem.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*tk-pdn3qY80A1yUKGVHzTQ.png" /></figure><h3>The Old Workaround: Bridge Mode</h3><p>Before ENI trunking existed, the common workaround was switching to bridge network mode.</p><p>In bridge mode, tasks share the host’s primary network interface via Docker’s internal bridge networking. No per-task ENI. No ENI limits. You can pack as many tasks onto an instance as memory and CPU allow.</p><p>The catch? You lose all the benefits of awsvpc:</p><ul><li>No per-task security groups</li><li>No per-task VPC Flow Logs</li><li>No per-task IP address</li><li>Port conflicts — two tasks cannot bind the same host port</li><li>Dynamic port mapping required for ALB integration</li><li>No isolation between tasks at the network layer</li></ul><p>For the client’s workload, switching to bridge mode would have worked in the short term. But they were already planning to integrate AWS App Mesh, which requires awsvpc. Going back to bridge mode would have been a dead end.</p><p>That is when ENI trunking became the right answer.</p><h3>The Fix: ENI Trunking (awsvpcTrunking)</h3><p>ENI trunking solves the ENI density problem without giving up awsvpc mode.</p><p>When you enable the awsvpcTrunking account setting, ECS creates a <strong>trunk ENI</strong> on newly launched container instances. A trunk ENI is a special network interface that multiplexes traffic for multiple branch ENIs — effectively allowing far more tasks to share the physical interface on the EC2 host while each task still gets its own logical ENI, IP address, and security group.</p><p>The result is dramatically higher task density on the same instance.</p><p><strong>ENI limits after enabling awsvpcTrunking:</strong></p><ul><li>c5.large → from 3 ENIs (2 task slots) → <strong>12 branch ENIs (10 task slots)</strong></li><li>c5.xlarge → from 4 ENIs (3 task slots) → <strong>14 branch ENIs (12 task slots)</strong></li><li>m5.large → from 3 ENIs (2 task slots) → <strong>12 branch ENIs (10 task slots)</strong></li><li>m5.2xlarge → from 4 ENIs (3 task slots) → <strong>18 branch ENIs (16 task slots)</strong></li><li>r6g.large → from 3 ENIs (2 task slots) → <strong>12 branch ENIs (10 task slots)</strong></li><li><strong>r6g.xlarge → from 4 ENIs (3 task slots) → 18 branch ENIs (16 task slots) ← my client&#39;s instance</strong></li><li>r6g.4xlarge → from 8 ENIs (7 task slots) → <strong>30 branch ENIs (28 task slots)</strong></li></ul><p>For my client’s r6g.xlarge, enabling trunking increased available task slots from 3 to 16 — more than a 5x improvement without changing instance type, without changing network mode, and without adding any cost.</p><p>The trunk ENI is fully managed by ECS. It is created automatically when the instance registers with the cluster and deleted automatically when the instance is terminated or deregistered. You never interact with it directly.</p><h3>How to enable it:</h3><ol><li>Open the Amazon ECS Console</li><li>In the left-hand navigation pane, look for account settings or go to your <strong>Account Settings</strong> / user settings page (note that console account settings typically apply the PutAccountSetting action to your current principal/user).</li><li>Locate <strong>awsvpcTrunking</strong> in the list of account settings.</li><li>Enable the setting.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k24Py22OaZLH1p2eacqAFQ.png" /></figure><h3>How ENI Trunking Works Internally</h3><p>Understanding the mechanism helps when troubleshooting.</p><p><strong>Without trunking:</strong></p><pre>EC2 Instance<br>├── eth0 (Primary ENI)   ← host-level traffic<br>├── eth1 (Task ENI)      ← Task A  (own IP, own SG)<br>├── eth2 (Task ENI)      ← Task B  (own IP, own SG)<br>└── [ENI limit reached — no more tasks]</pre><p><strong>With trunking enabled:</strong></p><pre>EC2 Instance<br>├── eth0 (Primary ENI)   ← host-level traffic<br>└── eth1 (Trunk ENI)     ← fully managed by ECS<br>    ├── branch ENI       ← Task A  (own IP, own SG)<br>    ├── branch ENI       ← Task B  (own IP, own SG)<br>    ├── branch ENI       ← Task C  (own IP, own SG)<br>    ├── branch ENI       ← Task D  (own IP, own SG)<br>    ├── branch ENI       ← Task E  (own IP, own SG)<br>    └── ... up to 16 tasks on m5.2xlarge</pre><p>Each task still believes it has its own dedicated ENI. From the task’s perspective — and from VPC’s perspective — nothing has changed. The multiplexing happens at the ECS networking layer, transparently. Same isolation. Same security groups. Same IP addresses. Just far more of them on one instance.</p><p><strong>EC2 Network Interfaces:</strong></p><p><strong>Before (old instance):</strong> Shows eth0 (primary, type: interface) and 1–2 task ENIs (type: interface). Interface type column shows only interface values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tGJ0UI8zz6ibgLHusGePQ.png" /></figure><p>Its took 10 –15 mins for my AWS account work.</p><p>The existing instances will be remains unaffected and it only applies when you terminate and relaunch them, or let the ASG replace them.</p><p><strong>After (new trunking instance):</strong> Shows eth0 (primary, type: interface) and eth1 with interface type <strong>trunk</strong>. The word trunk in the Type column is the visual proof this feature is active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oD66xvTMIV_d84KqkdCZcw.png" /></figure><h3>PoC: Step-by-Step with Screenshots</h3><p>Here is the exact sequence to demonstrate this in an AWS account.</p><h3>Step 1 — Check the Current Account Setting</h3><pre>aws ecs list-account-settings \<br>  --name awsvpcTrunking \<br>  --effective-settings \<br>  --region ap-south-1</pre><p>Expected output before enabling:</p><pre>{<br>    &quot;settings&quot;: [<br>        {<br>            &quot;name&quot;: &quot;awsvpcTrunking&quot;,<br>            &quot;value&quot;: &quot;disabled&quot;,<br>            &quot;principalArn&quot;: &quot;arn:aws:iam::123456789012:root&quot;<br>        }<br>    ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZD0F8ih7QqSaRfax6Dhtw.png" /></figure><h3>Step 2 — Verify ENI Count and Task Density on Existing Instance</h3><p>Check how many ENIs the current instance has and compare to how much memory is sitting idle:</p><pre># Check ENIs on the existing container instance<br>aws ec2 describe-network-interfaces \<br>  --filters &quot;Name=attachment.instance-id,Values=i-xxxxxxxxxxxxxxxxx&quot; \<br>  --query &#39;NetworkInterfaces[*].{Type:InterfaceType,ID:NetworkInterfaceId,IP:PrivateIpAddress}&#39; \<br>  --output table</pre><pre># Check how many tasks are running vs how much memory is available<br>aws ecs describe-container-instances \<br>  --cluster your-cluster-name \<br>  --container-instances CONTAINER_INSTANCE_ARN \<br>  --query &#39;containerInstances[*].{<br>    Tasks:runningTasksCount,<br>    CPURemaining:remainingResources[?name==`CPU`].integerValue|[0],<br>    MemRemaining:remainingResources[?name==`MEMORY`].integerValue|[0]<br>  }&#39; \<br>  --output table</pre><blockquote><em>ECS console → Cluster → Container Instances → click an instance. Shows: Tasks running: 3, CPU remaining: ~1980 units, Memory remaining: ~28,672 MB out of 32,768 MB. The gap between memory available and tasks running is the wasted capacity this fix addresses.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRttZLSYv4TpEUfucLRvbA.png" /></figure><blockquote><strong><em>EC2 Network Interfaces Before:</em></strong><em> EC2 console → Network Interfaces → filtered by old instance ID. Shows only </em><em>eth0 (type: interface, primary) and 1–2 task ENIs (type: interface). All entries in the Interface Type column show </em><em>interface — no trunk visible.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tGJ0UI8zz6ibgLHusGePQ.png" /></figure><h3>Step 3 — Enable awsvpcTrunking</h3><p><strong>Via AWS CLI:</strong></p><pre>aws ecs put-account-setting \<br>  --name awsvpcTrunking \<br>  --value enabled \<br>  --region ap-south-1</pre><p>Expected output:</p><pre>{<br>    &quot;setting&quot;: {<br>        &quot;name&quot;: &quot;awsvpcTrunking&quot;,<br>        &quot;value&quot;: &quot;enabled&quot;,<br>        &quot;principalArn&quot;: &quot;arn:aws:iam::123456789012:root&quot;<br>    }<br>}</pre><blockquote><strong><em>Via ECS Console:</em></strong><em> ECS Console → Account Settings (left nav) → find “AWSVPC Trunking” → toggle to Enabled → Save changes.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53OBwMbu10a_a9OLxtEMJg.png" /><figcaption>\</figcaption></figure><h4>We can enable it through AWS console :</h4><ol><li>Open the Amazon ECS Console</li><li>In the left-hand navigation pane, look for account settings or go to your <strong>Account Settings</strong> / user settings page (note that console account settings typically apply the PutAccountSetting action to your current principal/user).</li><li>Locate <strong>awsvpcTrunking</strong> in the list of account settings.</li><li>Enable the setting.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BQbl4KqhG8Wu8nULZ6pYA.png" /></figure><h3>Step 4 — Disable Resource-Based IPv4 DNS (Required Prerequisite)</h3><p>This step is easy to miss and will cause registration failures if skipped. New instances must have resource-based IPv4 DNS requests turned off.</p><p><strong>For a new instance launch (EC2 console):</strong> EC2 → Launch instance → Advanced details → Network interfaces section → uncheck “Enable resource-based IPv4 (A record) DNS requests”.</p><p><strong>For an existing instance (if you need to fix before re-registration):</strong></p><pre>aws ec2 modify-private-dns-name-options \<br>  --instance-id i-xxxxxxxxxxxxxxxxx \<br>  --no-enable-resource-name-dns-a-record \<br>  --no-dry-run</pre><blockquote><strong><em>DNS Setting at Launch:</em></strong><em> EC2 launch wizard → Advanced details section → showing “Enable resource-based IPv4 (A record) DNS requests” checkbox </em><strong><em>unchecked</em></strong><em>. Circle or highlight this checkbox — it is the easy-to-miss prerequisite.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3KMeC1vtp9P1jP2a8kW3g.png" /></figure><h3>Step 5 — Launch a New Container Instance</h3><p><strong>Important:</strong> ENI trunking only applies to instances launched after enabling the setting. Existing running instances will not be upgraded. You must launch a new instance.</p><p>Requirements checklist before launching:</p><ul><li>ECS-optimized AMI (Linux) — agent version 1.28.1 or later</li><li>Instance type on the supported list</li><li>ecsInstanceRole IAM role attached</li><li>Resource-based IPv4 DNS disabled</li><li>Instance in same VPC as tasks</li><li>Not in a shared subnet</li></ul><p>Once the instance is launched and registers with the cluster, it will briefly show REGISTERING status while ECS provisions the trunk ENI. Then it moves to ACTIVE.</p><pre># Watch the registration status<br>aws ecs describe-container-instances \<br>  --cluster your-cluster-name \<br>  --container-instances NEW_CONTAINER_INSTANCE_ARN \<br>  --query &#39;containerInstances[*].{Status:status,StatusReason:statusReason,Agent:agentVersion}&#39; \<br>  --output table</pre><blockquote><strong><em>New Instance ACTIVE:</em></strong><em> ECS console → Cluster → Container Instances tab → new instance showing status </em><em>ACTIVE. Note the &quot;Registered at&quot; timestamp is recent (after you enabled trunking). This confirms it is a trunking-eligible instance.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*Yse-RR_YA_xaHL3MI-wMPQ.png" /></figure><h3>Step 6 — Verify the Trunk ENI</h3><p>This is the money shot for the PoC. Go to EC2 Console → Network Interfaces → filter by the new instance ID.</p><pre>aws ec2 describe-network-interfaces \<br>  --filters &quot;Name=attachment.instance-id,Values=i-NEW-INSTANCE-ID&quot; \<br>  --query &#39;NetworkInterfaces[*].{Type:InterfaceType,ID:NetworkInterfaceId,IP:PrivateIpAddress,Desc:Description}&#39; \<br>  --output table</pre><p><strong>Old instance output (before trunking):</strong></p><pre>----------------------------------------------------------------------<br>|               DescribeNetworkInterfaces                            |<br>+-----------+---------------+-------------+--------------------------+<br>|   Desc    |      ID       |     IP      |          Type            |<br>+-----------+---------------+-------------+--------------------------+<br>|  Primary  |  eni-aaa111   |  10.0.1.50  |  interface               |<br>|  ecs-task |  eni-bbb222   |  10.0.1.51  |  interface               |<br>|  ecs-task |  eni-ccc333   |  10.0.1.52  |  interface               |<br>+-----------+---------------+-------------+--------------------------+</pre><p><strong>New instance output (after trunking):</strong></p><pre>----------------------------------------------------------------------<br>|               DescribeNetworkInterfaces                            |<br>+-----------+---------------+-------------+--------------------------+<br>|   Desc    |      ID       |     IP      |          Type            |<br>+-----------+---------------+-------------+--------------------------+<br>|  Primary  |  eni-aaa111   |  10.0.1.60  |  interface               |<br>| ECS Trunk |  eni-ddd444   |  10.0.1.61  |  trunk                   |<br>+-----------+---------------+-------------+--------------------------+</pre><p>The trunk value in the Type column is the before/after proof.</p><h3>Step 7 — Launch Tasks and Prove the Density Improvement</h3><p>Now scale up tasks on the new trunking-enabled instance and watch how many fit.</p><pre>aws ecs run-task \<br>  --cluster your-cluster-name \<br>  --task-definition your-task-def:latest \<br>  --count 10 \<br>  --launch-type EC2 \<br>  --network-configuration &quot;awsvpcConfiguration={subnets=[subnet-xxx],securityGroups=[sg-xxx],assignPublicIp=DISABLED}&quot;</pre><blockquote><strong><em>Instance Utilization After:</em></strong><em> ECS console → Cluster → Container Instances → click the new trunking instance. Shows: Tasks running: 6–8, Memory remaining: small amount (instance now actually utilized), CPU remaining: matching actual usage.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6ZEbSRIDkdtZ48J4yfQCg.png" /></figure><h3>Key Considerations Before You Enable This</h3><p><strong>1. Only new instances get trunking</strong> Existing running instances are not affected by enabling awsvpcTrunking. You must launch new instances after enabling the setting. Plan a rolling replacement — terminate old instances one at a time and let ECS launch replacements.</p><p><strong>2. Supported instance types only</strong> Not every EC2 instance type supports ENI trunking. Always verify your instance type in the <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-instance-eni.html">AWS documentation for supported instance types</a> before planning capacity.</p><p><strong>3. Linux only</strong> ENI trunking is not supported on Windows containers.</p><p><strong>4. Resource-based IPv4 DNS must be disabled</strong> Must be set at launch time — cannot be changed on a running instance.</p><p><strong>5. No shared subnets</strong> Container instances in shared subnets (from AWS Resource Access Manager) will fail to register.</p><p><strong>6. Public subnet instances lose public IP on stop/start</strong> If your container instance is in a public subnet and is stopped then restarted, it loses its public IP address. Use private subnets with a NAT Gateway for production.</p><p><strong>7. Tasks must be in the same VPC</strong> Tasks will fail with an attribute error if placed in a different VPC from their container instance.</p><p><strong>8. The trunk ENI uses the VPC default security group</strong> ECS creates the trunk ENI using the VPC default security group. Ensure your default security group rules allow the traffic patterns your tasks need.</p><h3>The Result for this problem</h3><p><strong>Before ENI trunking:</strong></p><ul><li>Instance type: r6g.xlarge (32 GB memory, 4 vCPUs, Graviton2 ARM)</li><li>ENI limit: 4 total, 1 primary = 3 task slots</li><li>Tasks per instance: 3</li><li>Memory utilization: ~19% (6 GB used out of 32 GB)</li><li>Cluster size: 8 instances for 24 tasks</li><li>New instances spinning up constantly on every deployment</li></ul><p><strong>After ENI trunking:</strong></p><ul><li>Same instance type: r6g.xlarge</li><li>ENI limit with trunking: 1 primary + 1 trunk = 18 branch ENI slots = <strong>16 task slots</strong></li><li>Tasks per instance: up to 16 (memory-bound now, not ENI-bound)</li><li>Memory utilization: ~100% (fully utilized as intended)</li><li>Cluster size: 2 instances for the same 24 tasks</li><li>Zero unnecessary instance launches</li></ul><p>The cluster shrank from 8 instances to 2. Same workload. Same instance type. No application changes. No network mode changes. One account setting toggle and a rolling fleet replacement.</p><h3>Quick Reference: Network Modes Compared</h3><p><strong>awsvpc with ENI trunking (recommended for production)</strong></p><ul><li>Each task gets its own ENI, IP, and security group</li><li>ENI trunking removes the density ceiling</li><li>Required for App Mesh, modern service discovery, zero-trust</li><li>Best choice for all new ECS workloads on EC2</li></ul><p><strong>awsvpc without ENI trunking</strong></p><ul><li>Works fine for small task counts or Fargate</li><li>Hits ENI wall quickly on EC2 with many tasks</li><li>Where my client was before this fix</li></ul><p><strong>bridge mode (legacy workaround)</strong></p><ul><li>Tasks share host network interface via Docker bridge</li><li>No ENI limit — pack tasks until memory/CPU runs out</li><li>No per-task security groups or IP isolation</li><li>Port conflicts, dynamic port mapping required</li><li>Cannot use App Mesh or modern service discovery</li><li>Use only for legacy workloads</li></ul><p><strong>host mode</strong></p><ul><li>Task uses EC2 instance network namespace directly</li><li>No isolation at all</li><li>Specialized use cases only</li></ul><h3>Tags</h3><p>#AWS #ECS #DevOps #CloudCost #EC2 #AWSNetworking #CloudArchitecture #ContainerOrchestration #SoftwareEngineering #CloudOptimization</p><p><em>All CLI commands and console steps reflect AWS documentation as of November 2026. Instance ENI limits vary by type — always verify the supported instance types list in the AWS ECS documentation before planning capacity.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a30c3044893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS ALB + Nginx: The Missing Security Layer in My Production Architecture — And How I Closed the…]]></title>
            <link>https://medium.com/@nagulesh03/aws-alb-nginx-the-missing-security-layer-in-my-production-architecture-and-how-i-closed-the-b81b04014e22?source=rss-5c20ebe6a9c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81b04014e22</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nagulesh]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 13:39:20 GMT</pubDate>
            <atom:updated>2026-10-27T13:39:20.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS ALB + Nginx: The Missing Security Layer in My Production Architecture — And How I Closed the Gap</h3><h3><strong>I Had Only an ALB and Containers. Then a Security Audit Happened.</strong></h3><p><em>How adding Nginx between my load balancer and containers solved every security header problem — without touching a single line of app code.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITTExHjxd5Y9bxSdNrXUNQ.png" /></figure><p>When I set up my AWS stack, it looked like every other production setup I had seen. An <strong>Application Load Balancer</strong> handling HTTPS, routing traffic to <strong>ECS containers</strong>, health checks passing, deployments clean. Everything worked.</p><p>Then a customer ran a security audit on our domain.</p><p>The report came back with a list of findings I couldn’t fix from the ALB console — because ALB simply doesn’t support them. No Content Security Policy. No HSTS preload. Server fingerprint headers leaking. No rate limiting at the application layer. No way to strip what the upstream containers were exposing.</p><p>That was the moment I understood why engineers at companies like Netflix, Uber, and Airbnb don’t just use ALB. They put <strong>Nginx in between</strong>.</p><p>This blog is that story — what ALB can’t do, what Nginx specifically solves, and how to combine them into a production-grade setup with the security posture your customers and auditors expect.</p><h3>The Setup That “Worked” But Had Gaps</h3><p>My original architecture was straightforward:</p><pre>Internet → HTTPS → AWS ALB → ECS Containers</pre><p>ALB was doing its job well:</p><ul><li>TLS termination with ACM (auto-renewing certificates)</li><li>Path-based routing to different services</li><li>Health checks replacing unhealthy containers</li><li>Multi-AZ availability</li></ul><p>But when I ran the domain through <a href="https://securityheaders.com/">securityheaders.com</a>, the grade was <strong>F</strong>.</p><blockquote><strong><em>Screenshot :</em></strong><em> securityheaders.com scan showing Grade F — missing CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNqUXtyUXncFB6QR1YbqGw.png" /></figure><p>And a curl -sI https://yourdomain.com revealed:</p><pre>HTTP/2 200<br>server: awselb/2.0<br>content-type: text/html</pre><p>No security headers. ALB fingerprint exposed. The upstream server version showing. All of it visible to anyone with a terminal.</p><h3>What ALB Cannot Do — The Hard Limits</h3><p>This is not a criticism of ALB. It’s excellent at what it’s built for. The problem is treating it as something it was never designed to be.</p><p><strong>What ALB is genuinely great at:</strong></p><ul><li>TLS termination with ACM certificates</li><li>Path and host-based routing to target groups</li><li>AWS WAF integration for DDoS and injection protection</li><li>Cognito / OIDC authentication before requests hit your app</li><li>Multi-AZ failover with zero configuration</li></ul><p><strong>Where ALB has no answer:</strong></p><ul><li>Adding custom response headers — no CSP, no HSTS, no X-Frame-Options</li><li>Rate limiting per IP at the application layer</li><li>Caching API responses</li><li>Stripping server fingerprint headers (Server: awselb/2.0 always leaks)</li><li>Serving static files directly</li><li>Custom error pages with any real logic</li><li>Request body size enforcement</li><li>GeoIP-based blocking</li></ul><p>The moment your security requirements go beyond routing and TLS, ALB has no answer. That boundary is exactly where Nginx starts.</p><h3>The Architecture That Fixes It</h3><p>Adding Nginx as a dedicated layer between ALB and your containers gives you full application-layer control — without changing your app code at all.</p><pre>Internet<br>    │<br>    ▼<br>AWS ALB<br>(TLS termination · WAF · Cognito auth · multi-AZ HA · AWS routing)<br>    │<br>    ▼<br>Nginx Container (ECS sidecar or dedicated task)<br>(CSP · HSTS · rate limiting · caching · header stripping · custom errors)<br>    │<br>    ▼<br>Your App Containers<br>(Pure business logic — no infrastructure concerns)</pre><p>Your app containers become completely infrastructure-agnostic. They ship business logic. Nginx owns the security and traffic behavior layer. When security policy changes, you update Nginx config — not the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxfGisTKdE-sb1K3k_OsGw.png" /></figure><h3>Nginx-Specific Features That Solve the Audit</h3><p>Let’s go through every finding from that security audit and exactly how Nginx fixes it.</p><h3>1. Content Security Policy (CSP)</h3><p><strong>What it is:</strong> CSP tells browsers which sources are allowed to load scripts, styles, images, and fonts on your page. It’s the primary browser-enforced defense against XSS attacks.</p><p><strong>Without it:</strong> An attacker exploiting an XSS vector can load scripts from any external origin. The browser has no policy to block them.</p><p><strong>Nginx config:</strong></p><pre>add_header Content-Security-Policy<br>  &quot;default-src &#39;self&#39;;<br>   script-src &#39;self&#39; https://cdn.yourdomain.com;<br>   style-src &#39;self&#39; &#39;unsafe-inline&#39;;<br>   img-src &#39;self&#39; data: https:;<br>   font-src &#39;self&#39; https://fonts.gstatic.com;<br>   frame-ancestors &#39;none&#39;;<br>   upgrade-insecure-requests;<br>   report-uri /csp-report&quot; always;</pre><blockquote><strong><em>Pro tip:</em></strong><em> Start with </em><em>Content-Security-Policy-Report-Only instead of </em><em>Content-Security-Policy. This reports violations to your </em><em>report-uri endpoint without blocking anything. Once you&#39;ve cleaned up all violations, switch to the enforcing header.</em></blockquote><p>Before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPHgQQVRAaTV-rfgKOX0iw.png" /></figure><p>After :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jvq-CuBBW5D8nzVmUiUWqQ.png" /></figure><h3>2. HTTP Strict Transport Security (HSTS)</h3><p><strong>What it is:</strong> HSTS instructs browsers to always connect to your domain over HTTPS — even if a user types http://. It also prevents SSL stripping attacks where a MITM attacker downgrades your connection.</p><p><strong>Without it:</strong> Even though ALB handles your TLS, the very first HTTP request a new visitor makes is vulnerable before the redirect happens.</p><p><strong>Nginx config:</strong></p><pre>add_header Strict-Transport-Security<br>  &quot;max-age=31536000; includeSubDomains; preload&quot; always;</pre><blockquote><strong><em>Start with </em></strong><strong><em>max-age=86400 (1 day) during testing.</em></strong><em> Once you&#39;ve confirmed no HTTP-only subdomains or resources are breaking, increase to </em><em>31536000 (1 year) and add </em><em>preload to submit your domain to browser HSTS preload lists.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*2_TArQgiUrV-BEHEh7Ejug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*RoxR72Kbh1ZcnpQK51aFwg.png" /></figure><h3>3. X-Frame-Options (Clickjacking Protection)</h3><p><strong>What it is:</strong> Prevents your application from being embedded in an &lt;iframe&gt; on another website. Clickjacking attacks trick users into clicking UI elements on your app while it&#39;s invisibly overlaid on a malicious page.</p><pre>add_header X-Frame-Options &quot;DENY&quot; always;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*I30n-LjQ0O-Xosn8kCBrAw.png" /></figure><h3>4. X-Content-Type-Options</h3><p><strong>What it is:</strong> Prevents browsers from MIME-sniffing a response away from its declared Content-Type. Stops certain content confusion attacks where a browser might execute a response as a different type than intended.</p><pre>add_header X-Content-Type-Options &quot;nosniff&quot; always;</pre><p>Small header. Huge impact on certain attack classes. One line.</p><h3>5. Referrer-Policy</h3><p><strong>What it is:</strong> Controls how much information from your URL is sent to external sites when users click links leaving your app. Without it, your full internal URL — potentially including auth tokens, internal paths, or user identifiers in query strings — gets sent to every third-party site your users navigate to.</p><pre>add_header Referrer-Policy &quot;strict-origin-when-cross-origin&quot; always;</pre><p>This sends the full URL for same-origin requests, only the origin (no path or query string) for cross-origin HTTPS requests, and nothing for cross-origin HTTP requests.</p><h3>6. Permissions-Policy (formerly Feature-Policy)</h3><p><strong>What it is:</strong> Controls which browser APIs and device features your page or its embedded content can access — camera, microphone, geolocation, payment, etc. Even if your app never uses these, restricting them limits what a successfully injected script can access.</p><pre>add_header Permissions-Policy<br>  &quot;camera=(), microphone=(), geolocation=(), payment=(), usb=(), magnetometer=()&quot; always;</pre><h3>7. Server Header Stripping (Hide Your Fingerprint)</h3><p><strong>What it is:</strong> By default, ALB exposes Server: awselb/2.0. Your upstream containers might add Server: gunicorn/21.2.0 or Server: nginx/1.25.3. These headers tell attackers exactly what software stack to search exploit databases for.</p><pre># In the http block — hides Nginx version number<br>server_tokens off;<br><br># Remove the Server header entirely<br># Requires the headers-more-nginx-module (available in nginx-extras or OpenResty)<br>more_clear_headers Server;<br># Or replace it with something neutral<br>add_header Server &quot;webserver&quot; always;<br># Also hide upstream headers your containers expose<br>proxy_hide_header X-Powered-By;<br>proxy_hide_header X-AspNet-Version;<br>proxy_hide_header X-Generator;</pre><p>The curl request to the endpoint should contain all this information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*gS08lPaLNL4AL7pO1EJolw.png" /></figure><h3>8. Rate Limiting (Per-IP Request Throttling)</h3><p><strong>What it is:</strong> Limits how many requests a single IP address can make per second. First line of defense against brute force attacks, credential stuffing, API scraping, and DDoS amplification.</p><p>ALB’s WAF rate limiting exists but operates at the rule level with minimum thresholds of 100 requests per 5 minutes — coarse and expensive. Nginx rate limiting is precise, free, and instant.</p><pre># Define rate limit zones in the http block<br>limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;<br>limit_req_zone $binary_remote_addr zone=login_limit:10m rate=3r/m;</pre><pre>server {<br>  # Apply to API endpoints — 10 req/sec, burst of 20<br>  location /api/ {<br>    limit_req zone=api_limit burst=20 nodelay;<br>    limit_req_status 429;<br>    add_header Retry-After 1 always;<br>    proxy_pass <a href="http://upstream_containers;/">http://upstream_containers;</a><br>  }</pre><pre>  # Stricter limit on login — 3 attempts per minute<br>  location /api/auth/login {<br>    limit_req zone=login_limit burst=5;<br>    limit_req_status 429;<br>    proxy_pass <a href="http://upstream_containers;/">http://upstream_containers;</a><br>  }</pre><pre>  # Health check excluded from rate limiting<br>  location /health {<br>    access_log off;<br>    proxy_pass <a href="http://upstream_containers;/">http://upstream_containers;</a><br>  }<br>}</pre><pre># Quick test command<br>for i in $(seq 1 30); do<br>  curl -s -o /dev/null -w &quot;Request $i: %{http_code}\n&quot; https://yourdomain.com/api/test<br>done</pre><blockquote><strong><em>Screenshot :</em></strong><em> Terminal showing a loop of curl requests — first 10 returning </em><em>200, then </em><em>429 Too Many Requests appearing as rate limit kicks in.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaC-Sxoym90n-TntJeQnrA.png" /></figure><h3>9. Response Caching</h3><p><strong>What it is:</strong> Cache upstream API responses in Nginx memory or disk. A cached response is served directly by Nginx — your containers are never hit. For read-heavy endpoints (product listings, config APIs, public data), this can reduce container load by 80–90%.</p><pre># Define cache zone in the http block<br>proxy_cache_path /tmp/nginx_cache<br>  levels=1:2<br>  keys_zone=api_cache:10m<br>  max_size=500m<br>  inactive=60m<br>  use_temp_path=off;<br><br>server {<br>  location /api/v1/products {<br>    proxy_cache api_cache;<br>    proxy_cache_valid 200 30s;<br>    proxy_cache_valid 404 5s;<br>    proxy_cache_methods GET HEAD;<br>    proxy_cache_bypass $http_pragma;<br>    # This header tells you whether Nginx served from cache<br>    add_header X-Cache-Status $upstream_cache_status;<br>    proxy_pass http://upstream_containers;<br>  }<br>}</pre><blockquote><strong><em>Screenshot :</em></strong><em> curl requests to the verify the cache:</em></blockquote><pre>docker compose restart nginx &amp;&amp; sleep 3        # clear cache first<br>for i in 1 2 3; do<br>  curl -so /dev/null -D- -w &quot;time=%{time_total}s\n&quot; &quot;$B/app.styles.7f3c9a2b1e.css&quot; | grep -i x-cache-status<br>done</pre><ul><li>First: X-Cache-Status: MISS — response time 240ms</li><li>Second: X-Cache-Status: HIT — response time 4ms</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWauh7UNK7kdp2OvHMSMZw.png" /></figure><h3>10. Request Body Size and Timeout Control</h3><p><strong>What it is:</strong> Prevents large payload attacks (XML bombs, ZIP bombs, malformed multipart abuse) by rejecting oversized requests before they reach your application. Also controls connection timeouts to prevent Slowloris-style attacks.</p><pre># In http or server block<br>client_max_body_size 10m;      # Reject payloads &gt; 10MB at Nginx layer<br>client_body_timeout 12s;        # Drop connections sending body too slowly<br>client_header_timeout 12s;      # Drop connections sending headers too slowly<br>keepalive_timeout 15s;          # Close idle keep-alive connections<br>send_timeout 10s;               # Drop connections receiving response too slowly</pre><h3>11. Custom Error Pages</h3><p><strong>What it is:</strong> Return controlled, branded, or JSON error responses instead of default server error pages that leak implementation details.</p><pre>error_page 404 /errors/404.json;<br>error_page 429 /errors/429.json;<br>error_page 500 502 503 504 /errors/50x.json;<br><br>location /errors/ {<br>  root /srv/static;<br>  internal;           # Only accessible via error_page directive, not directly<br>  add_header Content-Type application/json;<br>}</pre><h3>12. GeoIP Blocking (with GeoIP2 Module)</h3><p><strong>What it is:</strong> Block or restrict traffic by country using MaxMind’s GeoLite2 database. Common for compliance requirements — GDPR jurisdiction restrictions, sanctions compliance, or limiting admin interfaces to specific regions.</p><pre># Requires ngx_http_geoip2_module<br>load_module modules/ngx_http_geoip2_module.so;</pre><pre>geoip2 /etc/nginx/GeoLite2-Country.mmdb {<br>  $geoip2_data_country_code country iso_code;<br>}</pre><pre>map $geoip2_data_country_code $blocked_country {<br>  default 0;<br>  KP      1;   # North Korea<br>  # Add others per your compliance requirements<br>}</pre><pre>server {<br>  if ($blocked_country) {<br>    return 403;<br>  }<br>}</pre><h3>The Sample Nginx Config (Template)</h3><p>Here’s a production-ready Nginx config that combines everything above:</p><pre># /etc/nginx/nginx.conf<br>user nginx;<br>worker_processes auto;<br>worker_rlimit_nofile 65535;<br><br>events {<br>  worker_connections 1024;<br>  use epoll;<br>  multi_accept on;<br>}<br><br>http {<br>  # ── Basic settings ──────────────────────────────────────────<br>  sendfile            on;<br>  tcp_nopush          on;<br>  tcp_nodelay         on;<br>  server_tokens       off;          # Hide Nginx version<br>  keepalive_timeout   15s;<br>  client_max_body_size 10m;<br>  client_body_timeout 12s;<br>  client_header_timeout 12s;<br>  send_timeout        10s;<br><br>  # ── Rate limiting zones ──────────────────────────────────────<br>  limit_req_zone $binary_remote_addr zone=api_limit:10m  rate=10r/s;<br>  limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=3r/m;<br><br>  # ── Response cache zone ──────────────────────────────────────<br>  proxy_cache_path /tmp/nginx_cache<br>    levels=1:2<br>    keys_zone=api_cache:10m<br>    max_size=500m<br>    inactive=60m<br>    use_temp_path=off;<br><br>  # ── Upstream (your ECS containers) ──────────────────────────<br>  upstream app_containers {<br>    server app:8080;<br>    keepalive 32;<br>  }<br><br>  server {<br>    listen 80;<br>    server_name _;<br><br>    # ── Security headers (applied to all responses) ──────────<br>    add_header Strict-Transport-Security <br>      &quot;max-age=31536000; includeSubDomains; preload&quot; always;<br>    add_header Content-Security-Policy<br>      &quot;default-src &#39;self&#39;; script-src &#39;self&#39;; style-src &#39;self&#39; &#39;unsafe-inline&#39;; img-src &#39;self&#39; data: https:; frame-ancestors &#39;none&#39;; upgrade-insecure-requests;&quot; always;<br>    add_header X-Frame-Options          &quot;DENY&quot;                        always;<br>    add_header X-Content-Type-Options   &quot;nosniff&quot;                     always;<br>    add_header Referrer-Policy          &quot;strict-origin-when-cross-origin&quot; always;<br>    add_header Permissions-Policy<br>      &quot;camera=(), microphone=(), geolocation=(), payment=()&quot;          always;<br><br>    # ── Strip fingerprint headers ────────────────────────────<br>    proxy_hide_header X-Powered-By;<br>    proxy_hide_header X-AspNet-Version;<br><br>    # ── Proxy settings ────────────────────────────────────────<br>    proxy_set_header Host              $host;<br>    proxy_set_header X-Real-IP         $remote_addr;<br>    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;<br>    proxy_set_header X-Forwarded-Proto $scheme;<br>    proxy_set_header X-Request-ID      $request_id;<br>    proxy_http_version 1.1;<br>    proxy_set_header Connection &quot;&quot;;<br><br>    # ── Health check ──────────────────────────────────────────<br>    location /health {<br>      access_log off;<br>      proxy_pass http://app_containers;<br>    }<br><br>    # ── Auth endpoint — strict rate limiting ──────────────────<br>    location /api/auth/ {<br>      limit_req zone=auth_limit burst=5;<br>      limit_req_status 429;<br>      proxy_pass http://app_containers;<br>    }<br><br>    # ── API endpoints — with caching + rate limiting ──────────<br>    location /api/v1/products {<br>      limit_req zone=api_limit burst=20 nodelay;<br>      limit_req_status 429;<br><br>      proxy_cache api_cache;<br>      proxy_cache_valid 200 30s;<br>      proxy_cache_methods GET HEAD;<br>      add_header X-Cache-Status $upstream_cache_status always;<br><br>      proxy_pass http://app_containers;<br>    }<br><br>    # ── All other API routes ──────────────────────────────────<br>    location /api/ {<br>      limit_req zone=api_limit burst=20 nodelay;<br>      limit_req_status 429;<br>      proxy_pass http://app_containers;<br>    }<br><br>    # ── Static assets — served directly, long cache ───────────<br>    location /static/ {<br>      root /srv;<br>      expires 30d;<br>      add_header Cache-Control &quot;public, immutable&quot;;<br>      access_log off;<br>    }<br><br>    # ── Custom error pages ─────────────────────────────────────<br>    error_page 404 /errors/404.json;<br>    error_page 429 /errors/429.json;<br>    error_page 500 502 503 504 /errors/50x.json;<br><br>    location /errors/ {<br>      root /srv/static;<br>      internal;<br>    }<br>  }<br>}<br></pre><h3>The Before and After</h3><p>Here’s the difference after adding Nginx to the stack.</p><p><strong>Before (ALB + Containers only):</strong></p><pre>$ curl -sI https://yourdomain.com<br><br>HTTP/2 200<br>server: awselb/2.0<br>content-type: text/html; charset=utf-8<br>content-length: 4823</pre><p>No security headers. Server fingerprint exposed. Grade: <strong>F</strong> on securityheaders.com.</p><p><strong>After (ALB → Nginx → Containers):</strong></p><pre>$ curl -sI https://yourdomain.com<br><br>HTTP/2 200<br>content-type: text/html; charset=utf-8<br>strict-transport-security: max-age=31536000; includeSubDomains; preload<br>content-security-policy: default-src &#39;self&#39;; script-src &#39;self&#39;; ...<br>x-frame-options: DENY<br>x-content-type-options: nosniff<br>referrer-policy: strict-origin-when-cross-origin<br>permissions-policy: camera=(), microphone=(), geolocation=(), payment=()<br>x-request-id: 7f3a21bc-04d1-4a9e-b891-2c3d5f6e8901</pre><p>Server header: gone. All security headers: present. Grade: <strong>A</strong> on securityheaders.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMzYzwzHv5l-SbLwkImKcQ.png" /></figure><h3>Deployment: Running Nginx as an ECS Sidecar</h3><p>The cleanest way to add Nginx to an existing ECS setup is as a <strong>sidecar container</strong> in the same task definition. Nginx runs alongside your app container, proxying on port 80, and your app container only listens on a local port.</p><pre>{<br>  &quot;family&quot;: &quot;app-task&quot;,<br>  &quot;containerDefinitions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;nginx&quot;,<br>      &quot;image&quot;: &quot;nginx:1.25-alpine&quot;,<br>      &quot;portMappings&quot;: [{ &quot;containerPort&quot;: 80 }],<br>      &quot;mountPoints&quot;: [{<br>        &quot;sourceVolume&quot;: &quot;nginx-config&quot;,<br>        &quot;containerPath&quot;: &quot;/etc/nginx/nginx.conf&quot;<br>      }],<br>      &quot;dependsOn&quot;: [{<br>        &quot;containerName&quot;: &quot;app&quot;,<br>        &quot;condition&quot;: &quot;START&quot;<br>      }],<br>      &quot;essential&quot;: true<br>    },<br>    {<br>      &quot;name&quot;: &quot;app&quot;,<br>      &quot;image&quot;: &quot;your-app:latest&quot;,<br>      &quot;portMappings&quot;: [{ &quot;containerPort&quot;: 8080 }],<br>      &quot;essential&quot;: true<br>    }<br>  ]<br>}</pre><p>ALB target group points to port 80 on the task. Nginx receives all traffic, applies security headers and rate limiting, then forwards to localhost:8080 where your app container listens. Your app never changes.</p><h3>Best Practice Checklist</h3><p>Before shipping this to production, verify:</p><ul><li>[ ] All add_header directives use the always flag — this makes headers appear on error responses (4xx, 5xx), not just successful responses</li><li>[ ] server_tokens off is in the http block, not just server</li><li>[ ] CSP started in Report-Only mode first, violations reviewed, then switched to enforcing</li><li>[ ] HSTS tested with short max-age (86400) before setting 31536000 + preload</li><li>[ ] Health check endpoint (/health) excluded from rate limiting zones</li><li>[ ] Cache only applied to GET and HEAD methods (never POST, PUT, DELETE)</li><li>[ ] proxy_hide_header stripping X-Powered-By and other app-server headers</li><li>[ ] client_max_body_size set to a sensible limit for your use case</li><li>[ ] Error pages use internal location — not directly accessible via URL</li><li>[ ] Nginx logs include $request_id for request tracing across services</li></ul><h3>Quick Reference: ALB vs Nginx vs Combined</h3><p><strong>Let ALB own the AWS infrastructure layer:</strong></p><ul><li>TLS/HTTPS termination with ACM — zero cert management</li><li>Multi-AZ failover — automatic, no config needed</li><li>AWS WAF — DDoS and injection protection at the edge</li><li>Cognito / OIDC authentication before traffic reaches your app</li><li>Managed auto-scaling and AWS service discovery</li></ul><p><strong>Let Nginx own the application traffic layer:</strong></p><ul><li>CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy</li><li>Rate limiting per IP — precise, free, instant</li><li>Response caching — serve hot endpoints from memory</li><li>Server header stripping — zero fingerprint exposure</li><li>Static file serving — never hits your app containers</li><li>GeoIP blocking — jurisdiction and compliance enforcement</li><li>Custom error pages with full control</li></ul><h3>The Takeaway</h3><p>ALB is excellent at what it does: managed TLS, AWS-native routing, WAF integration, multi-AZ availability. But it was never designed to be an application-layer proxy with security header control, rate limiting, and caching.</p><p>Nginx was built for exactly those things.</p><p>The combination is not over-engineering. It’s a <strong>separation of concerns</strong> that lets your infrastructure team control security and traffic behavior independently of your application team. When your CSP policy changes, you update Nginx config. When you need to rate-limit a new endpoint, you update Nginx config. No app deployment. No code review. No coordination overhead.</p><p>Your app stays focused on business logic. Your infrastructure layer handles everything else.</p><p><em>If this helped solve a problem you were facing, share it — security misconfigurations in ALB-only setups are more common than most engineering teams realize.</em></p><p><em>Found a better way to handle any of these? Drop it in the comments.</em></p><p><strong>Tags:</strong> AWS Nginx DevOps Security ECS CloudInfrastructure WebSecurity CSP LoadBalancing SRE</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81b04014e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Host Langfuse on AWS EC2: A Complete Guide to Deployment, Security & User Management]]></title>
            <link>https://medium.com/@nagulesh03/self-host-langfuse-on-aws-ec2-a-complete-guide-to-deployment-security-user-management-c64a19b8cab8?source=rss-5c20ebe6a9c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c64a19b8cab8</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[ai-observability]]></category>
            <category><![CDATA[langfuse]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nagulesh]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 07:04:33 GMT</pubDate>
            <atom:updated>2026-10-16T07:04:33.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Langfuse is an open-source LLM observability platform (tracing, evaluation, monitoring). This guide covers the full journey of setting it up on an Amazon Linux EC2 instance using Docker Compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*8zfCVtYREXv5rfh0.png" /></figure><h3>1. EC2 Instance Requirements</h3><p>Setting Recommended Value Instance Type t3.xlarge (4 vCPU, 16 GiB RAM) or higher OS Amazon Linux 2023 (or Amazon Linux 2) Storage 100 GiB (observability data grows fast) Public IP Assign one if sending traces from external sources</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wR1lNI0gpTgxRjV_fI6rgw.png" /></figure><h3>Security Group Inbound Rules</h3><p>Port Protocol Purpose — 3000 TCP Langfuse Web UI &amp; API, 9090 TCP MinIO (blob storage, optional external access)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akV_9dzN6OP79n_FmTz4rA.png" /></figure><h3>IAM Permissions for the EC2</h3><p>It should have the AWS Managed IAM Policy : AmazonSSMManagedInstanceCore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSoyoctmIHUdriLWK_MCYQ.png" /></figure><h3>Connect your EC2 with the System Manager SSM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LS0xoGrljMOrjH_pzXa1TQ.png" /></figure><h3>2. Install Docker &amp; Docker Compose</h3><h3>Amazon Linux 2023</h3><pre>sudo dnf update -y<br>sudo dnf install -y docker<br>sudo systemctl start docker<br>sudo systemctl enable docker<br>sudo usermod -aG docker ec2-user</pre><h3>Amazon Linux 2</h3><pre>sudo yum update -y<br>sudo amazon-linux-extras install docker -y<br>sudo systemctl start docker<br>sudo systemctl enable docker<br>sudo usermod -aG docker ec2-user</pre><h3>Install Docker Compose Plugin</h3><pre>sudo mkdir -p /usr/local/lib/docker/cli-plugins<br>sudo curl -SL https://github.com/docker/compose/releases/latest/download/docker-compose-linux-x86_64 \<br>  -o /usr/local/lib/docker/cli-plugins/docker-compose<br>sudo chmod +x /usr/local/lib/docker/cli-plugins/docker-compose</pre><h3>Verify</h3><pre># Verify<br>docker compose version<br>sudo usermod -aG docker $(whoami) &amp;&amp; sg docker -c &quot;docker run hello-world&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*dgHGy8-cEVXf1YYcnEZ-0A.png" /></figure><h3>Install Gi</h3><pre>sudo dnf install -y git</pre><h3>3. Clone Langfuse Repository</h3><pre>cd ~ &amp;&amp; git clone https://github.com/langfuse/langfuse.git<br>cd langfuse</pre><h3>4. Generate Secrets</h3><p>Run these commands to generate strong secrets before editing docker-compose.yml:</p><pre>echo &quot;NEXTAUTH_SECRET=$(openssl rand -hex 32)&quot;<br>echo &quot;SALT=$(openssl rand -hex 16)&quot;<br>echo &quot;ENCRYPTION_KEY=$(openssl rand -hex 32)&quot;<br>echo &quot;DB_PASSWORD=$(openssl rand -hex 16)&quot;<br>echo &quot;REDIS_PASSWORD=$(openssl rand -hex 16)&quot;<br>echo &quot;MINIO_PASSWORD=$(openssl rand -hex 16)&quot;<br>echo &quot;CLICKHOUSE_PASSWORD=$(openssl rand -hex 16)&quot;</pre><p>Save these values — you will use them in the next step.</p><h3>5. Update docker-compose.yml (Things to Modify)</h3><p>Open the file:</p><pre>nano docker-compose.yml</pre><p>All lines marked # CHANGEME must be updated. Here is a full summary:</p><h3>5.1 Auth &amp; App Secrets (langfuse-worker + langfuse-web)</h3><pre>NEXTAUTH_URL: http://&lt;your-ec2-public-ip&gt;:3000   # Replace with actual EC2 public IP<br>NEXTAUTH_SECRET: &lt;generated-secret&gt;               # openssl rand -hex 32<br>SALT: &lt;generated-salt&gt;                            # openssl rand -hex 16<br>ENCRYPTION_KEY: &lt;generated-key&gt;                   # openssl rand -hex 32</pre><h3>5.2 PostgreSQL Password</h3><p>Update in <strong>two places</strong> — they must match:</p><pre># In langfuse-worker / langfuse-web environment:<br>DATABASE_URL: postgresql://postgres:&lt;DB_PASSWORD&gt;@postgres:5432/postgres</pre><pre># In postgres service:<br>POSTGRES_PASSWORD: &lt;DB_PASSWORD&gt;</pre><h3>5.3 Redis Password</h3><p>Update in <strong>two places</strong> — they must match exactly:</p><pre># In langfuse-worker environment:<br>REDIS_AUTH: &lt;REDIS_PASSWORD&gt;</pre><pre># In redis service command:<br>command: &gt;<br>  --requirepass &lt;REDIS_PASSWORD&gt;<br>  --maxmemory-policy noeviction</pre><blockquote><em>⚠️ Mismatch here causes </em><em>WRONGPASS invalid username-password pair errors.</em></blockquote><h3>5.4 ClickHouse Password</h3><p>Update in <strong>two places</strong> — they must match:</p><pre># In langfuse-worker / langfuse-web environment:<br>CLICKHOUSE_PASSWORD: &lt;CLICKHOUSE_PASSWORD&gt;</pre><pre># In clickhouse service:<br>CLICKHOUSE_PASSWORD: &lt;CLICKHOUSE_PASSWORD&gt;</pre><h3>5.5 MinIO (S3 Blob Storage) Password</h3><p>Update in <strong>four places</strong> — all must match:</p><pre># In minio service:<br>MINIO_ROOT_PASSWORD: &lt;MINIO_PASSWORD&gt;</pre><pre># In langfuse-worker environment (3 occurrences):<br>LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: &lt;MINIO_PASSWORD&gt;<br>LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY: &lt;MINIO_PASSWORD&gt;<br>LANGFUSE_S3_BATCH_EXPORT_SECRET_ACCESS_KEY: &lt;MINIO_PASSWORD&gt;</pre><h3>5.6 Optional: Pre-create Admin User</h3><p>Add these to the langfuse-web environment to auto-create an admin account on first start:</p><pre>LANGFUSE_INIT_USER_EMAIL: admin@yourdomain.com<br>LANGFUSE_INIT_USER_NAME: Admin<br>LANGFUSE_INIT_USER_PASSWORD: YourStrongPassword123!<br>LANGFUSE_INIT_ORG_NAME: MyOrganization<br>LANGFUSE_INIT_PROJECT_NAME: MyProject</pre><h3>Complete Modification Checklist</h3><p>Variable Location Action NEXTAUTH_URL worker + web Set EC2 public IP NEXTAUTH_SECRET web openssl rand -hex 32 SALT worker + web openssl rand -hex 16 ENCRYPTION_KEY worker + web openssl rand -hex 32 DATABASE_URL worker + web Update password POSTGRES_PASSWORD postgres service Match DATABASE_URL REDIS_AUTH worker New password redis --requirepass redis service Match REDIS_AUTH CLICKHOUSE_PASSWORD worker + clickhouse service New password MINIO_ROOT_PASSWORD minio service New password LANGFUSE_S3_*_SECRET_ACCESS_KEY (×3) worker Match MINIO_ROOT_PASSWORD</p><h3>6. Start Langfuse</h3><pre>docker compose up -d</pre><p>Wait 2–3 minutes for all containers to initialize. ClickHouse takes the longest (schema migrations).</p><p>Check status:</p><pre>docker compose ps<br>docker compose logs -f</pre><h3>7. Ports Reference</h3><p>Port Service Accessible From</p><pre>3000 Langfuse Web UI &amp; API Public (EC2 security group) <br>9090 MinIO blob storage Public (EC2 security group) <br>3030 Langfuse Worker localhost only <br>6379 Redis localhost only <br>5432 PostgreSQL localhost only <br>8123 ClickHouse HTTP localhost only <br>9000 ClickHouse TCP localhost only <br>9091 MinIO Console localhost only</pre><h3>8. Verify the Setup</h3><h3>Check all containers are running</h3><pre>docker ps</pre><p>All 6 containers should be Up and healthy:</p><ul><li>langfuse-langfuse-web-1</li><li>langfuse-langfuse-worker-1</li><li>langfuse-redis-1</li><li>langfuse-postgres-1</li><li>langfuse-clickhouse-1</li><li>langfuse-minio-1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hT-i9byVTP-mQeiTSAw26w.png" /></figure><h3>Health check via curl</h3><pre>curl http://localhost:3000/api/public/health<br># Expected: {&quot;status&quot;:&quot;ok&quot;}</pre><h3>Verify Redis</h3><pre>docker exec -it langfuse-redis-1 redis-cli -a &lt;REDIS_PASSWORD&gt; ping<br># Expected: PONG</pre><h3>Verify PostgreSQL</h3><pre>docker exec -it langfuse-postgres-1 pg_isready -U postgres<br># Expected: localhost:5432 - accepting connections</pre><h3>Verify ClickHouse</h3><pre>curl http://localhost:8123/ping<br># Expected: Ok.</pre><h3>Open in Browser</h3><pre>http://&lt;your-ec2-public-ip&gt;:3000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oewGnDEGgsiTEhKzfrC4AA.png" /></figure><h3>9. First Login</h3><p>If you did <strong>not</strong> set LANGFUSE_INIT_USER_* variables:</p><ol><li>Open http://&lt;ec2-ip&gt;:3000</li><li>Click <strong>Sign Up</strong></li><li>Enter your email, name, and password</li><li>The first account created becomes the admin</li></ol><p>If you <strong>did</strong> set LANGFUSE_INIT_USER_* variables:</p><ul><li>Use the email and password you configured</li></ul><p>After login, go to <strong>Settings → API Keys</strong> to get your:</p><ul><li>LANGFUSE_PUBLIC_KEY</li><li>LANGFUSE_SECRET_KEY</li></ul><h3>10. User Roles &amp; Access Management</h3><h3>Organization Level Roles</h3><p>Role What They Can Do <strong>Owner</strong> Full control — manage members, billing, delete org <strong>Admin</strong> Manage members and settings, cannot delete org <strong>Member</strong> Access only projects they are invited to</p><h3>Project Level Roles</h3><p>Role What They Can Do <strong>Owner</strong> Full control of the project <strong>Admin</strong> Manage project settings and members <strong>Editor</strong> Create/edit traces, prompts, datasets <strong>Viewer</strong> Read-only access — can only view data</p><h3>First User = Owner (Automatic)</h3><p>The <strong>first account</strong> created on a self-hosted Langfuse instance is automatically the <strong>Organization Owner</strong> with full admin privileges. No manual promotion needed.</p><blockquote><em>⚠️ The </em><em>LANGFUSE_INIT_USER_* variables in </em><em>docker-compose.yml are only needed if you want to auto-create a user before first startup (e.g. for CI/CD or automated deployments). If you signed up manually via the UI, you do </em><strong><em>not</em></strong><em> need to set these.</em></blockquote><h3>When Do You Need LANGFUSE_INIT_USER Variables?</h3><p>Scenario Need INIT variables? Already signed up via UI ❌ No Want to automate setup (CI/CD, fresh deploy) ✅ Yes Setting up a second fresh instance ✅ Yes Resetting and redeploying from scratch ✅ Yes</p><h3>Create Organization &amp; Project (First Time)</h3><p>After signup, Langfuse walks you through this automatically:</p><ol><li><strong>Create Organization</strong> — enter your org name and click Create</li><li><strong>Create Project</strong> — enter your project name and click Create</li><li><strong>Get API Keys</strong> — go to <strong>Settings → API Keys → Create new API Key</strong></li></ol><ul><li>Public Key → starts with pk-lf-...</li><li>Secret Key → starts with sk-lf-...</li></ul><h3>Invite Other Users</h3><p>As the Owner, you can invite teammates:</p><ol><li>Go to <strong>Settings → Organization Members → Invite Member</strong></li><li>Enter their email and assign a role: Owner / Admin / Member</li><li>Then add them to your project under <strong>Settings → Project Members</strong> with role Editor or Viewer</li></ol><h3>Verify You Are the Owner</h3><ol><li>Go to <strong>Settings</strong> (top right or sidebar)</li><li>Click <strong>Organization Members</strong></li><li>Your email should show role <strong>Owner</strong></li></ol><h3>11. Disable Public Signup (Recommended)</h3><p>By default, anyone who can reach port 3000 can create an account. After you’ve created your admin account, disable public signups.</p><h3>Step 1 — Edit docker-compose.yml</h3><pre>nano docker-compose.yml</pre><p>Add AUTH_DISABLE_SIGNUP under the langfuse-web environment section:</p><pre>langfuse-web:<br>    image: docker.langfuse.com/langfuse/langfuse:4<br>    restart: always<br>    ports:<br>      - 3000:3000<br>    environment:<br>      &lt;&lt;: *langfuse-worker-env<br>      NEXTAUTH_SECRET: ${NEXTAUTH_SECRET:-your-secret}<br>      AUTH_DISABLE_SIGNUP: &quot;true&quot;        # ← ADD THIS LINE<br>      ...</pre><h3>Step 2 — Restart</h3><pre>docker compose down<br>docker compose up -d</pre><h3>Step 3 — Verify</h3><p>Open your browser in <strong>incognito mode</strong> and go to:</p><pre>http://&lt;your-ec2-public-ip&gt;:3000</pre><p>You should see <strong>only the Login page</strong> — the Sign Up option will be gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7DXPjfTim1toVyUPlyeig.png" /></figure><p>After this, only the Owner can add new users via <strong>Settings → Organization Members → Invite Member</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*osmnExVMd_t72mhoN6EzOA.png" /></figure><h3>12. Deployment in secured way</h3><pre>Internet<br>    │<br>    ▼ :443 (HTTPS)  [:80 → redirect to :443]<br>┌──────────────────────────────────────────────┐<br>│  Application Load Balancer (public subnets)  │<br>│  SG: allow 80/443 from internet              │<br>│  ACM certificate, health check: /api/public/health │<br>└──────────────────────────────────────────────┘<br>    │                              │<br>    ▼ Target group :3000           ▼ Target group :9090<br>                                   (host rule: media.example.com)<br>┌────────────────────────────────────────────────────────────────┐<br>│  EC2 instance (private subnet)                                 │<br>│  SG: allow 3000 and 9090 from the ALB SG only                  │<br>│                                                                │<br>│   langfuse-web :3000  ◄─────────────────────────────┐          │<br>│       │                                             │          │<br>│       ▼                                             │          │<br>│   langfuse-worker                                   │          │<br>│       │                                             │          │<br>│       ├──► PostgreSQL :5432  (metadata &amp; state)     │          │<br>│       ├──► Redis :6379       (queue &amp; caching)      │          │<br>│       ├──► ClickHouse :8123  (trace analytics)      │          │<br>│       └──► MinIO :9000       (blob/media storage) ──┘          │<br>│                 │                                              │<br>│                 ▼ :9090 (published port, reached via ALB only) │<br>└────────────────────────────────────────────────────────────────┘</pre><p><strong>Notes</strong></p><ul><li><strong>Only the ALB is public.</strong> The EC2 instance sits in a private subnet and its security group accepts traffic only from the ALB’s security group. PostgreSQL, Redis, ClickHouse and MinIO’s port 9000 stay internal to the Docker network and should not be published on the host.</li><li><strong>MinIO on :9090</strong> is only needed externally because browsers upload and download media using presigned URLs. Route it through the ALB with a host-based rule, such as media.example.com, and set LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT to that public URL. If you don’t need browser media uploads, you can drop the second target group.</li><li><strong>Set </strong><strong>NEXTAUTH_URL</strong> to the public ALB hostname (for example https://langfuse.example.com), or login redirects will break.</li><li><strong>Optional hardening for production:</strong> move PostgreSQL to RDS, Redis to ElastiCache, and blob storage to S3. The EC2 instance then only runs langfuse-web and langfuse-worker (plus ClickHouse).</li></ul><h3>13. Connect Your Application (Python Example)</h3><pre>pip install langfuse</pre><pre>import os<br>os.environ[&quot;LANGFUSE_PUBLIC_KEY&quot;] = &quot;pk-lf-your-public-key&quot;<br>os.environ[&quot;LANGFUSE_SECRET_KEY&quot;] = &quot;sk-lf-your-secret-key&quot;<br>os.environ[&quot;LANGFUSE_HOST&quot;] = &quot;http://&lt;your-ec2-public-ip&gt;:3000&quot;</pre><pre>from langfuse import observe, get_client<br>@observe()<br>def my_llm_function(prompt: str):<br>    # your LLM call here<br>    return &quot;response&quot;</pre><h3>14. Common Errors &amp; Fixes</h3><h3>Redis WRONGPASS Error</h3><pre>WRONGPASS invalid username-password pair or user is disabled</pre><p><strong>Fix:</strong> REDIS_AUTH in the worker environment and --requirepass in the redis service command must be identical.</p><pre>docker compose down -v   # clears old redis volume<br># fix passwords in docker-compose.yml<br>docker compose up -d</pre><h3>Blank Page at /langfuse subpath</h3><p><strong>Fix:</strong> Set NEXTAUTH_URL to the exact URL you&#39;re accessing, including the subpath if applicable. Use the custom base path guide if reverse proxying.</p><h3>Port 3000 Already in Use</h3><p><strong>Fix:</strong> Change the host port mapping in docker-compose.yml:</p><pre>ports:<br>  - &quot;3001:3000&quot;   # use 3001 instead</pre><h3>ClickHouse Worker Restart Loop on First Boot</h3><p>This is normal. ClickHouse takes 1+ minute on first boot for schema migrations. The worker will stabilize once ClickHouse is healthy.</p><h3>15. Maintenance</h3><h3>Upgrade Langfuse</h3><pre>docker compose down<br>docker compose up --pull always -d</pre><h3>Stop Langfuse</h3><pre>docker compose down          # stops containers, keeps data<br>docker compose down -v       # stops containers AND deletes all data</pre><h3>View Logs</h3><pre>docker compose logs -f                        # all containers<br>docker compose logs langfuse-web -f           # web only<br>docker compose logs langfuse-worker -f        # worker only</pre><h3>Backup PostgreSQL</h3><pre>docker exec langfuse-postgres-1 pg_dump -U postgres postgres &gt; langfuse_backup_$(date +%Y%m%d).sql</pre><h3>15. Architecture Overview</h3><pre>Internet<br>    │<br>    ▼ :3000<br>langfuse-web  ◄──────────────────────────────────┐<br>    │                                             │<br>    ▼                                             │<br>langfuse-worker                                  │<br>    │                                             │<br>    ├──► PostgreSQL :5432  (metadata &amp; state)     │<br>    ├──► Redis :6379       (queue &amp; caching)      │<br>    ├──► ClickHouse :8123  (trace analytics)      │<br>    └──► MinIO :9000       (blob/media storage) ──┘<br>              │<br>              ▼ :9090 (external access)<br>           Internet</pre><h3>Resources</h3><ul><li>Langfuse Docs: <a href="https://langfuse.com/docs">https://langfuse.com/docs</a></li><li>Self-Hosting Guide: <a href="https://langfuse.com/self-hosting">https://langfuse.com/self-hosting</a></li><li>Docker Compose Reference: <a href="https://langfuse.com/self-hosting/deployment/docker-compose">https://langfuse.com/self-hosting/deployment/docker-compose</a></li><li>GitHub: <a href="https://github.com/langfuse/langfuse">https://github.com/langfuse/langfuse</a></li><li>Troubleshooting: <a href="https://langfuse.com/self-hosting/troubleshooting-and-faq">https://langfuse.com/self-hosting/troubleshooting-and-faq</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c64a19b8cab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Pain? How We Fixed Async API Request Splitting Across Multiple EKS Pods]]></title>
            <link>https://medium.com/@nagulesh03/scaling-pain-how-we-fixed-async-api-request-splitting-across-multiple-eks-pods-df34e69e9cdf?source=rss-5c20ebe6a9c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/df34e69e9cdf</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nagulesh]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 19:11:21 GMT</pubDate>
            <atom:updated>2026-04-13T04:13:37.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftiNHyQbgcBl4svNCX3hMw.png" /></figure><h3>Introduction</h3><p>Kubernetes is powerful — but scaling your application from <strong>1 pod to multiple pods</strong> can sometimes introduce unexpected bugs that only appear under load. One of the most frustrating issues is when your <strong>async application works perfectly with a single pod</strong> but starts behaving erratically when you scale up.</p><p>In this blog, we’ll walk through:</p><ul><li>What the problem is</li><li>Why it happens</li><li>How we fixed it using ALB Ingress annotations in EKS</li><li>Alternative approaches to solve the same problem</li></ul><h3>The Problem: Async Requests Getting Split Across Pods</h3><h3>What We Observed</h3><pre>Single Pod  → Everything works perfectly<br>2+ Pods     → Requests are split, sessions break, async operations fail</pre><p>When running a <strong>single pod</strong>, all HTTP requests from the same client session go to the same instance. The async operations maintain their state correctly.</p><p>However, when we scaled to <strong>2 or more pods</strong>, the AWS Application Load Balancer (ALB) started distributing requests using its <strong>default round-robin algorithm</strong>. This meant:</p><pre>Client Request 1  → Pod 1 (Session Created Here)<br>Client Request 2  → Pod 2 (No Session Knowledge!)<br>Client Request 3  → Pod 1<br>Client Request 4  → Pod 3 ← Async callback lands here </pre><h3>Real-World Impact</h3><pre>Scenario Single          Pod          Multiple Pods<br>-------------------------------------------------<br>Async API Calls          Working      Broken <br>Session State            Maintained   Lost <br>WebSocket Connections    Stable       Disconnecting <br>Long-running Operations  Complete     Interrupted</pre><h3>Root Cause Analysis</h3><h3>The In-Memory State Problem</h3><p>The problem lies in how the application stores job state. Let’s examine the actual code from backend/api_server.py:</p><pre># api_server.py<br># In-memory job store (use Redis/DB in production)<br># Also stores temporary directories to keep them alive<br>JOBS = {}<br>TEMP_DIRS = {}</pre><p>This in-memory dictionary is the root cause of our multi-pod issues. Each pod maintains its own isolated JOBS dictionary in memory.</p><h3>The Request Flow That Causes 404 Errors</h3><h4>Step 1: Upload Metadata (Pod A)</h4><p>When you upload a PDF, the /api/v1/documents/upload-metadata endpoint performs these operations:</p><ol><li>Saves the file locally to ./input/ directory</li><li>Uploads to S3 (if configured)</li><li><strong>Stores job metadata in the in-memory JOBS dictionary</strong>:</li></ol><pre># api_server.py<br>JOBS[upload_id] = {<br>    &quot;status&quot;: &quot;uploaded&quot;,<br>    &quot;file_name&quot;: file.filename,<br>    &quot;file_path&quot;: str(file_path),<br>    &quot;s3_input_path&quot;: f&quot;input/{file.filename}&quot; if S3_BUCKET_NAME else None,<br>    &quot;file_size_mb&quot;: file_size_mb,<br>    &quot;total_pages&quot;: total_pages,<br>    &quot;created_at&quot;: datetime.now().isoformat(),<br>    &quot;selected_pages&quot;: None  # Will be set when user starts processing<br>}</pre><p>At this point, <strong>only Pod A</strong> has this job information in its memory.</p><h4>Step 2: Start Processing (Pod B)</h4><p>When the processing request arrives, the ALB might route it to a different pod. The /api/v1/documents/{upload_id}/process endpoint checks:</p><pre># api_server.py<br># Lines 1048-1049<br>if upload_id not in JOBS:<br>    raise HTTPException(status_code=404, detail=&quot;Upload not found&quot;)</pre><p><strong>Pod B’s JOBS dictionary is empty</strong> — it has no knowledge of the upload that happened on Pod A. Hence, the <strong>404 Not Found</strong> error.</p><h3>Visual Representation of the Problem</h3><pre>Upload Request (Step 1)<br>       |<br>       v<br>    Pod A Memory<br>    +---------------------------------+<br>    | JOBS = {                        |<br>    |   &quot;4311d13d...&quot;: {              |<br>    |     &quot;status&quot;: &quot;uploaded&quot;,       |<br>    |     &quot;file_name&quot;: &quot;doc.pdf&quot;,     |<br>    |     ...                         |<br>    |   }                             |<br>    | }                               |<br>    +---------------------------------+<br><br>Processing Request (Step 2)<br>       |<br>       v<br>    Pod B Memory<br>    +---------------------------------+<br>    | JOBS = {}   &lt;-- EMPTY!          |<br>    |                                 |<br>    | Result: 404 Not Found           |<br>    +---------------------------------+</pre><h3>Why This Happens</h3><p>Each pod has its own isolated memory space. The JOBS = {} dictionary is not shared between pods:</p><pre>Pod A Memory: JOBS = {&quot;4311d13d-1049-4596-b0c7-257faf4e9448&quot;: {...}}<br>Pod B Memory: JOBS = {}  &lt;-- Empty! No knowledge of the upload<br>Pod C Memory: JOBS = {}  &lt;-- Empty! No knowledge of the upload</pre><p><strong>Key Issue</strong>: Python dictionaries live in process memory. When you have multiple pods, you have multiple Python processes, each with its own separate memory space.</p><h3>Understanding Python’s Asynchronous Behavior</h3><h3>How Python Async Works (And Why It Breaks with Multiple Pods)</h3><p>Python’s async/await pattern is designed for <strong>concurrent operations within a single process</strong>, not distributed systems. Here’s what happens:</p><pre># Python Async Example - FastAPI<br>from fastapi import FastAPI, BackgroundTasks<br>import asyncio<br><br>app = FastAPI()<br># In-memory storage (THIS IS THE PROBLEM!)<br>async_operations = {}<br><br>@app.post(&quot;/api/start-processing&quot;)<br>async def start_processing(file_id: str, background_tasks: BackgroundTasks):<br>    operation_id = str(uuid.uuid4())<br>    # State stored in THIS pod&#39;s memory<br>    async_operations[operation_id] = {<br>        &quot;status&quot;: &quot;processing&quot;,<br>        &quot;file_id&quot;: file_id<br>    }<br>    background_tasks.add_task(process_file, operation_id, file_id)<br>    return {&quot;operation_id&quot;: operation_id}<br><br>@app.get(&quot;/api/status/{operation_id}&quot;)<br>async def check_status(operation_id: str):<br>    # This ONLY works if request hits the SAME pod<br>    if operation_id not in async_operations:<br>        return {&quot;error&quot;: &quot;Operation not found&quot;}<br>    return async_operations[operation_id]</pre><h3>The Multi-Pod Problem Visualized</h3><pre>                    CLIENT<br>                      |<br>                      v<br>              Kubernetes Service<br>                      |<br>                      v<br>                 AWS ALB (Round Robin)<br>                      |<br>        +-------------+-------------+<br>        v             v             v<br>     Pod 1         Pod 2         Pod 3</pre><pre>Request 1: POST /start-processing<br>        v<br>    Pod 1: operation_123, status: running (State stored HERE)</pre><pre>Request 2: GET /status/operation_123<br>                    v<br>    Pod 2: (empty memory) - Returns 404!</pre><p>The problem occurs because:</p><ol><li>Python stores async operation state in <strong>local pod memory</strong></li><li>Each pod has its <strong>own isolated memory space</strong></li><li>ALB distributes requests <strong>across all pods</strong></li><li>Status checks land on <strong>different pods</strong> without the operation data</li></ol><h3>Environment Setup</h3><pre>Cloud Provider  : AWS<br>Orchestration   : Amazon EKS (Elastic Kubernetes Service)<br>Load Balancer   : AWS Application Load Balancer (ALB)<br>Ingress         : AWS Load Balancer Controller<br>Application     : Async API (Node.js/Python/Java)<br>Pods            : 2+ Replicas</pre><h3>The Ingress Configuration (Before Fix)</h3><pre># ingress-before-fix.yaml<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: my-app-ingress<br>  namespace: production<br>  annotations:<br>    kubernetes.io/ingress.class: alb<br>    alb.ingress.kubernetes.io/scheme: internet-facing<br>    alb.ingress.kubernetes.io/target-type: ip<br>spec:<br>  rules:<br>    - host: api.myapp.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: my-app-service<br>                port:<br>                  number: 80</pre><p><strong>Problem:</strong> No sticky sessions configured. ALB distributes requests randomly across pods.</p><h3>The Fix: ALB Sticky Sessions + Header Validation</h3><h3>The Two Magic Annotations</h3><pre># The Fix - Two Critical Annotations<br>alb.ingress.kubernetes.io/target-group-attributes: |<br>  stickiness.enabled=true,<br>  stickiness.lb_cookie.duration_seconds=86400<br><br>alb.ingress.kubernetes.io/load-balancer-attributes: |<br>  routing.http.drop_invalid_header_fields.enabled=true</pre><h3>Complete Fixed Ingress Configuration</h3><pre># ingress-after-fix.yaml<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: my-app-ingress<br>  namespace: production<br>  annotations:<br>    # Basic ALB Configuration<br>    kubernetes.io/ingress.class: alb<br>    alb.ingress.kubernetes.io/scheme: internet-facing<br>    alb.ingress.kubernetes.io/target-type: ip<br><br>    # FIX 1: Enable Sticky Sessions (24 hours = 86400 seconds)<br>    alb.ingress.kubernetes.io/target-group-attributes: |<br>      stickiness.enabled=true,<br>      stickiness.lb_cookie.duration_seconds=86400<br><br>    # FIX 2: Drop Invalid Header Fields<br>    alb.ingress.kubernetes.io/load-balancer-attributes: |<br>      routing.http.drop_invalid_header_fields.enabled=true<br>spec:<br>  rules:<br>    - host: api.myapp.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: my-app-service<br>                port:<br>                  number: 80</pre><h3>Deep Dive: What Do These Annotations Actually Do?</h3><h3>Annotation 1: target-group-attributes - Sticky Sessions</h3><pre>stickiness.enabled=true<br>└── Enables session affinity on the ALB Target Group<br>    └── ALB creates a cookie: AWSALB<br>        └── Same client always routes to same pod</pre><pre>stickiness.lb_cookie.duration_seconds=86400<br>└── Cookie lives for 86400 seconds (24 hours)<br>    └── Client stays on same pod for 24 hours<br>        └── Async operations complete successfully</pre><p><strong>How ALB Sticky Sessions Work:</strong></p><pre>┌─────────────────────────────────────────────────────┐<br>│                    CLIENT                           │<br>│                                                     │<br>│  Request 1 ──────────────────────────────────────► │<br>│                         ALB                         │<br>│                    Sets Cookie:                     │<br>│                 AWSALB=pod1-token                   │<br>│                         │                          │<br>│                         ▼                          │<br>│  ┌─────────┐    ┌─────────────────────────────┐   │<br>│  │  Pod 1  │◄───│  All subsequent requests     │   │<br>│  │         │    │  from this client go to Pod 1│   │<br>│  └─────────┘    └─────────────────────────────┘   │<br>│  ┌─────────┐                                       │<br>│  │  Pod 2  │  ← Other clients route here           │<br>│  └─────────┘                                       │<br>│  ┌─────────┐                                       │<br>│  │  Pod 3  │  ← Other clients route here           │<br>│  └─────────┘                                       │<br>└─────────────────────────────────────────────────────┘</pre><h3>Annotation 2: load-balancer-attributes - Drop Invalid Headers</h3><pre>routing.http.drop_invalid_header_fields.enabled=true<br>└── Drops HTTP headers with invalid characters<br>    └── Prevents request smuggling attacks<br>        └── Ensures async callbacks are properly formatted<br>            └── Reduces malformed request errors</pre><h3>Before vs After Comparison</h3><pre>BEFORE FIX:<br>──────────────────────────────────────────────<br>Client ──► ALB ──► Service ──► Round Robin Distribution<br>                                ├──► Pod 1 (Request 1)<br>                                ├──► Pod 2 (Request 2)<br>                                └──► Pod 3 (Request 3) </pre><pre>AFTER FIX:<br>──────────────────────────────────────────────<br>Client ──► ALB ──► Sticky Session (Cookie)<br>                    └──► service ──► Pod 1 (All Requests)</pre><pre>Other Client ──► ALB ──► Sticky Session<br>                          └──► service ──► Pod 2 (All Requests)</pre><h3>Step-by-Step Implementation Guide</h3><h3>Step 1: Verify Your AWS Load Balancer Controller</h3><pre># Check if AWS Load Balancer Controller is installed<br>kubectl get deployment -n kube-system aws-load-balancer-controller<br># Expected Output:<br># NAME                           READY   UP-TO-DATE   AVAILABLE<br># aws-load-balancer-controller   2/2     2            2</pre><h3>Step 2: Check Current Ingress Configuration</h3><pre># View current ingress<br>kubectl get ingress -n production<br># Describe ingress for details<br>kubectl describe ingress my-app-ingress -n production</pre><h3>Step 3: Apply the Fixed Ingress</h3><pre># Apply the updated ingress configuration<br>kubectl apply -f ingress-after-fix.yaml<br># Verify the update<br>kubectl describe ingress my-app-ingress -n production</pre><h3>Step 4: Verify ALB Target Group Settings</h3><pre># Get the ALB ARN from ingress<br>kubectl get ingress my-app-ingress -n production -o jsonpath=&#39;{.metadata.annotations}&#39;<br><br># Check target group attributes via AWS CLI<br>aws elbv2 describe-target-group-attributes \\<br>  --target-group-arn &lt;your_target_group_arn&gt;<br># Expected Output:<br># {<br>#   &quot;Attributes&quot;: [<br>#     {<br>#       &quot;Key&quot;: &quot;stickiness.enabled&quot;,<br>#       &quot;Value&quot;: &quot;true&quot;<br>#     },<br>#     {<br>#       &quot;Key&quot;: &quot;stickiness.lb_cookie.duration_seconds&quot;,<br>#       &quot;Value&quot;: &quot;86400&quot;<br>#     }<br>#   ]<br># }</pre><h3>Step 5: Test the Fix</h3><pre># Test with curl - check for sticky session cookie<br>curl -v -c cookies.txt &lt;https://api.myapp.com/health&gt;<br><br># Second request should go to same pod<br>curl -v -b cookies.txt &lt;https://api.myapp.com/api/async-operation&gt;<br><br># Check the AWSALB cookie<br>cat cookies.txt | grep AWSALB</pre><h3>Alternative Methods to Fix This Issue</h3><h4>Alternative 1: Redis-Based Session Sharing (Recommended for Production)</h4><p><strong>Best for:</strong> Applications that need true horizontal scaling without session affinity</p><pre># redis-deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: redis-session-store<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: redis<br>  template:<br>    spec:<br>      containers:<br>      - name: redis<br>        image: redis:7-alpine<br>        ports:<br>        - containerPort: 6379<br>        resources:<br>          requests:<br>            memory: &quot;128Mi&quot;<br>            cpu: &quot;100m&quot;<br>          limits:<br>            memory: &quot;256Mi&quot;<br>            cpu: &quot;200m&quot;<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: redis-service<br>spec:<br>  selector:<br>    app: redis<br>  ports:<br>  - port: 6379</pre><pre>// Node.js Example - Connect-Redis<br>const session = require(&#39;express-session&#39;);<br>const RedisStore = require(&#39;connect-redis&#39;)(session);<br>const redis = require(&#39;redis&#39;);<br>const redisClient = redis.createClient({<br>  host: process.env.REDIS_HOST || &#39;redis-service&#39;,<br>  port: 6379<br>});<br>app.use(session({<br>  store: new RedisStore({ client: redisClient }),<br>  secret: process.env.SESSION_SECRET,<br>  resave: false,<br>  saveUninitialized: false,<br>  cookie: { secure: true, maxAge: 86400000 }<br>}));</pre><pre># Python/Flask Example<br>from flask import Flask<br>from flask_session import Session<br>import redis<br>app = Flask(__name__)<br>app.config[&#39;SESSION_TYPE&#39;] = &#39;redis&#39;<br>app.config[&#39;SESSION_REDIS&#39;] = redis.from_url(https://medium.com/%3Cbr%3E%20%20%20%20&#39;redis://redis-service:6379&#39;%3Cbr%3E)<br>Session(app)</pre><p><strong>Pros vs Cons:</strong></p><pre>Pros                                  Cons <br>True horizontal scaling            Additional Redis infrastructure <br>Pod restarts don&#39;t lose sessions   Redis becomes single point of failure <br>Better load distribution           Network latency for session reads <br>Production-grade solution          More complex setup</pre><h3>Alternative 2: Stateless Application Design (JWT Tokens)</h3><p><strong>Best for:</strong> Modern API applications that can be redesigned</p><pre>// JWT-based stateless async operations<br>const jwt = require(&#39;jsonwebtoken&#39;);<br>// Instead of storing state in pod memory<br>// Encode state in JWT token<br>app.post(&#39;/api/async-start&#39;, async (req, res) =&gt; {<br>  const operationId = generateUUID();<br>  // Store operation state in database, not pod memory<br>  await db.saveOperation({<br>    id: operationId,<br>    status: &#39;pending&#39;,<br>    userId: req.user.id<br>  });<br>  // Return token with operation reference<br>  const token = jwt.sign(<br>    { operationId, userId: req.user.id },<br>    process.env.JWT_SECRET,<br>    { expiresIn: &#39;24h&#39; }<br>  );<br>  res.json({ token, operationId });<br>});<br>// Any pod can handle the status check<br>app.get(&#39;/api/async-status/:operationId&#39;, async (req, res) =&gt; {<br>  // State is in database, not pod - any pod can respond<br>  const operation = await db.getOperation(req.params.operationId);<br>  res.json(operation);<br>});</pre><p><strong>Pros vs Cons:</strong></p><pre>Pros                               Cons <br>Truly stateless and scalable      Requires application redesign <br>No sticky session needed          State must live in external DB <br>Works with any load balancing     More complex async handling <br>Cloud-native approach             Higher development effort</pre><h3>Alternative 3: NLB (Network Load Balancer) with IP Hash</h3><p><strong>Best for:</strong> When you need consistent routing based on client IP</p><pre># ingress-nlb.yaml<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: my-app-ingress-nlb<br>  annotations:<br>    kubernetes.io/ingress.class: alb<br>    alb.ingress.kubernetes.io/scheme: internet-facing<br>    alb.ingress.kubernetes.io/target-type: ip<br>    # Use IP-based routing<br>    alb.ingress.kubernetes.io/load-balancer-attributes: &gt;<br>      routing.http.drop_invalid_header_fields.enabled=true<br>    # Alternative: Use least outstanding requests algorithm<br>    alb.ingress.kubernetes.io/target-group-attributes: &gt;<br>      load_balancing.algorithm.type=least_outstanding_requests,<br>      stickiness.enabled=true,<br>      stickiness.type=app_cookie,<br>      stickiness.app_cookie.cookie_name=MY_APP_SESSION,<br>      stickiness.app_cookie.duration_seconds=86400</pre><h3>Alternative 4: Application-Level Cookie Stickiness</h3><p><strong>Best for:</strong> When you want application-controlled session routing</p><pre># Using App Cookie instead of LB Cookie<br>alb.ingress.kubernetes.io/target-group-attributes: &gt;<br>  stickiness.enabled=true,<br>  stickiness.type=app_cookie,<br>  stickiness.app_cookie.cookie_name=JSESSIONID,<br>  stickiness.app_cookie.duration_seconds=86400</pre><pre>// Java Spring Boot - Set session cookie<br>@Configuration<br>public class SessionConfig {<br>    @Bean<br>    public HttpSessionIdResolver httpSessionIdResolver() {<br>        return CookieHttpSessionIdResolver.withCookieSerializer(<br>            new DefaultCookieSerializer() {{<br>                setCookieName(&quot;JSESSIONID&quot;);<br>                setCookiePath(&quot;/&quot;);<br>                setUseSecureCookie(true);<br>            }}<br>        );<br>    }<br>}</pre><h3>Alternative 5: Kubernetes Service with SessionAffinity</h3><p><strong>Best for:</strong> Simple setups without Ingress controller</p><pre># service-with-affinity.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: my-app-service<br>  namespace: production<br>spec:<br>  selector:<br>    app: my-app<br>  ports:<br>  - port: 80<br>    targetPort: 8080<br>  # Enable session affinity at Service level<br>  sessionAffinity: ClientIP<br>  sessionAffinityConfig:<br>    clientIP:<br>      timeoutSeconds: 86400  # 24 hours</pre><p><strong>⚠️ Warning:</strong> This uses client IP, which can cause uneven distribution with NAT/proxies.</p><h3>Alternative 6: Message Queue for Async Operations</h3><p><strong>Best for:</strong> Decoupling async operations completely</p><pre># Complete async decoupling with SQS/RabbitMQ<br>// Producer Pod - Any pod can create the job<br>app.post(&#39;/api/async-operation&#39;, async (req, res) =&gt; {<br>  const jobId = await messageQueue.publish({<br>    queue: &#39;async-jobs&#39;,<br>    message: {<br>      jobId: uuid(),<br>      userId: req.user.id,<br>      data: req.body<br>    }<br>  });<br>  res.json({ jobId, status: &#39;queued&#39; });<br>});<br>// Consumer - Dedicated worker pods<br>// Completely separate from API pods<br>// No routing issues!<br>messageQueue.consume(&#39;async-jobs&#39;, async (message) =&gt; {<br>  await processAsyncJob(message);<br>  await db.updateJobStatus(message.jobId, &#39;completed&#39;);<br>});<br>// Status check - Any pod can check DB<br>app.get(&#39;/api/job-status/:jobId&#39;, async (req, res) =&gt; {<br>  const status = await db.getJobStatus(req.params.jobId);<br>  res.json(status);<br>});</pre><h3>Comparison of All Solutions</h3><p>Method Complexity Cost Scalability Best For</p><p><strong>ALB Sticky Sessions:</strong> Low Free Medium Quick fix, existing apps</p><p><strong>Redis Session Store:</strong> Medium Low High Production apps</p><p><strong>JWT/Stateless:</strong> High Free Very High New app design</p><p><strong>NLB IP Hash:</strong> Low Low Medium IP-consistent routing</p><p><strong>App Cookie:</strong> Low Free Medium App-controlled sessions</p><p><strong>K8s SessionAffinity:</strong> Low Free Low Simple/internal apps</p><p><strong>Message Queue:</strong> High Medium Very High Async-heavy workloads</p><h3>Key Takeaways</h3><pre>1. Sticky Sessions = Quick Fix<br>   └── Use when you need immediate resolution<br>2. Redis Sessions = Production Grade<br>   └── Use when building scalable production systems<br>3. Stateless Design = Cloud Native<br>   └── Use when designing new applications<br>4. Message Queues = Async Champion<br>   └── Use when async operations are core to your app</pre><h3>Security Considerations</h3><pre># Always combine sticky sessions with security best practices<br>alb.ingress.kubernetes.io/load-balancer-attributes: &gt;<br>  routing.http.drop_invalid_header_fields.enabled=true,<br>  routing.http.desync_mitigation_mode=defensive,<br>  routing.http2.enabled=true<br>alb.ingress.kubernetes.io/target-group-attributes: &gt;<br>  stickiness.enabled=true,<br>  stickiness.lb_cookie.duration_seconds=86400<br># Additional security annotations<br>alb.ingress.kubernetes.io/ssl-redirect: &#39;443&#39;<br>alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-TLS13-1-2-2021-06</pre><h3>Resources</h3><ul><li><a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/guide/ingress/annotations/">AWS ALB Ingress Annotations</a></li><li><a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html">AWS Target Group Stickiness</a></li><li><a href="https://aws.github.io/aws-eks-best-practices/">EKS Best Practices</a></li><li><a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/">AWS Load Balancer Controller</a></li></ul><h3>Conclusion</h3><p>Scaling from 1 pod to multiple pods exposed a classic distributed systems challenge — <strong>session state management</strong>. The quick fix using ALB sticky sessions solved our immediate problem with just two annotations. However, for a truly scalable production system, consider migrating to <strong>Redis-based sessions</strong> or a <strong>stateless JWT approach</strong>.</p><blockquote><strong><em>Pro Tip:</em></strong><em> Start with sticky sessions as a quick fix, then plan your migration to a stateless architecture for long-term scalability.</em></blockquote><p><em>Have you faced similar issues with async applications in Kubernetes? Share your experience in the comments below!</em></p><p><strong>Tags:</strong> #EKS #Kubernetes #AWS #ALB #DevOps #CloudNative #K8s #LoadBalancing #SessionManagement</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df34e69e9cdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Lost code, Saved by Docker image”.]]></title>
            <link>https://medium.com/@nagulesh03/lost-code-saved-by-docker-image-649700a6a02f?source=rss-5c20ebe6a9c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/649700a6a02f</guid>
            <dc:creator><![CDATA[Nagulesh]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 18:02:32 GMT</pubDate>
            <atom:updated>2025-12-01T18:02:32.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Lost code, Saved by Docker image”. Get the Code files from the docker image from docker registry/AWS ECR</h3><h3>Problem background</h3><p>You usually edited code directly on your machine and rebuilt the Docker image frequently, but if you did not use Git correctly or consistently (few or no commits, no separate branches). One day you built a new image with incorrect changes, overwrote your working copy, and then realized you could not easily get back the previous version of the code because there was no reliable Git history to restore from.​</p><p>In that situation, the only reliable place where the old code still existed was inside a previously built working Docker image (or a running container based on that image). Because the image layers contained your application files, you could still recover the “lost” source by exploring the image and copying the code out.​</p><p><strong>Prerequisite : </strong><br>Make sure that you have installed the docker in you local system.</p><p>These solutions are provided only for the 2 possible registries:</p><ol><li>Docker Hub</li><li>AWS ECR</li></ol><h3>1. Docker registry (including Docker Hub):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*mDO0qkiDB_r_QBNn.png" /></figure><p><strong>Step 1 :</strong> Basic Docker Hub login (interactive):</p><pre>docker login</pre><p>Enter your Docker Hub username and password when prompted.</p><p>Login to a specific private registry:</p><pre>docker login registry.example.com</pre><p>Or with explicit username:</p><pre>docker login -u YOUR_USER registry.example.com.</pre><p><strong>Step 2 :</strong> Then Pull the docker image,</p><pre>docker pull &lt;dockerhub-username&gt;/&lt;repository&gt;:&lt;tag&gt;</pre><p>Example:</p><pre>docker pull nagulesh123/myapp:latest</pre><p><strong>Step 3 : </strong>creates a stopped container from the specified docker image without running it.</p><pre>docker create --name temp_container nagulesh123/myapp:latest</pre><p><strong>Step 4 :</strong> Copy Files Out of the Container</p><pre>docker cp temp_container:/app ./extracted_code</pre><blockquote>Here /app is just an example — the actual path depends on where your code was copied during the Dockerfile build (WORKDIR or COPY instruction).</blockquote><p><strong>Step 5 : </strong>Clean up the container</p><pre>docker rm temp_container</pre><h3>2. AWS ECR (private):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*8Yw-Q_yc7xfwnHve" /></figure><p><strong>Step 1 :</strong> AWS CLI configured (aws configure) and an ECR repository already created.​</p><p>Command pattern (Linux/macOS, AWS CLI v2):</p><pre>aws ecr get-login-password - region &lt;region&gt; | docker login - username AWS - password-stdin &lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com​</pre><p>Example:</p><pre>aws ecr get-login-password - region ap-south-1 | docker login - username AWS - password-stdin 123456789012.dkr.ecr.ap-south-1.amazonaws.com​</pre><p><strong>Step 2 :</strong> Then pull the ECR image ,</p><pre>docker pull &lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/&lt;repository-name&gt;:&lt;tag&gt;</pre><p>Example :</p><pre>docker pull 123456789012.dkr.ecr.ap-south-1.amazonaws.com/myapp:latest</pre><p><strong>Step 3 : </strong>creates a stopped container from the specified ECR image without running it.</p><pre>docker create --name temp_container &lt;account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/&lt;repository_name&gt;:&lt;tag&gt;</pre><p><strong>Step 4 :</strong> Copy Files Out of the Container</p><pre>docker cp temp_container:/app ./extracted_code</pre><blockquote>Here /app is just an example — the actual path depends on where your code was copied during the Dockerfile build (WORKDIR or COPY instruction).</blockquote><p><strong>Step 5 : </strong>Clean up the container</p><pre>docker rm temp_container</pre><h3>Closing thoughts</h3><p>This whole mistake started because the code was not properly backed up in Git and the only “backup” left was a Docker image. Turning that painful moment into a small rescue mission using docker cp and Docker/ECR registries is what this post walked through.​</p><p>Going forward, always keep your source in Git, treat Docker images as build artifacts (not version control), and push them to a registry like Docker Hub or ECR only after you are happy with the code. With that workflow in place, if something goes wrong again, you will have both clean images to run and a solid history of your code to roll back to.​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649700a6a02f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>