<?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 Machindranath Wagare on Medium]]></title>
        <description><![CDATA[Stories by Machindranath Wagare on Medium]]></description>
        <link>https://medium.com/@machindra220?source=rss-25ec73d0c597------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1OlVsDl4Un9yq_FRINu8xA.png</url>
            <title>Stories by Machindranath Wagare on Medium</title>
            <link>https://medium.com/@machindra220?source=rss-25ec73d0c597------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:09:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@machindra220/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[Why Every Service Deserves Its Own Monitor]]></title>
            <link>https://medium.com/@machindra220/why-every-service-deserves-its-own-monitor-7a0b416bb11b?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a0b416bb11b</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[cicd-pipeline]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[sre]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 09:44:43 GMT</pubDate>
            <atom:updated>2026-11-13T09:44:43.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Shared monitors hide failures, slow down incident response, and create false confidence. Per-service monitoring is not overhead — it is the minimum viable safety net for any production system.</p><h3>The Problem With Shared Monitors</h3><p>Most teams start with one monitor per environment. A single alert for “high error rate” watches everything. It seems efficient. It is not.</p><p>Shared monitors create three failure modes:</p><ol><li><strong>Alert fatigue.</strong> When a single monitor covers ten services, any one of them triggers the same alert. On-call engineers learn to dismiss it because “it’s probably that flaky service again.” The night a critical service starts burning, the alert fires — and nobody moves fast enough.</li><li><strong>Masked failures.</strong> A healthy service and a degraded one average out. If seven services have a 0.1% error rate and one has a 15% error rate, an aggregated monitor might sit quietly under its threshold the entire time the bad one is melting.</li><li><strong>Useless runbooks.</strong> A generic alert points to a generic runbook. The on-call engineer stares at it and starts from scratch every time, running the same kubectl get pods dance before they even know which service to look at.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIIxxeaxVI6KEJfl7hVWbg.jpeg" /></figure><h3>What Per-Service Monitoring Looks Like</h3><p>The screenshot above shows a well-structured monitor setup in Datadog. The [sre-demo-api] service has five dedicated monitors, each one answering a specific question:</p><p>MonitorPriorityWhat It CatchesAPI Availability — No TrafficP1Total silence: the service stopped receiving requestsHigh Error RateP2Elevated 5xx responses in the request pathHigh p99 LatencyP3Tail latency degrading user experiencePod Restart RateP2Kubernetes instability before it becomes an outageSLO Availability Burn RateP2Error budget burning faster than the target allows</p><p>Each monitor is tagged with service:sre-demo-api, env:dev, and a severity label. Those tags do real work: they route alerts to the right team, filter dashboards, feed SLO reports, and power auto-remediation scripts. A shared monitor cannot carry meaningful tags because it covers too many things at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnWFsSjlKcrPZk9QhpJ1DQ.jpeg" /></figure><h3>Reason 1: Blast Radius Isolation</h3><p>In a microservices architecture, failures are supposed to be contained. That is the entire point of the design. But if your monitoring is not equally decomposed, a single noisy service contaminates the signal for the whole fleet.</p><p>Per-service monitors preserve the blast radius contract at the observability layer. When payment-service has a problem, its monitors fire. auth-service monitors stay green. The on-call engineer looks at the alert, reads the service name, and already knows where to go. They are not diffing two services trying to figure out which one is the culprit.</p><p>This matters most during major incidents when multiple things break at once. With shared monitors, everything fires together and nothing tells you the order of events. With per-service monitors, the timeline of which service degraded first — and in what order others followed — is embedded in the alert history.</p><h3>Reason 2: Priority and Severity Are Service-Specific</h3><p>Not every service is P1. A batch job that runs nightly and processes non-urgent reports is not the same as the checkout API that processes live payments. Treating them identically in your monitoring system means you are either over-paging on the former or under-responding to the latter.</p><p>Look at the screenshot again. The API Availability monitor is P1. High Error Rate and Pod Restart Rate are P2. High p99 Latency is P3. These priority decisions are deliberate. They encode the team’s judgment about what actually matters and in what order.</p><p>A shared monitor forces you to pick the highest common denominator — everything becomes P1 — or the lowest, in which case real P1 events get missed. Per-service monitors let each service define what “critical” means for its own SLA. That is not a configuration detail. It is incident response policy expressed as code.</p><h3>Reason 3: Faster MTTD and MTTR</h3><p>Mean time to detect (MTTD) and mean time to resolve (MTTR) are the two numbers that matter most in incident response. Per-service monitors improve both directly.</p><p><strong>MTTD</strong> drops because the alert name contains the answer to the first question every on-call engineer asks: “Which service is this?” With a shared monitor, that question takes minutes to answer. With a named service monitor, it takes zero seconds — it is in the subject line.</p><p><strong>MTTR</strong> drops because per-service monitors link to service-specific runbooks, dashboards, and playbooks. The screenshot shows this pattern already embedded in the naming convention: [sre-demo-api] API Availability - No Traffic is an alert title that tells you the service, the monitor type, and the failure mode before you have opened a single terminal. That context, delivered at alert time, is the difference between a 4-minute and a 40-minute MTTR.</p><p>For a 10-service system, the cumulative savings compound. For a 200-service system, they are the difference between a functional on-call rotation and one that burns out in six months.</p><h3>Reason 4: Ownership and Accountability</h3><p>A monitor with no service name is a monitor nobody owns. When an alert fires and three teams are staring at the same Slack notification, everyone assumes someone else is handling it. This is not a cultural failure. It is a structural one. The monitoring setup made it ambiguous.</p><p>Per-service monitors make ownership explicit. When payment-service alerts fire, the payments team responds. When inventory-service alerts fire, the inventory team responds. The service name in the monitor is a contract, not a label.</p><p>This also matters for postmortems. A well-tagged per-service monitor tells you exactly who was paged, at what time, what they saw, and what they did. Shared monitors produce incident timelines full of “unclear who was responsible” entries, which is the most common root cause listed in postmortems that never actually improve anything.</p><p>Ownership at the monitor level reinforces ownership at the code level. Teams that maintain their own monitors develop sharper intuition for where their service breaks and why. That knowledge does not emerge from watching a shared monitor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBGZSkfURn9Wq7uitB7qzg.jpeg" /></figure><h3>Getting Started</h3><p>If your team is running shared monitors today, the migration is straightforward. You do not need to do it all at once.</p><ul><li>[ ] Pick your highest-traffic or highest-risk service and create its monitor set first. Five monitors covers most services: availability, error rate, latency (p99), resource pressure, and SLO burn rate.</li><li>[ ] Name every monitor [service-name] &lt;what it checks&gt;. The service name in brackets is searchable, filterable, and readable in a Slack notification at 3 AM.</li><li>[ ] Tag with service:, env:, and severity:. These three tags give you routing, filtering, and dashboard scoping for free.</li><li>[ ] Write a one-paragraph runbook per monitor before you ship it. It does not need to be perfect. It needs to exist.</li><li>[ ] Set priority deliberately. P1 means “wake someone up immediately.” If everything is P1, nothing is.</li><li>[ ] Roll out to the next service, then the next. Within a quarter, shared monitors become exceptions, not the norm.</li></ul><p>The screenshot at the top of this post is the end state: five monitors, one service, clean tags, explicit priorities, all green. Building that for each of your services is not a large project. It is a series of small ones, each of which pays off the first time it fires.</p><p>Monitoring is not a checkbox. It is the feedback loop that tells you whether your software is doing what you think it is doing. Per-service monitors are what makes that loop fast enough to be useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a0b416bb11b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SRE AI Agent: Every Real Error We Hit and How We Fixed It]]></title>
            <link>https://medium.com/@machindra220/sre-ai-agent-every-real-error-we-hit-and-how-we-fixed-it-ce84c3e9c0e8?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce84c3e9c0e8</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ai-automation]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 07:51:36 GMT</pubDate>
            <atom:updated>2026-11-03T07:51:36.045Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an AI-powered SRE agent on AWS EKS surfaced a long trail of real errors across Python, Kubernetes, AWS, and LLMs. This post documents every one: what broke, exactly why, and the precise fix. Use it as a troubleshooting reference.</p><p><strong>Stack:</strong> Python 3.12 . LangGraph . fastembed . pgvector . FastAPI . AWS EKS . Grafana Cloud (Prometheus + Loki) . chaoskube</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI_gkrAD_rST-Gu9EKdzcg.png" /><figcaption>5 Node LangGraph Pipeline</figcaption></figure><h3>1. Python &amp; Dependency Errors</h3><h3>Error 1.1 — psycopg2-binary fails to install on Python 3.14</h3><p><strong>Error message:</strong></p><pre>error: metadata-generation-failed<br>subprocess-exited-with-error: python setup.py egg_info</pre><p><strong>Why it happened:</strong> psycopg2-binary ships pre-compiled C extension wheels. Python 3.14 was so new that no compatible wheel existed on PyPI. pip fell back to building from source, which requires libpq-dev headers, and even then the build fails on 3.14 due to internal API changes.</p><p><strong>Fix:</strong> Always use Python 3.12 for this project.</p><pre># Check your Python version first<br>python3 --version</pre><pre># If on 3.14, install 3.12 alongside it<br>sudo apt-get install python3.12 python3.12-venv</pre><pre># Create the venv explicitly on 3.12<br>python3.12 -m venv .venv<br>source .venv/bin/activate</pre><pre># Now psycopg2-binary installs cleanly<br>pip install psycopg2-binary</pre><p><strong>Rule going forward:</strong> Pin Python in your README. python_requires=&#39;&gt;=3.12,&lt;3.14&#39; in setup.py, or a .python-version file if you use pyenv.</p><h3>Error 1.2 — fastembed downloads 130MB model on first run, no progress indicator</h3><p><strong>Symptom:</strong> The agent process hangs for 60–90 seconds on first startup with no output. Looks like a deadlock.</p><p><strong>Why it happened:</strong> fastembed downloads the BAAI/bge-small-en-v1.5 embedding model (~130MB) on first use and caches it in ~/.cache/fastembed. There is no progress bar by default.</p><p><strong>Fix:</strong> Pre-download the model before deploying, and add a log line so you know it is working:</p><pre>from fastembed import TextEmbedding<br>import logging</pre><pre>log = logging.getLogger(__name__)<br>log.info(&quot;Loading fastembed model (first run downloads ~130MB)...&quot;)<br>model = TextEmbedding(&quot;BAAI/bge-small-en-v1.5&quot;)<br>log.info(&quot;fastembed model ready&quot;)</pre><p>In Docker/EKS, pre-bake the cache into the image:</p><pre># In Dockerfile — run during build so download happens at build time, not runtime<br>RUN python -c &quot;from fastembed import TextEmbedding; TextEmbedding(&#39;BAAI/bge-small-en-v1.5&#39;)&quot;</pre><h3>Error 1.3 — pgvector ivfflat index fails for dimensions &gt; 2000</h3><p><strong>Error message:</strong></p><pre>ERROR: column cannot have more than 2000 dimensions for ivfflat index</pre><p><strong>Why it happened:</strong> pgvector’s ivfflat index type has a hard limit of 2000 dimensions. OpenAI’s text-embedding-ada-002 produces 1536-dim vectors (fine). But if you experiment with larger models like text-embedding-3-large (3072-dim) or any 4096-dim model, the index creation fails.</p><p><strong>Fix:</strong> Use fastembed BAAI/bge-small-en-v1.5 (384-dim) or another sub-2000 model. In init.sql:</p><pre>-- This works (384 dimensions)<br>CREATE TABLE runbook_chunks (<br>    id SERIAL PRIMARY KEY,<br>    content TEXT,<br>    embedding vector(384),  -- must match model output dim<br>    metadata JSONB<br>);</pre><pre>CREATE INDEX ON runbook_chunks<br>  USING ivfflat (embedding vector_cosine_ops)<br>  WITH (lists = 100);  -- only valid for &lt;= 2000 dims</pre><p>If you need higher dimensions, use hnsw instead (no dimension limit):</p><pre>CREATE INDEX ON runbook_chunks<br>  USING hnsw (embedding vector_cosine_ops);</pre><h3>2. LangGraph &amp; LLM Errors</h3><h3>Error 2.1 — chunk_text infinite loop hangs the indexer</h3><p><strong>Symptom:</strong> python rag/indexer.py hangs forever. CPU at 100% on one core. No output.</p><p><strong>Why it happened:</strong> The chunk_text function had a bug when CHUNK_OVERLAP &gt;= CHUNK_SIZE. The sliding window advance value became zero or negative, so the loop never moved forward:</p><pre># BROKEN - infinite loop when chunk_size &lt;= chunk_overlap<br>def chunk_text(text, chunk_size=800, chunk_overlap=100):<br>    chunks = []<br>    start = 0<br>    while start &lt; len(text):<br>        end = start + chunk_size<br>        chunks.append(text[start:end])<br>        start += chunk_size - chunk_overlap  # becomes 0 if overlap &gt;= size<br>    return chunks</pre><p><strong>Fix:</strong> Add an advance guard:</p><pre># FIXED - advance guard prevents infinite loop<br>def chunk_text(text, chunk_size=800, chunk_overlap=100):<br>    chunks = []<br>    start = 0<br>    while start &lt; len(text):<br>        end = start + chunk_size<br>        chunks.append(text[start:end])<br>        advance = chunk_size - chunk_overlap<br>        if advance &lt;= 0:          # guard: never get stuck<br>            advance = chunk_size<br>        start += advance<br>    return chunks</pre><p>The safe production values used in this project: CHUNK_SIZE=800, CHUNK_OVERLAP=100.</p><h3>Error 2.2 — Gemini model name raises NotFound / 404</h3><p><strong>Error message:</strong></p><pre>google.api_core.exceptions.NotFound: 404 models/gemini-pro is not found<br># or<br>google.api_core.exceptions.InvalidArgument: 400 model not found: gemini-2.5-flash</pre><p><strong>Why it happened:</strong> Google changes Gemini model IDs frequently. gemini-pro, gemini-1.5-pro, gemini-2.5-flash — names are versioned and some are deprecated or renamed without notice. What worked last month may 404 today.</p><p><strong>Fix:</strong> Always look up available models before hardcoding a name:</p><pre>import google.generativeai as genai</pre><pre>genai.configure(api_key=&quot;your-key&quot;)</pre><pre># List all models available to your key<br>for m in genai.list_models():<br>    if &#39;generateContent&#39; in m.supported_generation_methods:<br>        print(m.name)  # e.g. models/gemini-1.5-flash</pre><p>The working model for this project’s free tier: gemini-1.5-flash (1500 req/day free). In diagnoser.py:</p><pre>model = genai.GenerativeModel(&#39;gemini-1.5-flash&#39;)</pre><h3>Error 2.3 — Gemini rate limit: 429 Too Many Requests</h3><p><strong>Error message:</strong></p><pre>google.api_core.exceptions.ResourceExhausted: 429 Quota exceeded</pre><p><strong>Why it happened:</strong> The Gemini free tier allows 20 requests/day for some models (the eval suite alone used 6 per run). Running evals multiple times a day hit the ceiling.</p><p><strong>Fix options:</strong></p><ol><li>Switch to gemini-1.5-flash which has a higher free quota (1500 req/day)</li><li>Add exponential backoff:</li></ol><pre>import time<br>from google.api_core.exceptions import ResourceExhausted</pre><pre>def call_gemini_with_retry(model, prompt, max_retries=3):<br>    for attempt in range(max_retries):<br>        try:<br>            return model.generate_content(prompt)<br>        except ResourceExhausted as e:<br>            if attempt &lt; max_retries - 1:<br>                wait = 2 ** attempt  # 1s, 2s, 4s<br>                time.sleep(wait)<br>            else:<br>                raise</pre><ol><li>Cache LLM responses during eval runs to avoid re-calling for the same prompt.</li></ol><h3>Error 2.4 — LangGraph StateGraph node not receiving state fields</h3><p><strong>Symptom:</strong> A node receives the state but a field that a previous node wrote is None.</p><p><strong>Why it happened:</strong> LangGraph state fields must be declared in the TypedDict state class. If a node writes a new key that was not in the original TypedDict, LangGraph silently drops it — it doesn&#39;t carry forward to the next node.</p><p><strong>Fix:</strong> Declare every field a node may write in the state schema upfront:</p><pre>from typing import TypedDict, Optional</pre><pre>class SREAgentState(TypedDict):<br>    alert_data: dict<br>    pod_name: Optional[str]        # written by alert_parser<br>    pod_logs: Optional[str]        # written by log_fetcher<br>    runbook_context: Optional[str] # written by runbook_retriever<br>    diagnosis: Optional[str]       # written by diagnoser<br>    rca_id: Optional[str]          # written by rca_writer</pre><p>Every field that any node reads or writes must appear here.</p><h3>3. RBAC &amp; Kubernetes Errors</h3><h3>Error 3.1 — log_fetcher returns empty logs silently (pods/log RBAC missing)</h3><p><strong>Symptom:</strong> log_fetcher node runs without error, but pod_logs in state is an empty string. The dashboard shows no pod logs.</p><p><strong>Why it happened:</strong> Even from inside the cluster, accessing pod logs via the Kubernetes API requires explicit RBAC permission to the pods/log subresource. The ClusterRole only granted access to pods — not pods/log. The API server silently returns empty rather than 403 in some configurations.</p><p>The broken ClusterRole:</p><pre>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;pods&quot;]     # WRONG - this does not include pod logs<br>  verbs: [&quot;get&quot;, &quot;list&quot;]</pre><p><strong>Fix:</strong> Add pods/log as a separate resource:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: sre-agent-log-reader<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;pods&quot;]        # for pod metadata<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;pods/log&quot;]    # for actual log content - this is the one that was missing<br>  verbs: [&quot;get&quot;]<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: sre-agent-log-reader-binding<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: sre-agent-log-reader<br>subjects:<br>- kind: ServiceAccount<br>  name: default<br>  namespace: sre-ai-agent</pre><p>Apply with kubectl apply -f rbac.yaml. Verify it works:</p><pre># Test pod log access from inside cluster<br>kubectl auth can-i get pods/log -n sre-ai-agent --as=system:serviceaccount:sre-ai-agent:default<br># Should print: yes</pre><p><strong>Rule:</strong> pods and pods/log are two distinct resources in Kubernetes RBAC. Granting one does not grant the other.</p><h3>Error 3.2 — t3.small node hits 11-pod limit, pods pending</h3><p><strong>Symptom:</strong> New pods stay in Pending state. kubectl describe pod &lt;pod&gt; shows:</p><pre>Warning  FailedScheduling  0/3 nodes are available: 3 Too many pods</pre><p><strong>Why it happened:</strong> AWS t3.small supports a maximum of 11 pods per node (limited by the number of ENI secondary IPs). With 3 app_nodes each capped at 11, the total cluster pod limit is 33. System pods (kube-dns, aws-node, kube-proxy) consume ~5–6 per node, leaving ~5–6 for workloads per node.</p><p><strong>Fix options:</strong></p><ol><li><strong>Reduce system pod count</strong> by disabling unused add-ons</li><li><strong>Add more nodes</strong> to the node group</li><li><strong>Upgrade to t3.medium or larger</strong> (allows 17 pods per node)</li><li><strong>Use prefix delegation</strong> (VPC CNI feature that multiplies ENI capacity):</li></ol><pre># Enable prefix delegation on the VPC CNI<br>kubectl set env daemonset aws-node -n kube-system \<br>  ENABLE_PREFIX_DELEGATION=true</pre><pre># After enabling, nodes need to be cycled (rolling replacement)<br>exsctl upgrade nodegroup --name app_nodes --cluster my-cluster</pre><p>In this project the solution was staying on 4 nodes total (3 app + 1 agent) and being disciplined about workloads per node.</p><h3>Error 3.3 — MongoDB StatefulSet stuck Pending due to taint mismatch</h3><p><strong>Symptom:</strong> LitmusChaos MongoDB pod stays Pending with:</p><pre>Warning  FailedScheduling  0/4 nodes are available: 1 node(s) had taint {workload: ai-agent} that the pod did not tolerate</pre><p><strong>Why it happened:</strong> The agent_nodes node group was tainted with workload=ai-agent:NoSchedule. LitmusChaos&#39;s MongoDB StatefulSet was scheduled to run on any available node — but with only the agent node having capacity, and that node rejecting untolerated pods, there was nowhere to place it.</p><p><strong>Fix:</strong> Add the toleration to LitmusChaos’s MongoDB helm values:</p><pre># helm/litmus/values.yaml<br>mongodb:<br>  tolerations:<br>  - key: workload<br>    operator: Equal<br>    value: ai-agent<br>    effect: NoSchedule<br>  nodeSelector: {}</pre><p>Then reinstall with the values file:</p><pre>helm upgrade --install litmus litmuschaos/litmus \<br>  -n litmus \<br>  -f helm/litmus/values.yaml</pre><h3>Error 3.4 — Promtail DaemonSet pods not scheduling on tainted nodes</h3><p><strong>Symptom:</strong> Promtail pods run on app_nodes but not on agent_node. Logs from the agent namespace not shipped to Loki.</p><p><strong>Why it happened:</strong> DaemonSets schedule a pod on every node, but taint tolerations must be explicitly set. The default Promtail helm chart does not tolerate custom taints.</p><p><strong>Fix:</strong> Set a broad toleration in promtail-values.yaml:</p><pre># promtail-values.yaml<br>tolerations:<br>- operator: Exists   # tolerates ALL taints on any node</pre><p>This is the correct approach for DaemonSets that must run everywhere (log shippers, monitoring agents). The operator: Exists form tolerates any taint regardless of key/value.</p><h3>4. pgvector &amp; Database Errors</h3><h3>Error 4.1 — psycopg2-binary fails to install on Python 3.14</h3><p><strong>Symptom:</strong></p><pre>ERROR: Could not find a version that satisfies the requirement psycopg2-binary==2.9.9<br>ERROR: No matching distribution found for psycopg2-binary==2.9.9</pre><p>or at runtime:</p><pre>ImportError: /usr/local/lib/python3.14/site-packages/psycopg2/_psycopg.cpython-314...</pre><p><strong>Why it happened:</strong> psycopg2-binary ships pre-compiled C extensions. Wheels are published per Python version; as of mid-2025, no wheel exists for Python 3.14. Even if it installs from source, the C extension may not compile cleanly against newer CPython internals.</p><p><strong>Fix:</strong> Pin your Docker base image to Python 3.12:</p><pre># Dockerfile<br>FROM python:3.12-slim</pre><pre># psycopg2-binary 2.9.9 has a wheel for 3.12 on linux/amd64<br>RUN pip install psycopg2-binary==2.9.9</pre><p>Also pin in requirements.txt:</p><pre>psycopg2-binary==2.9.9</pre><p>Do not use psycopg2 (source build) in production containers — the build requires libpq-dev and gcc, adding ~200MB to the image.</p><h3>Error 4.2 — pgvector connection refused when running locally</h3><p><strong>Symptom:</strong> psycopg2.OperationalError: could not connect to server: Connection refused when running the indexing script locally against the pgvector container.</p><p><strong>Why it happened:</strong> Two root causes hit at different times:</p><ol><li>The pgvector Docker container was not running (forgotten after a reboot)</li><li>The DB_HOST env var was set to the in-cluster service name (postgres-service) which only resolves inside Kubernetes — not on localhost</li></ol><p><strong>Fix for local development:</strong></p><pre># Start the container<br>docker run -d \<br>  --name pgvector \<br>  -e POSTGRES_USER=sre_user \<br>  -e POSTGRES_PASSWORD=sre_pass \<br>  -e POSTGRES_DB=sre_db \<br>  -p 5432:5432 \<br>  pgvector/pgvector:pg17</pre><pre># Verify it is listening<br>docker ps | grep pgvector<br>psql -h localhost -U sre_user -d sre_db -c &#39;SELECT 1&#39;</pre><p>For local runs against the in-cluster Postgres on EKS:</p><pre># Port-forward the postgres pod<br>kubectl port-forward svc/postgres-service 5432:5432 -n sre-ai-agent &amp;</pre><pre># Then set DB_HOST=localhost in your local .env<br>export DB_HOST=localhost<br>export DB_PORT=5432</pre><h3>Error 4.3 — ivfflat index creation fails with &gt;2000 dimensions</h3><p><strong>Symptom:</strong></p><pre>ERROR: ivfflat index does not support vectors with more than 2000 dimensions</pre><p><strong>Why it happened:</strong> The ivfflat index algorithm in pgvector has a hard-coded 2000-dimension limit. If you choose an embedding model that produces vectors larger than 2000 dims (e.g., text-embedding-3-large at 3072 dims), index creation fails entirely.</p><p><strong>Fix Option A — Use a model under 2000 dims (what this project does):</strong></p><p>We use BAAI/bge-small-en-v1.5 via fastembed, which produces 384-dimensional vectors — well under the 2000 limit:</p><pre># embedder.py<br>from fastembed import TextEmbedding</pre><pre>model = TextEmbedding(model_name=&quot;BAAI/bge-small-en-v1.5&quot;)  # 384 dims</pre><pre>-- Create ivfflat index on 384-dim column<br>CREATE INDEX ON runbook_chunks<br>USING ivfflat (embedding vector_cosine_ops)<br>WITH (lists = 100);</pre><p><strong>Fix Option B — Switch to hnsw (no dimension limit):</strong></p><pre>CREATE INDEX ON runbook_chunks<br>USING hnsw (embedding vector_cosine_ops)<br>WITH (m = 16, ef_construction = 64);</pre><p>hnsw is generally faster at query time but uses more memory and takes longer to build. For this project&#39;s scale (&lt; 10k chunks), either works; we chose ivfflat + 384-dim model.</p><h3>Error 4.4 — Runbook indexing produces zero vectors (silent failure)</h3><p><strong>Symptom:</strong> Script completes without error, but SELECT COUNT(*) FROM runbook_chunks; returns 0.</p><p><strong>Why it happened:</strong> The runbook .md files were being read from the wrong path. The indexing script used a relative path ./runbooks/ which resolved correctly in local dev but failed silently inside the container (no such directory = no files = no chunks = no inserts).</p><p><strong>Fix:</strong> Use an absolute path via an env var:</p><pre># indexer.py<br>import os</pre><pre>RUNBOOK_DIR = os.getenv(&quot;RUNBOOK_DIR&quot;, &quot;/app/runbooks&quot;)</pre><pre>def index_runbooks():<br>    files = list(Path(RUNBOOK_DIR).glob(&quot;*.md&quot;))<br>    if not files:<br>        print(f&quot;[WARN] No .md files found in {RUNBOOK_DIR}&quot;)<br>        return<br>    print(f&quot;[INFO] Indexing {len(files)} runbooks from {RUNBOOK_DIR}&quot;)<br>    ...</pre><p>And in Dockerfile:</p><pre>COPY runbooks/ /app/runbooks/<br>ENV RUNBOOK_DIR=/app/runbooks</pre><p>Always add a count log after indexing so silent failures surface immediately.</p><h3>5. Observability Stack Errors</h3><h3>Error 5.1 — Prometheus port conflict (9090 already in use)</h3><p><strong>Symptom:</strong> Prometheus pod in CrashLoopBackOff. Logs show:</p><pre>level=error ts=... caller=main.go msg=&quot;Opening storage failed&quot; err=&quot;lock DB directory: ...&quot;</pre><p>or port-forward fails:</p><pre>error: unable to forward port because pod is not running</pre><p><strong>Why it happened:</strong> Multiple Prometheus instances were deployed across namespaces (one for the app stack, one that came with LitmusChaos), and port-forward 9090 was already bound on the local machine from a previous session.</p><p><strong>Fix:</strong></p><pre># Check what is using 9090 locally<br>lsof -i :9090<br># Kill the stale port-forward<br>kill &lt;PID&gt;</pre><pre># Always use different local ports for different forwards<br>kubectl port-forward svc/prometheus-kube-prometheus-prometheus 9091:9090 -n monitoring &amp;<br>kubectl port-forward svc/prometheus-operated 9092:9090 -n litmus &amp;</pre><p>For Alertmanager (which defaults to 9093), use 9094 locally if 9093 is taken:</p><pre>kubectl port-forward svc/alertmanager-operated 9094:9093 -n monitoring &amp;</pre><h3>Error 5.2 — LOKI_USER_ID must be a number, not a stack name</h3><p><strong>Symptom:</strong> Promtail pods in Error state. Logs:</p><pre>level=error msg=&quot;error sending batch&quot; error=&quot;server returned HTTP status 401 Unauthorized&quot;</pre><p>Or Loki queries returning no data despite logs being shipped.</p><p><strong>Why it happened:</strong> Grafana Cloud’s Loki endpoint uses a numeric User ID (shown in the Loki data source connection details page as a 7-digit number like 1234567). When setting up Promtail, the stack name (scarletcanary2090) was used instead of the numeric ID.</p><p><strong>Fix:</strong> In Promtail’s promtail-values.yaml, the tenantId and basic auth username must be the numeric Loki User ID:</p><pre># promtail-values.yaml<br>config:<br>  clients:<br>  - url: https://logs-prod-ap-south-1.grafana.net/loki/api/v1/push<br>    tenant_id: &quot;1234567&quot;      # Numeric Loki User ID, NOT the stack name<br>    basic_auth:<br>      username: &quot;1234567&quot;     # Same numeric ID<br>      password_from_secret:<br>        name: loki-secret<br>        key: password</pre><p>To find your numeric Loki User ID:</p><ol><li>Go to Grafana Cloud → your stack → Loki</li><li>Click <strong>“Details”</strong> or <strong>“Send Logs”</strong></li><li>The User field shows the numeric ID (e.g., 1234567)</li></ol><h3>Error 5.3 — Promtail not scraping logs from all namespaces</h3><p><strong>Symptom:</strong> Grafana shows logs only from some pods/namespaces; logs from sre-ai-agent and chaos-testing are missing.</p><p><strong>Why it happened:</strong> Promtail’s pipelineStages and scrapeConfigs were only targeting the default and monitoring namespaces. The additional namespaces (sre-ai-agent, chaos-testing, litmus) were not listed.</p><p><strong>Fix:</strong> Update promtail-values.yaml to scrape all required namespaces:</p><pre>config:<br>  snippets:<br>    pipelineStages:<br>    - cri: {}<br>    scrapeConfigs: |<br>      - job_name: kubernetes-pods<br>        kubernetes_sd_configs:<br>        - role: pod<br>          namespaces:<br>            names:<br>            - default<br>            - monitoring<br>            - sre-ai-agent<br>            - chaos-testing<br>            - litmus<br>        relabel_configs:<br>        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]<br>          action: keep<br>          regex: true<br>        - source_labels: [__meta_kubernetes_namespace]<br>          target_label: namespace<br>        - source_labels: [__meta_kubernetes_pod_name]<br>          target_label: pod</pre><p>Then upgrade:</p><pre>helm upgrade promtail grafana/promtail -n monitoring -f promtail-values.yaml</pre><h3>Error 5.4 — fastembed hangs for 60–90 seconds on first run</h3><p><strong>Symptom:</strong> The SRE agent pod is healthy but the first request takes over a minute. Kubernetes liveness probe times out and kills the pod.</p><p><strong>Why it happened:</strong> fastembed downloads the BAAI/bge-small-en-v1.5 model (~130MB) from HuggingFace on first use. This download happens at runtime inside the container if the model is not pre-cached.</p><p><strong>Fix:</strong> Pre-bake the model download into the Docker image:</p><pre># Dockerfile<br>FROM python:3.12-slim</pre><pre>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt</pre><pre># Pre-download fastembed model during build (not at runtime)<br>RUN python -c &quot;<br>from fastembed import TextEmbedding<br>print(&#39;[BUILD] Downloading fastembed model...&#39;)<br>model = TextEmbedding(model_name=&#39;BAAI/bge-small-en-v1.5&#39;)<br>print(&#39;[BUILD] Model cached successfully&#39;)<br>&quot;</pre><pre>COPY . .<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>Also add a startup log in your app so you can confirm the model loads from cache:</p><pre>import time<br>start = time.time()<br>model = TextEmbedding(model_name=&quot;BAAI/bge-small-en-v1.5&quot;)<br>print(f&quot;[INFO] fastembed model loaded in {time.time()-start:.1f}s&quot;)<br># With pre-bake: ~0.3s. Without: 60-90s.</pre><p>And increase the Kubernetes startup probe to tolerate even a cache miss:</p><pre>startupProbe:<br>  httpGet:<br>    path: /health<br>    port: 8000<br>  failureThreshold: 30<br>  periodSeconds: 5   # allows up to 150s startup</pre><h3>6. AWS Infrastructure Errors</h3><h3>Error 6.1 — LitmusChaos MongoDB PVC stuck in WaitForFirstConsumer</h3><p><strong>Symptom:</strong> LitmusChaos installs but MongoDB StatefulSet pod stays Pending. kubectl describe pvc shows:</p><pre>Waiting for a volume to be created either by the external provisioner &#39;ebs.csi.aws.com&#39;<br>or for a volume bound manually...<br>WaitForFirstConsumer</pre><p><strong>Why it happened:</strong> The gp2 StorageClass on EKS uses volumeBindingMode: WaitForFirstConsumer, which means the PVC won&#39;t bind until a pod is scheduled. But the EBS CSI driver was not installed, so no provisioner could fulfill the request. The pod stays Pending forever.</p><p><strong>Fix Step 1 — Install the EBS CSI driver add-on:</strong></p><pre># Check if EBS CSI is installed<br>kubectl get pods -n kube-system | grep ebs-csi</pre><pre># Install via eksctl<br>eksctl create addon \<br>  --name aws-ebs-csi-driver \<br>  --cluster &lt;your-cluster-name&gt; \<br>  --region ap-south-1 \<br>  --force</pre><pre># Or via AWS console:<br># EKS → Clusters → your cluster → Add-ons → Get more add-ons → Amazon EBS CSI Driver</pre><p><strong>Fix Step 2 — Attach the required IAM policy to the node group role:</strong></p><pre># The EBS CSI driver needs this managed policy<br>aws iam attach-role-policy \<br>  --role-name &lt;NodeGroupRoleName&gt; \<br>  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy</pre><p>After installing the add-on, existing PVCs may need to be deleted and recreated, or the pod deleted so it reschedules and triggers the PVC binding.</p><h3>Error 6.2 — .terraform directory accidentally committed to git (twice)</h3><p><strong>Symptom:</strong> git status shows a huge diff with thousands of provider binary files. git push is either very slow or rejected for size limits.</p><p><strong>Why it happened:</strong> .gitignore was not set up before terraform init was run. The .terraform/ directory (containing provider plugins, ~50-200MB) was added to the repository by a blanket git add ..</p><p><strong>Fix — Remove it from git history:</strong></p><pre># Remove from index without deleting locally<br>git rm -r --cached .terraform/<br>git rm -r --cached .terraform.lock.hcl  # optional, usually safe to commit</pre><pre># Add to .gitignore immediately<br>cat &gt;&gt; .gitignore &lt;&lt; &#39;EOF&#39;<br>.terraform/<br>*.tfstate<br>*.tfstate.backup<br>.terraform.tfvars<br>EOF</pre><pre>git add .gitignore<br>git commit -m &quot;Remove .terraform from tracking, add to .gitignore&quot;</pre><p>If it was pushed to remote and you need to fully purge it (caution: rewrites history):</p><pre>git filter-branch --force --index-filter \<br>  &#39;git rm -r --cached --ignore-unmatch .terraform/&#39; \<br>  --prune-empty --tag-name-filter cat -- --all<br>git push origin --force --all</pre><p>For future safety, always run terraform init only after .gitignore is in place.</p><h3>Error 6.3 — EKS cluster migration us-east-1 → ap-south-1 breaks kubeconfig</h3><p><strong>Symptom:</strong> After recreating the cluster in ap-south-1, kubectl get nodes fails:</p><pre>Unable to connect to the server: dial tcp: lookup &lt;old-endpoint&gt;.us-east-1.eks.amazonaws.com: no such host</pre><p><strong>Why it happened:</strong> The kubeconfig still pointed to the old us-east-1 endpoint. The context was not updated after cluster recreation.</p><p><strong>Fix:</strong> Update kubeconfig for the new cluster:</p><pre>aws eks update-kubeconfig \<br>  --name &lt;cluster-name&gt; \<br>  --region ap-south-1</pre><pre># Verify<br>kubectl config current-context<br>kubectl get nodes</pre><p>Also update any hard-coded region references in Terraform variables:</p><pre># terraform/variables.tf<br>variable &quot;region&quot; {<br>  default = &quot;ap-south-1&quot;   # was us-east-1<br>}</pre><h3>Error 6.4 — LitmusChaos chaos experiments not targeting correct pods (toleration/selector mismatch)</h3><p><strong>Symptom:</strong> ChaosEngine runs but kubectl describe chaosresult shows Verdict: Awaited then times out. The target pod is never found.</p><p><strong>Why it happened:</strong> The ChaosEngine spec had appLabel pointing to a label that did not match the deployed pods, and the chaos runner pod could not schedule on the tainted agent node (missing toleration).</p><p><strong>Fix:</strong> Match the chaos engine spec to your actual pod labels and add tolerations:</p><pre>apiVersion: litmuschaos.io/v1alpha1<br>kind: ChaosEngine<br>metadata:<br>  name: pod-delete-engine<br>  namespace: chaos-testing<br>spec:<br>  appinfo:<br>    appns: sre-ai-agent<br>    applabel: &quot;app=sre-agent&quot;     # must match actual pod label<br>    appkind: deployment<br>  experiments:<br>  - name: pod-delete<br>    spec:<br>      components:<br>        runner:<br>          tolerations:<br>          - key: workload<br>            operator: Equal<br>            value: ai-agent<br>            effect: NoSchedule</pre><p>Verify your pod labels first:</p><pre>kubectl get pods -n sre-ai-agent --show-labels</pre><h3>7. DNS &amp; Networking Errors</h3><h3>Error 7.1 — Two duplicate Route53 hosted zones causing NS mismatch</h3><p><strong>Symptom:</strong> HTTPS endpoint returns NXDOMAIN or certificate errors. dig shows the wrong nameservers:</p><pre>dig NS myapp.example.com<br># Returns NS records from zone Z03766052D7VJCPILHC1A<br># But domain registrar delegates to Z0853158MC1FIFCWWDEB</pre><p><strong>Why it happened:</strong> Terraform created a hosted zone. Separately, a manual create in the AWS console created a second hosted zone for the same domain. Route53 happily hosts two zones with the same name — but DNS queries only hit one (whichever nameservers the registrar delegates to). The A/CNAME records were added to the wrong zone.</p><p><strong>How to diagnose:</strong></p><pre># List all zones for the domain<br>aws route53 list-hosted-zones-by-name \<br>  --dns-name myapp.example.com \<br>  --query &#39;HostedZones[*].{Id:Id,Name:Name,RecordCount:Config}&#39;</pre><pre># Check which zone the registrar points to<br>whois myapp.example.com | grep -i &#39;name server&#39;<br># Compare against the NS records in each zone:<br>aws route53 list-resource-record-sets \<br>  --hosted-zone-id Z0853158MC1FIFCWWDEB \<br>  --query &quot;ResourceRecordSets[?Type==&#39;NS&#39;]&quot;</pre><p><strong>Fix:</strong></p><ol><li>Identify the zone the registrar’s NS records match</li><li>Ensure all DNS records (A, CNAME, TXT for cert validation) are in THAT zone</li><li>Delete the duplicate zone</li></ol><pre># Delete all records in the wrong zone first (can&#39;t delete non-empty zone)<br>aws route53 change-resource-record-sets \<br>  --hosted-zone-id &lt;WRONG-ZONE-ID&gt; \<br>  --change-batch &#39;{&quot;Changes&quot;: [{&quot;Action&quot;: &quot;DELETE&quot;, ...}]}&#39;</pre><pre># Then delete the zone<br>aws route53 delete-hosted-zone --id &lt;WRONG-ZONE-ID&gt;</pre><p>If the zone was created by Terraform, remove it from state and let Terraform manage only one:</p><pre>terraform state rm aws_route53_zone.duplicate</pre><h3>Error 7.2 — WSL DNS resets to 8.8.8.8 after wsl — shutdown</h3><p><strong>Symptom:</strong> After wsl --shutdown and restart, DNS stops resolving internal or custom domains. ping myapp.example.com fails with Temporary failure in name resolution.</p><p><strong>Why it happened:</strong> WSL2 auto-generates /etc/resolv.conf on startup, overwriting any manual changes with the Windows host&#39;s DNS (often 8.8.8.8 in corporate environments that block external DNS queries for internal domains).</p><p><strong>Fix:</strong> Disable auto-generation and set a persistent nameserver:</p><pre># 1. Disable WSL auto-generating resolv.conf<br>sudo tee /etc/wsl.conf &lt;&lt; &#39;EOF&#39;<br>[network]<br>generateResolvConf = false<br>EOF</pre><pre># 2. Remove the existing symlink (WSL uses a symlink to a generated file)<br>sudo unlink /etc/resolv.conf</pre><pre># 3. Write a persistent resolv.conf<br>sudo tee /etc/resolv.conf &lt;&lt; &#39;EOF&#39;<br>nameserver 8.8.8.8<br>nameserver 8.8.4.4<br>EOF</pre><pre># 4. Make it immutable so WSL can&#39;t overwrite it<br>sudo chattr +i /etc/resolv.conf</pre><p>After wsl --shutdown and restart, the file persists.</p><p>To undo the immutability:</p><pre>sudo chattr -i /etc/resolv.conf</pre><h3>Error 7.3 — EKS pod DNS resolution failing inside cluster</h3><p><strong>Symptom:</strong> Pod can reach external IPs but cannot resolve Kubernetes service names:</p><pre>nslookup postgres-service.sre-ai-agent.svc.cluster.local<br>;; connection timed out; no servers could be reached</pre><p><strong>Why it happened:</strong> CoreDNS pods were running but one was crash-looping due to a ConfigMap edit gone wrong. Because Kubernetes service DNS relies on CoreDNS, internal names stopped resolving.</p><p><strong>Fix:</strong></p><pre># Check CoreDNS pods<br>kubectl get pods -n kube-system -l k8s-app=kube-dns</pre><pre># Check CoreDNS logs<br>kubectl logs -n kube-system -l k8s-app=kube-dns</pre><pre># If ConfigMap was edited incorrectly, reset to default<br>kubectl edit configmap coredns -n kube-system<br># Ensure the &#39;forward . /etc/resolv.conf&#39; line is present under &#39;forward&#39;</pre><pre># Restart CoreDNS pods<br>kubectl rollout restart deployment coredns -n kube-system</pre><pre># Verify from a debug pod<br>kubectl run dnstest --image=busybox --rm -it --restart=Never -- \<br>  nslookup postgres-service.sre-ai-agent.svc.cluster.local</pre><h3>8. Namespace Teardown &amp; EKS Cleanup Errors</h3><h3>Error 8.1 — Namespace stuck in Terminating forever</h3><p><strong>Symptom:</strong> kubectl delete namespace litmus hangs. kubectl get ns litmus shows:</p><pre>NAME     STATUS        AGE<br>litmus   Terminating   47m</pre><p>kubectl get all -n litmus returns nothing — resources appear deleted, but the namespace won&#39;t close.</p><p><strong>Why it happened:</strong> The namespace has a finalizer registered by the LitmusChaos operator or the AWS Load Balancer Controller. When those controllers were deleted before the namespace, nothing remained to process the finalizer and remove it. Kubernetes holds the namespace open indefinitely waiting for a controller that no longer exists.</p><p><strong>Diagnosis:</strong></p><pre># Check which finalizers are blocking<br>kubectl get ns litmus -o json | jq &#39;.spec.finalizers&#39;<br># e.g. [&quot;kubernetes&quot;]</pre><pre># Check for sub-resources with their own finalizers<br>kubectl api-resources --verbs=list --namespaced -o name | \<br>  xargs -I{} kubectl get {} -n litmus --ignore-not-found 2&gt;/dev/null</pre><p><strong>Fix — Force-finalize via the raw API:</strong></p><pre># Export the namespace spec<br>kubectl get ns litmus -o json &gt; /tmp/litmus.json</pre><pre># Remove finalizers from the spec<br>jq &#39;.spec.finalizers = []&#39; /tmp/litmus.json &gt; /tmp/litmus-fix.json</pre><pre># Submit via the finalize subresource (bypasses normal controller path)<br>kubectl replace --raw &quot;/api/v1/namespaces/litmus/finalize&quot; \<br>  -f /tmp/litmus-fix.json</pre><pre># Confirm namespace is gone<br>kubectl get ns litmus<br># Error from server (NotFound): namespaces &quot;litmus&quot; not found</pre><h3>Error 8.2 — AWS Load Balancer Controller finalizers orphan NLBs</h3><p><strong>Symptom:</strong> After deleting the aws-load-balancer-controller Helm release, NLB LoadBalancer services remain:</p><pre>kubectl get svc -A | grep LoadBalancer<br># Still shows services with EXTERNAL-IP and finalizers</pre><p>Services can’t be deleted:</p><pre>Error: unable to delete service: unable to remove finalizer: ...<br>elbv2.k8s.aws/resources, service.k8s.aws/resources</pre><p><strong>Why it happened:</strong> The AWS LB Controller writes finalizers onto Service objects it manages. When the controller is deleted first, nothing processes the finalizer removal. The services (and the NLBs in AWS) remain.</p><p><strong>Fix — Patch finalizers off the services:</strong></p><pre># List all services with LB finalizers<br>kubectl get svc -A -o json | \<br>  jq &#39;.items[] | select(.metadata.finalizers != null) | \<br>  {ns: .metadata.namespace, name: .metadata.name, fin: .metadata.finalizers}&#39;</pre><pre># Patch each stuck service<br>kubectl patch svc &lt;service-name&gt; -n &lt;namespace&gt; \<br>  -p &#39;{&quot;metadata&quot;:{&quot;finalizers&quot;:null}}&#39;</pre><pre># Then delete the service<br>kubectl delete svc &lt;service-name&gt; -n &lt;namespace&gt;</pre><p>Also manually delete the orphaned NLBs in AWS:</p><pre>aws elbv2 describe-load-balancers \<br>  --query &#39;LoadBalancers[?State.Code==`active`].{Name:LoadBalancerName,ARN:LoadBalancerArn}&#39; \<br>  --output table</pre><pre>aws elbv2 delete-load-balancer --load-balancer-arn &lt;ARN&gt;</pre><h3>Error 8.3 — CloudFormation DELETE_FAILED: dependency violation</h3><p><strong>Symptom:</strong> terraform destroy completes but EKS cluster CloudFormation stacks show DELETE_FAILED:</p><pre>AWS::CloudFormation::Stack eks-cluster DELETE_FAILED<br>&quot;Resource handler returned message: Dependency Violation: The network interface<br>&#39;eni-xxxx&#39; has a pending attachment&quot;</pre><p><strong>Why it happened:</strong> Two orphaned NLBs kept their ENIs attached to the VPC subnets. CloudFormation cannot delete the subnet or VPC while those ENIs exist. The NLBs were created by Kubernetes Service objects managed by the LB Controller but were not cleaned up before the cluster was deleted.</p><p><strong>Fix sequence:</strong></p><pre># 1. Find and delete the orphaned NLBs (see Error 8.2 above)<br>aws elbv2 describe-load-balancers --output table<br>aws elbv2 delete-load-balancer --load-balancer-arn &lt;ARN&gt;</pre><pre># 2. Wait for NLBs to fully deregister (2-3 minutes)<br>aws elbv2 describe-load-balancers --load-balancer-arns &lt;ARN&gt;<br># Wait until this returns empty</pre><pre># 3. Find any remaining ENIs in the VPC<br>aws ec2 describe-network-interfaces \<br>  --filters &quot;Name=vpc-id,Values=&lt;VPC-ID&gt;&quot; \<br>  --query &#39;NetworkInterfaces[*].{ID:NetworkInterfaceId,Status:Status,Desc:Description}&#39;</pre><pre># 4. Detach and delete non-ela-attach ENIs manually<br># (ela-attach ENIs are AWS-managed and cannot be deleted — they release automatically)<br>aws ec2 detach-network-interface --attachment-id &lt;AttachmentId&gt;<br>aws ec2 delete-network-interface --network-interface-id &lt;ENI-ID&gt;</pre><pre># 5. Retry the CloudFormation stack deletion<br>aws cloudformation delete-stack --stack-name &lt;stack-name&gt;</pre><p><strong>Note on ela-attach ENIs:</strong> ENIs with description starting ELB ela-attach/ are managed by the EKS control plane and cannot be manually deleted. They are released automatically when the CloudFormation stack deletion proceeds. Do not attempt to force-delete them.</p><h3>Error 8.4 — Complete EKS teardown order (what to do and when)</h3><p>Order matters. Reverse the install order:</p><pre># 1. Delete chaos experiments and engines first<br>kubectl delete chaosengine --all -n chaos-testing<br>kubectl delete chaosexperiment --all -n chaos-testing</pre><pre># 2. Uninstall LitmusChaos (removes CRDs and the operator)<br>helm uninstall litmus -n litmus</pre><pre># 3. Delete LoadBalancer services BEFORE removing LB Controller<br>kubectl delete svc -A -l &#39;service.kubernetes.io/type=LoadBalancer&#39;<br># Wait for NLBs to be deregistered by the controller (~2 min)</pre><pre># 4. Uninstall AWS Load Balancer Controller<br>helm uninstall aws-load-balancer-controller -n kube-system</pre><pre># 5. Delete all application namespaces<br>kubectl delete ns sre-ai-agent chaos-testing litmus monitoring</pre><pre># 6. Now run terraform destroy<br>terraform destroy -auto-approve</pre><pre># 7. If CloudFormation stacks remain stuck, check for orphaned NLBs<br># and follow Error 8.3 fix above</pre><h3>Error 8.5 — PVCs block namespace deletion during terraform destroy</h3><p><strong>Symptom:</strong> kubectl delete ns litmus hangs, or PVCs stay Terminating long after the Helm release is gone:</p><pre>kubectl get pvc -n litmus<br>NAME              STATUS        VOLUME  ...<br>mongodb-data-0    Terminating   ...</pre><p>The backing EBS volume stays as an unattached volume in AWS (still billing you).</p><p><strong>Why it happened:</strong> PVCs backed by EBS have a finalizer kubernetes.io/pvc-protection that prevents deletion until the consuming pod is fully terminated. If you delete the Helm release or the namespace without first scaling down the StatefulSet, the PVC enters Terminating but can never finish — the controller that owns the pod termination signal (LitmusChaos operator) is already gone.</p><p><strong>Fix:</strong> Scale down StatefulSets first, then delete PVCs explicitly:</p><pre># 1. Scale down MongoDB to 0 replicas<br>kubectl scale statefulset mongodb -n litmus --replicas=0<br>kubectl wait --for=delete pod/mongodb-0 -n litmus --timeout=60s</pre><pre># 2. Delete PVCs explicitly BEFORE uninstalling Helm or deleting namespace<br>kubectl delete pvc --all -n litmus<br>sleep 30   # wait for EBS to detach from node</pre><pre># 3. Now safe to delete namespace<br>kubectl delete ns litmus</pre><p>This sequence is now codified in infra-down.sh — PVC deletion happens before Helm uninstall and before namespace deletion.</p><h3>Error 8.6 — EBS CSI add-on deletion fails / blocks terraform destroy</h3><p><strong>Symptom:</strong> terraform destroy errors out:</p><pre>Error: error deleting EKS Add-On (my-cluster:aws-ebs-csi-driver):<br>Conflict: Addon is currently being updated</pre><p>Or the add-on simply remains attached and orphaned after the cluster is gone, leaving IAM roles dangling.</p><p><strong>Why it happened:</strong> The EBS CSI driver was installed via eksctl create addon (not Terraform), so Terraform had no record of it in state. Terraform destroys the cluster without cleaning up the add-on first, which can either conflict or leave orphaned IAM resources.</p><p><strong>Fix:</strong> Delete the add-on and its IAM service account manually before terraform destroy:</p><pre># Delete the EBS CSI add-on<br>exsctl delete addon \<br>  --name aws-ebs-csi-driver \<br>  --cluster $CLUSTER_NAME \<br>  --region ap-south-1</pre><pre># Delete the associated IAM service account (created by eksctl)<br>exsctl delete iamserviceaccount \<br>  --name ebs-csi-controller-sa \<br>  --namespace kube-system \<br>  --cluster $CLUSTER_NAME \<br>  --region ap-south-1</pre><pre># Now terraform destroy is clean<br>terraform destroy -auto-approve</pre><p>This is now step 1 in infra-down.sh, before any namespace or Helm operations.</p><h3>Error 8.7 — gp2 StorageClass not default — LitmusChaos MongoDB PVC never binds</h3><p><strong>Symptom:</strong> After installing LitmusChaos on a fresh EKS cluster, MongoDB PVC stays in Pending:</p><pre>kubectl describe pvc mongodb-data-0 -n litmus<br>Events:<br>  Normal  WaitForFirstConsumer  ...<br>  Warning  ProvisioningFailed    no default StorageClass found</pre><p><strong>Why it happened:</strong> EKS ships with a gp2 StorageClass but it is <strong>not</strong> set as the default. LitmusChaos&#39;s MongoDB chart requests the cluster&#39;s default StorageClass (empty storageClassName). Without a default, no StorageClass is selected and the PVC is never provisioned.</p><p>Even after setting gp2 as default, volumeBindingMode: WaitForFirstConsumer means the PVC only binds once a pod is scheduled. Without the EBS CSI driver installed, the provisioner isn&#39;t present and binding never happens regardless.</p><p><strong>Fix:</strong> Both conditions must be true before installing LitmusChaos:</p><pre># Step 1: Set gp2 as the default StorageClass<br>kubectl patch storageclass gp2 \<br>  -p &#39;{&quot;metadata&quot;:{&quot;annotations&quot;:{&quot;storageclass.kubernetes.io/is-default-class&quot;:&quot;true&quot;}}}&#39;</pre><pre># Verify<br>kubectl get sc<br># NAME            PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE<br># gp2 (default)   kubernetes.io/aws-ebs   Delete          WaitForFirstConsumer</pre><pre># Step 2: Ensure EBS CSI driver is installed (see Error 6.1)<br>exsctl create addon --name aws-ebs-csi-driver \<br>  --cluster $CLUSTER_NAME --region ap-south-1 --force</pre><pre># Step 3: Delete existing broken PVC and re-install LitmusChaos<br>kubectl delete pvc --all -n litmus<br>helm upgrade --install litmus litmuschaos/litmus \<br>  -n litmus -f helm/litmus/values.yaml</pre><p>Both of these steps are now baked into infra-up.sh and run before the LitmusChaos Helm install.</p><h3>infra-down.sh — Final Correct Teardown Order</h3><p>After hitting all of the above, the working teardown order is:</p><pre>#!/bin/bash<br># infra-down.sh<br>set -e</pre><pre># 0. Variables<br>CLUSTER_NAME=&quot;sre-ai-cluster&quot;<br>AWS_REGION=&quot;ap-south-1&quot;</pre><pre># 1. Delete chaos resources first<br>kubectl delete chaosengine --all -A 2&gt;/dev/null || true<br>kubectl delete chaosexperiment --all -A 2&gt;/dev/null || true</pre><pre># 2. Scale down StatefulSets so PVCs can be cleanly deleted<br>kubectl scale statefulset --all -n litmus --replicas=0 2&gt;/dev/null || true<br>kubectl wait pod --for=delete -l app.kubernetes.io/name=mongodb \<br>  -n litmus --timeout=60s 2&gt;/dev/null || true</pre><pre># 3. Delete PVCs explicitly BEFORE helm uninstall or namespace delete<br>kubectl delete pvc --all -n litmus 2&gt;/dev/null || true<br>echo &quot;Waiting 20s for EBS volumes to detach...&quot;<br>sleep 20</pre><pre># 4. Delete LoadBalancer services BEFORE removing LB Controller<br>#    (lets the controller deprovision the NLBs cleanly)<br>for NS in sre-ai-agent sre-ai-agent-llm monitoring; do<br>  kubectl delete svc -n $NS --field-selector spec.type=LoadBalancer 2&gt;/dev/null || true<br>done<br>echo &quot;Waiting 90s for NLBs to deregister from AWS...&quot;<br>sleep 90</pre><pre># 5. Uninstall Helm releases<br>helm uninstall litmus -n litmus 2&gt;/dev/null || true<br>helm uninstall aws-load-balancer-controller -n kube-system 2&gt;/dev/null || true<br>helm uninstall kube-prometheus-stack -n monitoring 2&gt;/dev/null || true<br>helm uninstall promtail -n monitoring 2&gt;/dev/null || true<br>helm uninstall chaoskube -n chaos 2&gt;/dev/null || true</pre><pre># 6. Delete all application namespaces<br>kubectl delete ns litmus sre-ai-agent sre-ai-agent-llm chaos-testing monitoring 2&gt;/dev/null || true</pre><pre># 7. Delete EBS CSI add-on and IAM service account<br>exsctl delete addon --name aws-ebs-csi-driver \<br>  --cluster $CLUSTER_NAME --region $AWS_REGION 2&gt;/dev/null || true<br>exsctl delete iamserviceaccount --name ebs-csi-controller-sa \<br>  --namespace kube-system --cluster $CLUSTER_NAME --region $AWS_REGION 2&gt;/dev/null || true</pre><pre># 8. Terraform destroy<br>pushd infrastructure/terraform<br>terraform destroy -auto-approve<br>popd</pre><pre># 9. Post-destroy sanity checks<br>echo &quot;&quot;<br>echo &quot;=== POST-DESTROY CHECKS ===&quot;<br>echo &quot;Orphaned NLBs (should be empty):&quot;<br>aws elbv2 describe-load-balancers \<br>  --query &#39;LoadBalancers[*].{Name:LoadBalancerName,State:State.Code}&#39; \<br>  --output table<br>echo &quot;Unattached EBS volumes (should be empty):&quot;<br>aws ec2 describe-volumes \<br>  --filters Name=status,Values=available \<br>  --query &#39;Volumes[*].{ID:VolumeId,Size:Size,AZ:AvailabilityZone}&#39; \<br>  --output table<br>echo &quot;CloudFormation stacks still active:&quot;<br>aws cloudformation list-stacks \<br>  --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE \<br>  --query &#39;StackSummaries[*].{Name:StackName,Status:StackStatus}&#39; \<br>  --output table</pre><h3>9. Dashboard &amp; Frontend Errors</h3><h3>Error 9.1 — Logs section silently shows nothing (duplicate DOM IDs)</h3><p><strong>Symptom:</strong> The dashboard loads, all pods display, metrics show — but clicking “View Logs” on any pod shows an empty modal. No error in the browser console. The logs API endpoint returns data when tested with curl.</p><p><strong>Why it happened:</strong> The dashboard generated multiple pod cards, each containing a &lt;div id=&quot;logsBox-N&quot;&gt; element. When JavaScript called document.getElementById(&quot;logsBox-1&quot;), the browser returned the first element with that ID in the DOM — which happened to be on a card that was scrolled off-screen and not the one the user clicked. The logs were being injected into the wrong (hidden) element.</p><p>Duplicate IDs violate the HTML spec: getElementById is only guaranteed to work correctly when IDs are unique per document.</p><p><strong>Fix:</strong> Use unique IDs that include both index and context, and scope modal elements differently:</p><pre>// Before (broken): duplicate IDs when multiple pods rendered<br>function renderPodCard(pod, index) {<br>  return `<br>    &lt;div class=&quot;pod-card&quot;&gt;<br>      &lt;div id=&quot;logsBox-${index}&quot;&gt;...&lt;/div&gt;  &lt;!-- WRONG: reused per row --&gt;<br>      &lt;button onclick=&quot;showLogs(${index})&quot;&gt;View Logs&lt;/button&gt;<br>    &lt;/div&gt;<br>  `;<br>}</pre><pre>// After (fixed): separate IDs for inline box vs modal<br>function renderPodCard(pod, index) {<br>  return `<br>    &lt;div class=&quot;pod-card&quot;&gt;<br>      &lt;div id=&quot;inlineLogsBox-${index}&quot;&gt;...&lt;/div&gt;   &lt;!-- unique --&gt;<br>      &lt;button onclick=&quot;showLogsModal(${index})&quot;&gt;View Logs&lt;/button&gt;<br>    &lt;/div&gt;<br>  `;<br>}</pre><pre>// Modal uses its own ID, separate from pod cards<br>function showLogsModal(index) {<br>  const modal = document.getElementById(&#39;modalLogsBox&#39;);  // single modal<br>  const content = document.getElementById(`inlineLogsBox-${index}`);<br>  modal.innerHTML = content ? content.innerHTML : &#39;Loading...&#39;;<br>  modal.style.display = &#39;block&#39;;<br>}</pre><p><strong>Key rule:</strong> In any dynamically rendered list, every element that JavaScript accesses by ID must have a globally unique ID. The safest pattern: use data-* attributes and querySelector with context, rather than getElementById in loops:</p><pre>// Even safer: no IDs in the list at all<br>document.querySelectorAll(&#39;[data-pod-index=&quot;3&quot;] .logs-box&#39;)</pre><h3>Error 9.2 — Dashboard showing stale data after agent completes RCA</h3><p><strong>Symptom:</strong> The dashboard shows an old RCA result even after the agent has written a new one. Refreshing the page clears the issue.</p><p><strong>Why it happened:</strong> The dashboard cached the /api/rca response in a JavaScript variable on page load and did not re-fetch when a new analysis arrived. The EventSource (SSE) stream updated the status indicator but not the RCA text panel.</p><p><strong>Fix:</strong> Fetch RCA data on every SSE event rather than caching it:</p><pre>// Connect to SSE for live updates<br>const evtSource = new EventSource(&#39;/api/stream&#39;);</pre><pre>evtSource.onmessage = function(e) {<br>  const data = JSON.parse(e.data);<br>  updateStatus(data.status);<br>  <br>  // Re-fetch RCA on every new event, not just once<br>  if (data.status === &#39;complete&#39; || data.rca_updated) {<br>    fetch(&#39;/api/rca&#39;)<br>      .then(r =&gt; r.json())<br>      .then(rca =&gt; {<br>        document.getElementById(&#39;rcaPanel&#39;).textContent = rca.summary;<br>      });<br>  }<br>};</pre><h3>10. Quick-Reference Error Index</h3><p>Every error in one table. Find the symptom, jump to the section for the full fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TPAeFv6ZuuSPj2YG6Jaiw.png" /><figcaption>Quick-Reference Error Index</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce84c3e9c0e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Force-Finalizing Stuck Kubernetes Namespaces on AWS EKS]]></title>
            <link>https://medium.com/@machindra220/force-finalizing-stuck-kubernetes-namespaces-on-aws-eks-ac343f0985c1?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac343f0985c1</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ai-automation]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 19:02:57 GMT</pubDate>
            <atom:updated>2026-11-02T19:02:57.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Your EKS cluster teardown is stuck. kubectl delete ns my-namespace has been running for 10 minutes. The namespace shows Terminating and refuses to go away. This guide explains why it happens, what force-finalize actually does, and how to fully clean up an AWS EKS cluster — from stuck namespaces to orphaned VPCs.</p><h3>What Is a Finalizer?</h3><p>A <strong>finalizer</strong> is a metadata string on a Kubernetes object that acts as a <strong>deletion gate</strong>. Kubernetes will not permanently delete an object until every finalizer on it has been removed.</p><p>Think of it like a checklist that must be cleared before checkout:</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: my-app<br>  finalizers:<br>  - kubernetes                          # built-in namespace finalizer<br>  - elbv2.k8s.aws/resources             # AWS Load Balancer Controller<br>  - service.k8s.aws/resources           # AWS Service Controller</pre><p>The namespace above has three finalizers. Kubernetes will hold the object in Terminating state until all three are removed. Each finalizer is &quot;owned&quot; by a controller — a piece of software running in the cluster that watches for objects being deleted and performs cleanup before removing the finalizer string.</p><p><strong>Why do finalizers exist?</strong></p><p>They prevent orphaned cloud resources. When you delete a Kubernetes Service of type LoadBalancer, the AWS Load Balancer Controller needs to delete the actual AWS Network Load Balancer first. The finalizer ensures the NLB is gone before Kubernetes cleans up its own records. Without finalizers, you&#39;d have dangling AWS resources with no way to find which cluster created them.</p><p><strong>Common finalizers you’ll encounter on AWS EKS:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghP_Sx79_jeA4-ooiW7B_w.png" /></figure><h3>The Kubernetes Deletion Lifecycle</h3><p>When you run kubectl delete ns my-namespace, here is exactly what happens:</p><ol><li><strong>kubectl sends a DELETE request</strong> to the Kubernetes API server for the namespace object.</li><li><strong>API server sets </strong><strong>deletionTimestamp</strong> on the object — a timestamp marking when deletion was requested. The object is now in Terminating state.</li><li><strong>API server does NOT delete the object yet.</strong> It checks for finalizers. If any exist, it waits.</li><li><strong>Each owning controller sees the </strong><strong>deletionTimestamp</strong> and starts its cleanup work (deleting the AWS NLB, removing target groups, etc.).</li><li><strong>Each controller removes its own finalizer</strong> from the object’s metadata once cleanup is done.</li><li><strong>Once all finalizers are removed</strong>, the API server permanently deletes the object from etcd.</li></ol><pre>kubectl delete ns  →  deletionTimestamp set  →  controllers clean up<br>                                                        ↓<br>                       object deleted from etcd  ←  finalizers all removed</pre><p>The critical point: <strong>the object exists in etcd as long as any finalizer remains</strong>. If a controller crashes, is deleted, or its cleanup fails, that finalizer stays on the object forever. The namespace is stuck Terminating indefinitely — and there is no timeout built into Kubernetes for this.</p><p><strong>What </strong><strong>kubectl get ns looks like when stuck:</strong></p><pre>$ kubectl get ns<br>NAME               STATUS        AGE<br>default            Active        8h<br>kube-system        Active        8h<br>my-namespace       Terminating   47m   # stuck here</pre><p>The AGE keeps climbing. The namespace will never delete on its own.</p><h3>Why Namespaces Get Stuck on AWS EKS</h3><p>The root cause is always the same: <strong>a finalizer remains on an object, but the controller that owns it no longer exists to remove it.</strong></p><p>This happens most often during cluster teardown when you delete controllers before cleaning up the resources they manage.</p><p><strong>The most common AWS EKS scenario: AWS Load Balancer Controller</strong></p><p>If you installed the AWS Load Balancer Controller to manage NLBs and ALBs, it attaches finalizers to resources like TargetGroupBinding:</p><pre>$ kubectl get targetgroupbindings -n my-namespace -o yaml<br>apiVersion: elbv2.k8s.aws/v1beta1<br>kind: TargetGroupBinding<br>metadata:<br>  finalizers:<br>  - elbv2.k8s.aws/resources    # &lt;-- owned by AWS LB Controller<br>  - service.k8s.aws/resources  # &lt;-- also AWS LB Controller</pre><p>If you then delete the AWS Load Balancer Controller (for example, by helm uninstall aws-load-balancer-controller) <strong>before</strong> deleting your Service objects, you get:</p><ul><li>The TargetGroupBinding still has those finalizers</li><li>The controller that would remove them is gone</li><li>The namespace cannot finish terminating</li><li>The namespace is stuck forever</li></ul><p><strong>Other common causes on EKS:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCRiHd1Rne8io-EnDVZjQw.png" /></figure><p><strong>The diagnostic command:</strong></p><pre># See what&#39;s blocking namespace deletion<br>kubectl get namespace my-namespace -o json | \<br>  jq &#39;.status.conditions[] | select(.type==&quot;NamespaceContentRemaining&quot;)&#39;</pre><p>Output tells you exactly what’s left inside the namespace — pods, services, custom resources — and which finalizers are blocking them.</p><h3>What Force-Finalize Actually Does</h3><p>Force-finalize is <strong>not a kubectl command</strong> — it’s a pattern: you manually patch an object to remove all its finalizers, bypassing the controller-based cleanup process entirely.</p><p>The command for a namespace looks like this:</p><pre>kubectl get namespace my-namespace -o json \<br>  | jq &#39;del(.spec.finalizers[])&#39; \<br>  | kubectl replace --raw &quot;/api/v1/namespaces/my-namespace/finalize&quot; -f -</pre><p><strong>What each part does:</strong></p><ul><li>kubectl get namespace my-namespace -o json — fetch the namespace as JSON</li><li>jq &#39;del(.spec.finalizers[])&#39; — remove all entries from the spec.finalizers array (sets it to [])</li><li>kubectl replace --raw &quot;/api/v1/namespaces/my-namespace/finalize&quot; -f - — send the modified object directly to the namespace finalize endpoint</li></ul><p><strong>The finalize endpoint</strong> (/api/v1/namespaces/&lt;name&gt;/finalize) is a special Kubernetes API endpoint that <strong>only</strong> updates spec.finalizers — it ignores everything else in the payload. Writing an empty array to it tells Kubernetes: &quot;all finalizers are satisfied.&quot;</p><p>Once Kubernetes sees spec.finalizers: [], it removes the deletionTimestamp block from etcd and permanently deletes the namespace object.</p><p><strong>Critical distinction:</strong> Force-finalize tells Kubernetes the cleanup is done. It does <strong>not</strong> actually do the cleanup. If the AWS Load Balancer Controller was supposed to delete an NLB before removing its finalizer, and you force-finalize instead, <strong>the NLB still exists in AWS</strong> — it just has no Kubernetes record attached to it. You now have an orphaned cloud resource that will keep billing you until you find and delete it manually.</p><blockquote><strong><em>Force-finalize is a last resort, not a first step.</em></strong><em> Use it only when the controller is already gone and cannot do its own cleanup.</em></blockquote><h3>Step-by-Step: How to Force-Finalize a Stuck Namespace</h3><h3>Step 1 — Confirm the namespace is stuck</h3><pre>kubectl get ns | grep Terminating<br># sre-ai-agent   Terminating   23m</pre><h3>Step 2 — Find out what’s blocking it</h3><pre>kubectl get namespace sre-ai-agent -o json | \<br>  jq &#39;.status.conditions&#39;</pre><p>Look for NamespaceContentRemaining or NamespaceFinalizersRemaining. The message field tells you what objects are left and which finalizers are holding them.</p><h3>Step 3 — Try to delete the blocking objects first</h3><p>Before force-finalizing, try to delete the stuck resources normally:</p><pre># List all resources in the namespace<br>kubectl api-resources --verbs=list --namespaced -o name | \<br>  xargs -I{} kubectl get {} -n sre-ai-agent 2&gt;/dev/null</pre><pre># If you see TargetGroupBindings or similar:<br>kubectl delete targetgroupbinding --all -n sre-ai-agent</pre><pre># Force-delete stuck pods:<br>kubectl delete pods --all -n sre-ai-agent --force --grace-period=0</pre><h3>Step 4 — Patch finalizers off individual objects (if needed)</h3><p>If a specific resource has orphaned finalizers, patch them directly:</p><pre># Patch a TargetGroupBinding to remove its finalizers<br>kubectl patch targetgroupbinding &lt;name&gt; -n sre-ai-agent \<br>  --type=json \<br>  -p=&#39;[{&quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: &quot;/metadata/finalizers&quot;}]&#39;</pre><pre># Or use merge patch:<br>kubectl patch targetgroupbinding &lt;name&gt; -n sre-ai-agent \<br>  --type=merge \<br>  -p=&#39;{&quot;metadata&quot;:{&quot;finalizers&quot;:null}}&#39;</pre><h3>Step 5 — Force-finalize the namespace</h3><p>Once the blocking resources are cleared (or if the namespace itself has orphaned finalizers):</p><pre>kubectl get namespace sre-ai-agent -o json \<br>  | jq &#39;del(.spec.finalizers[])&#39; \<br>  | kubectl replace --raw &quot;/api/v1/namespaces/sre-ai-agent/finalize&quot; -f -</pre><p>If successful, you’ll see the full namespace JSON returned. Then confirm it’s gone:</p><pre>kubectl get ns sre-ai-agent<br># Error from server (NotFound): namespaces &quot;sre-ai-agent&quot; not found</pre><p><strong>That “NotFound” is exactly what you want.</strong> The namespace is deleted.</p><h3>Step 6 — Check for orphaned AWS resources</h3><p>After force-finalizing, always verify that cloud resources were actually cleaned up:</p><pre># Check for orphaned NLBs<br>aws elbv2 describe-load-balancers \<br>  --query &#39;LoadBalancers[?contains(LoadBalancerName, `my-cluster`)].{Name:LoadBalancerName,ARN:LoadBalancerArn,State:State.Code}&#39;</pre><pre># Check for orphaned target groups<br>aws elbv2 describe-target-groups \<br>  --query &#39;TargetGroups[?contains(TargetGroupName, `my-cluster`)].TargetGroupName&#39;</pre><p>Delete anything that remains before tearing down the VPC.</p><h3>The AWS-Specific Problem: Load Balancers, ENIs, and VPCs</h3><p>Force-finalizing the Kubernetes namespace is only half the battle on AWS EKS. The real pain comes after — when CloudFormation fails to delete the VPC because AWS resources created by Kubernetes are still alive.</p><h3>Network Load Balancers (NLBs) block VPC deletion</h3><p>Every Service of type LoadBalancer creates an AWS NLB. When you force-finalize the namespace, Kubernetes drops its records but the NLB still exists in AWS. NLBs attach to your VPC subnets via ENI (Elastic Network Interface) attachments. CloudFormation cannot delete the subnet while an ENI is attached to it — and it cannot delete the VPC while the subnet exists.</p><p>Result: eksctl delete cluster finishes, but CloudFormation is stuck in DELETE_FAILED:</p><pre>SubnetPublicAPSOUTH1A    DELETE_FAILED   DependencyViolation<br>SubnetPublicAPSOUTH1B    DELETE_FAILED   DependencyViolation<br>VPCGatewayAttachment     DELETE_FAILED   DependencyViolation</pre><p><strong>How to find orphaned NLBs:</strong></p><pre># List NLBs tagged with your cluster name<br>aws elbv2 describe-load-balancers \<br>  --query &#39;LoadBalancers[].{Name:LoadBalancerName,ARN:LoadBalancerArn,VPC:VpcId}&#39; \<br>  --output table</pre><pre># Or by VPC ID:<br>aws elbv2 describe-load-balancers \<br>  --query &quot;LoadBalancers[?VpcId==&#39;vpc-xxxxxxxxx&#39;].LoadBalancerArn&quot; \<br>  --output text</pre><p><strong>Delete them:</strong></p><pre>aws elbv2 delete-load-balancer \<br>  --load-balancer-arn arn:aws:elasticloadbalancing:ap-south-1:123456789:loadbalancer/net/k8s-sreaiage-abc123/xyz</pre><h3>ela-attach ENIs — the ones you cannot delete</h3><p>When inspecting your VPC’s ENIs, you may see interfaces with description &quot;amazon-eks-...&quot; and request type &quot;ela-attach&quot;. These are EKS control plane ENIs — AWS-managed network interfaces that connect the EKS control plane to your VPC.</p><pre>$ aws ec2 delete-network-interface --network-interface-id eni-xxx<br># An error occurred (OperationNotPermitted): You do not have permission to<br># manage &#39;ela-attach&#39; attachment type network interfaces.</pre><p><strong>Do not try to delete these.</strong> They are owned by AWS and will be released automatically when the CloudFormation stack finishes deleting the control plane. There is no manual action required or possible.</p><h3>Security groups block VPC deletion</h3><p>Kubernetes also creates security groups for load balancers and node communication. These must be deleted before the VPC can be removed.</p><pre># Find security groups in the VPC (exclude the default one)<br>aws ec2 describe-security-groups \<br>  --filters &quot;Name=vpc-id,Values=vpc-xxxxxxxxx&quot; \<br>  --query &#39;SecurityGroups[?GroupName!=`default`].{ID:GroupId,Name:GroupName}&#39;</pre><pre># Delete them one by one<br>aws ec2 delete-security-group --group-id sg-xxxxxxxxx</pre><p>If a security group delete fails with DependencyViolation, there is still an ENI referencing it. Find and delete that ENI first, or wait for the NLB deletion to propagate (can take 1–2 minutes).</p><h3>Complete EKS Teardown Playbook</h3><p>Follow this order to avoid stuck namespaces and orphaned AWS resources. The sequence matters — each step removes a dependency for the next.</p><p><strong>Phase 1: Delete Kubernetes workloads (before any infrastructure)</strong></p><pre># 1. Delete Services (allows LB Controller to clean up NLBs while it&#39;s still running)<br>kubectl delete svc --all -n my-namespace --wait=true</pre><pre># 2. Delete Deployments, StatefulSets<br>kubectl delete deploy,sts,ds --all -n my-namespace</pre><pre># 3. Delete any CRDs&#39; custom resources<br>kubectl delete targetgroupbinding,ingressclassparams --all -n my-namespace</pre><pre># 4. Delete the namespace normally (wait for it)<br>kubectl delete ns my-namespace --timeout=120s</pre><p><strong>Phase 2: Delete controllers (after their managed resources are gone)</strong></p><pre># Uninstall AWS Load Balancer Controller AFTER services are deleted<br>helm uninstall aws-load-balancer-controller -n kube-system</pre><pre># Uninstall any other controllers (cert-manager, external-dns, etc.)<br>helm uninstall cert-manager -n cert-manager</pre><p><strong>Phase 3: If namespaces are stuck, force-finalize</strong></p><pre># For each stuck namespace:<br>NS=&quot;my-namespace&quot;</pre><pre># Check what&#39;s blocking<br>kubectl get namespace $NS -o json | jq &#39;.status.conditions&#39;</pre><pre># Patch finalizers off any blocking resources<br>kubectl get namespace $NS -o json \<br>  | jq &#39;del(.spec.finalizers[])&#39; \<br>  | kubectl replace --raw &quot;/api/v1/namespaces/$NS/finalize&quot; -f -</pre><p><strong>Phase 4: Delete the cluster</strong></p><pre>exsctl delete cluster --name my-cluster --region ap-south-1</pre><p>This triggers the CloudFormation stack deletion. Watch it:</p><pre>aws cloudformation describe-stack-events \<br>  --stack-name eksctl-my-cluster-cluster \<br>  --query &#39;StackEvents[?ResourceStatus==`DELETE_FAILED`].[LogicalResourceId,ResourceStatusReason]&#39; \<br>  --output table</pre><p><strong>Phase 5: Manual AWS cleanup if CloudFormation fails</strong></p><pre># 1. Find and delete orphaned NLBs<br>aws elbv2 describe-load-balancers \<br>  --query &quot;LoadBalancers[?contains(VpcId,&#39;vpc-xxx&#39;)].LoadBalancerArn&quot; \<br>  --output text | xargs -I{} aws elbv2 delete-load-balancer --load-balancer-arn {}</pre><pre># Wait 60 seconds for NLB ENIs to detach<br>sleep 60</pre><pre># 2. Delete subnets<br>for SUBNET in $(aws ec2 describe-subnets --filters &quot;Name=vpc-id,Values=vpc-xxx&quot; \<br>  --query &#39;Subnets[].SubnetId&#39; --output text); do<br>  aws ec2 delete-subnet --subnet-id $SUBNET<br>done</pre><pre># 3. Detach and delete internet gateway<br>IGW=$(aws ec2 describe-internet-gateways \<br>  --filters &quot;Name=attachment.vpc-id,Values=vpc-xxx&quot; \<br>  --query &#39;InternetGateways[0].InternetGatewayId&#39; --output text)<br>aws ec2 detach-internet-gateway --internet-gateway-id $IGW --vpc-id vpc-xxx<br>aws ec2 delete-internet-gateway --internet-gateway-id $IGW</pre><pre># 4. Delete non-default security groups<br>for SG in $(aws ec2 describe-security-groups \<br>  --filters &quot;Name=vpc-id,Values=vpc-xxx&quot; \<br>  --query &#39;SecurityGroups[?GroupName!=`default`].GroupId&#39; --output text); do<br>  aws ec2 delete-security-group --group-id $SG<br>done</pre><pre># 5. Delete the VPC<br>aws ec2 delete-vpc --vpc-id vpc-xxx</pre><h3>What Can Go Wrong</h3><p><strong>1. Orphaned cloud resources after force-finalize</strong></p><p>This is the most dangerous outcome. If you force-finalize before the controller cleans up, AWS resources persist invisibly — NLBs, target groups, security groups. They bill you and block future VPC deletion. Always run the AWS CLI checks after force-finalizing.</p><p><strong>2. CloudFormation DELETE_FAILED is not fatal</strong></p><p>A DELETE_FAILED stack does not mean the cluster is still running. It usually means one dependency (a subnet, a security group) could not be deleted because of an orphaned resource. The EKS control plane itself may be gone. Clean up the AWS dependency manually and the stack will finish.</p><p><strong>3. </strong><strong>eksctl delete cluster exits successfully but VPC remains</strong></p><p>eksctl considers its job done when the stack deletion starts — it does not always wait for full completion. Always verify the VPC is actually gone:</p><pre>aws ec2 describe-vpcs --vpc-ids vpc-xxx<br># Should return: An error occurred (InvalidVpcID.NotFound)</pre><p><strong>4. The </strong><strong>ela-attach ENIs block subnet deletion temporarily</strong></p><p>Even after NLBs are deleted, EKS control plane ENIs (ela-attach type) remain until CloudFormation finishes deleting the control plane stack. If you delete NLBs and immediately try to delete subnets, you may still see DependencyViolation. Wait 1–2 minutes and retry.</p><p><strong>5. Force-finalizing a namespace with running pods</strong></p><p>If pods are still running inside the namespace when you force-finalize the namespace itself, the pods become orphaned — they still run on the node but have no namespace parent in the API. Always force-delete pods first:</p><pre>kubectl delete pods --all -n my-namespace --force --grace-period=0</pre><p><strong>6. jq may not be installed</strong></p><p>The force-finalize command uses jq. On minimal cloud images it may not be installed:</p><pre>apt-get install -y jq    # Debian/Ubuntu<br>yum install -y jq        # Amazon Linux / RHEL<br>brew install jq          # macOS</pre><h3>Key Takeaways</h3><p><strong>Finalizers are not bugs — they are safety mechanisms.</strong> They exist to prevent orphaned cloud resources. When they get stuck, it’s because the system lost track of its own cleanup process, not because Kubernetes is broken.</p><p><strong>Force-finalize is surgery, not a shortcut.</strong> It tells Kubernetes “this is done” without doing the cleanup. Use it only when:</p><ul><li>The owning controller no longer exists</li><li>You have verified there are no cloud resources left to clean up, or you’re prepared to clean them up manually</li></ul><p><strong>On AWS EKS, the correct teardown order is:</strong></p><ol><li>Delete workloads (Pods, Services) — while controllers are still running</li><li>Delete controllers (AWS LB Controller, cert-manager, etc.)</li><li>Force-finalize stuck namespaces if any remain</li><li>Run eksctl delete cluster</li><li>Verify and manually delete any orphaned NLBs, security groups, and VPCs</li></ol><p><strong>The two-step failure pattern to memorize:</strong></p><ul><li>Step A: You delete the AWS Load Balancer Controller before deleting your LoadBalancer Services</li><li>Step B: The NLB lives in AWS forever, blocks your VPC, and the only fix is finding it via AWS CLI and deleting it manually</li></ul><p><strong>The diagnostic you should always run first:</strong></p><pre>kubectl get namespace &lt;name&gt; -o json | jq &#39;.status.conditions&#39;</pre><p>This tells you exactly what is blocking deletion and why. Never guess — read the status first.</p><p><em>Written from a real AWS EKS cluster teardown: a 5-node LangGraph </em><a href="https://github.com/Machindra220/SRE-AI-Agent-Observability"><em>SRE agent project </em></a><em>on EKS ap-south-1, where both of the above failure patterns were hit in sequence during final infrastructure teardown.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac343f0985c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taints, Tolerations &
Affinity in Kubernetes]]></title>
            <link>https://medium.com/@machindra220/taints-tolerations-affinity-in-kubernetes-55e233d62091?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/55e233d62091</guid>
            <category><![CDATA[taints-and-toleration]]></category>
            <category><![CDATA[affinity]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 02:51:01 GMT</pubDate>
            <atom:updated>2026-10-15T02:51:01.674Z</atom:updated>
            <content:encoded><![CDATA[<p>A complete, beginner-friendly guide to controlling exactly which pods land on which nodes — and why that matters in production.</p><p>In this article</p><ol><li><a href="#problem">The Problem — Why Pod Placement Matters</a></li><li><a href="#taints">Taints &amp; Tolerations — The Bouncer Model</a></li><li><a href="#affinity">Node Affinity — Attraction</a></li><li><a href="#pod-affinity">Pod Affinity &amp; Anti-Affinity — Social Rules</a></li><li><a href="#together">Using All Three Together</a></li><li><a href="#summary">Quick Reference</a></li></ol><p>Part 1</p><h3>The Problem — Why Pod Placement Matters</h3><p>When you deploy a pod in Kubernetes, the scheduler decides which node it runs on. By default, it picks any available node. This sounds fine — until you have a cluster with different kinds of nodes doing different jobs.</p><p>Imagine your cluster has three nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*nusFFKW21lRX_3pu_Wq3Og.png" /><figcaption><em>Without scheduling control: random pod placement — expensive nodes wasted, busy nodes overloaded.</em></figcaption></figure><p>This is the exact problem that Taints &amp; Tolerations, Node Affinity, and Pod Affinity/Anti-Affinity solve. Think of them as three different tools — each with a different job.</p><p>Mental model before you read on</p><blockquote>Taints = a “No Entry” sign on the door of a node.<br>Tolerations = a special pass that lets your pod ignore that sign.<br>Affinity = a pod’s own preferences about where it wants to live.</blockquote><p>Part 2</p><h3>Taints &amp; Tolerations — The Bouncer Model</h3><p>A taint is set on a <em>node</em>. It says: <em>“I don’t want just any pod here.”</em></p><p>A toleration is set on a <em>pod</em>. It says: <em>“I’m okay with that node’s restriction, let me in.”</em></p><p>Think of a nightclub. The bouncer (taint) stands at the door. Only guests with the right wristband (toleration) get in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*BQ5u2BqiMTNx-u6ZoSLvqA.png" /><figcaption><em>The Bouncer model — only pods with the matching toleration get past the taint.</em></figcaption></figure><h3>Setting a taint on a node</h3><pre>kubectl taint nodes gpu-node-1 gpu=true:NoSchedule</pre><p>The taint format is always key=value:Effect. The three effects are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*XSf77z6kFgAhM4Ua5xybqQ.png" /><figcaption>taint format table</figcaption></figure><h3>Adding a toleration to your pod</h3><p>pod-spec.yaml</p><pre>spec:<br>  tolerations:<br>    - key: &quot;gpu&quot;<br>      operator: &quot;Equal&quot;<br>      value: &quot;true&quot;<br>      effect: &quot;NoSchedule&quot;</pre><p>There’s also a wildcard form — tolerate <em>every</em> taint on the node:</p><p>tolerate ALL taints (used by DaemonSets)</p><pre>tolerations:<br>  - operator: Exists   # no key or value — matches everything</pre><blockquote>⚠ Common mistake:</blockquote><blockquote>Tolerations only <em>allow</em> a pod to land on a tainted node — they don’t <em>guarantee</em> it. A pod with a toleration can still end up on any untainted node. To guarantee placement, you also need affinity (covered next).</blockquote><h3>Real-world example — your SRE project</h3><p>In the SRE-AI-Agent project, agent-nodes (the node that runs LangGraph) has this taint:</p><p>eksctl — applied during infra-up</p><pre>--node-taints &quot;workload=ai-agent:NoSchedule&quot;</pre><p>This keeps pgvector, Prometheus, and other pods off that node, reserving its resources entirely for the LangGraph RCA agent. Only the LangGraph pod has a toleration for workload=ai-agent, so only it gets in.</p><p>The one exception is Promtail (the log shipper DaemonSet). It needs to run on every node including agent-nodes. So it uses the wildcard:</p><p>deploy-loki-promtail.sh</p><pre>tolerations:<br>  - operator: Exists   # DaemonSet — runs on ALL nodes regardless of taints</pre><p>Part 3</p><h3>Node Affinity — Attraction</h3><p>Node Affinity is a rule on a <em>pod</em> that says: <em>“I want to run on a node that has this label.”</em> Unlike taints (which push pods away from nodes), affinity <em>pulls</em> a pod toward certain nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*vmof-CwrO6C1ilE5-nwsRg.png" /><figcaption><em>Node Affinity pulls the pod toward nodes with the matching label.</em></figcaption></figure><h3>Hard vs Soft rules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*fbtUR--x44PG5oxBqw99cQ.png" /><figcaption>Table: Hard and soft rules</figcaption></figure><p>langgraph-deployment.yaml — Hard rule</p><pre>spec:<br>  affinity:<br>    nodeAffinity:<br>      requiredDuringSchedulingIgnoredDuringExecution:<br>        nodeSelectorTerms:<br>          - matchExpressions:<br>              - key: role<br>                operator: In<br>                values: [&quot;agent&quot;]   # must land on a node with role=agent</pre><blockquote>✓ Best practice: use both</blockquote><blockquote>In our SRE project, the agent-node has a taint (keeps others out) AND the LangGraph pod has affinity (pulls it specifically here). Taint alone leaves the pod floating; affinity alone lets the pod land anywhere the taint isn’t. You need both for guaranteed exclusive placement.</blockquote><p>Part 4</p><h3>Pod Affinity &amp; Anti-Affinity — Social Rules</h3><p>So far, pods have been expressing opinions about <em>nodes</em>. Now pods can express opinions about <em>other pods</em>.</p><p>Pod Affinity: “Schedule me on the <em>same</em> node as pod X.”<br>Pod Anti-Affinity: “Schedule me on a <em>different</em> node from pod X.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*7N1aLwimbbbVfRnRdmdFHQ.png" /><figcaption><em>Left: Pod Affinity groups pods together (low latency). Right: Anti-Affinity spreads replicas across nodes (high availability).</em></figcaption></figure><h3>Pod Affinity — co-locate for low latency</h3><p>fastapi-deployment.yaml — “sit near Redis”</p><pre>spec:<br>  affinity:<br>    podAffinity:<br>      requiredDuringSchedulingIgnoredDuringExecution:<br>        - labelSelector:<br>            matchLabels:<br>              app: redis-cache       # find nodes that already have Redis<br>          topologyKey: kubernetes.io/hostname   # &quot;same node&quot;</pre><h3>Pod Anti-Affinity — spread for high availability</h3><p>fastapi-deployment.yaml — “never share a node with my own replicas”</p><pre>spec:<br>  affinity:<br>    podAntiAffinity:<br>      requiredDuringSchedulingIgnoredDuringExecution:<br>        - labelSelector:<br>            matchLabels:<br>              app: sre-ai-agent     # don&#39;t co-locate with pods that share my label<br>          topologyKey: kubernetes.io/hostname   # &quot;different node&quot;</pre><p>What is topologyKey?</p><p>topologyKey defines the boundary. kubernetes.io/hostname means &quot;per node&quot;. You can also use topology.kubernetes.io/zone to spread across availability zones, or topology.kubernetes.io/region for regions. The key must match a label that exists on the nodes.</p><p>Part 5</p><h3>Using All Three Together</h3><p>In a real production cluster, you combine all three mechanisms. Here is how the SRE-AI-Agent project uses them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*M2rHHuwO4le8XlavWwMNrQ.png" /><figcaption>Our full cluster — three mechanisms working together: taint (repels), toleration (allows), affinity (attracts).</figcaption></figure><h3>The complete LangGraph deployment spec</h3><p>langgraph-deployment.yaml — all three mechanisms</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: langgraph-agent<br>  namespace: sre-ai-agent-llm<br>spec:<br>  replicas: 1<br>  template:<br>    spec:<br>      # 1. TOLERATION — &quot;I can handle the taint on agent-nodes&quot;<br>      tolerations:<br>        - key: &quot;workload&quot;<br>          operator: &quot;Equal&quot;<br>          value: &quot;ai-agent&quot;<br>          effect: &quot;NoSchedule&quot;<br>      # 2. NODE AFFINITY — &quot;I want to land on role=agent specifically&quot;<br>      affinity:<br>        nodeAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            nodeSelectorTerms:<br>              - matchExpressions:<br>                  - key: role<br>                    operator: In<br>                    values: [&quot;agent&quot;]<br>      containers:<br>        - name: langgraph<br>          image: 123456789.dkr.ecr.ap-south-1.amazonaws.com/langgraph-agent:latest<br>          resources:<br>            requests:<br>              cpu: &quot;500m&quot;<br>              memory: &quot;512Mi&quot;<br>            limits:<br>              cpu: &quot;1000m&quot;<br>              memory: &quot;1Gi&quot;</pre><p>Part 6</p><h3>Quick Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*zaYQXAbWrqcoqd80QiZ3eA.png" /></figure><h4>🔒 Taint + Toleration</h4><p>The access control pair. Taint locks the node; toleration is the key. Always used together. Neither is useful without the other.</p><h4>🧲 Affinity (Node)</h4><p>Tells a pod <em>where</em> to go. Hard rules cause Pending forever on failure; soft rules fall back gracefully.</p><h4>👥 Pod Affinity</h4><p>Group latency-sensitive workloads. FastAPI and its Redis cache on the same node cuts network hops to zero.</p><h4>↔ Pod Anti-Affinity</h4><p>Force replicas apart. If one node dies, the other replicas survive. The most common HA pattern in Kubernetes.</p><blockquote>The golden rule</blockquote><blockquote>Taint = the node sets the rules.<br>Toleration = the pod says “I accept your rules.”<br>Affinity = the pod says “And I specifically want to go there.”</blockquote><blockquote>For guaranteed exclusive placement: you need all three. Taint keeps others out. Toleration lets you in. Affinity makes sure you actually go there instead of somewhere else that has no taint.</blockquote><p>Written as part of the SRE-AI-Agent-Observability project deep-dive series — covering the end-to-end architecture from EKS bootstrap to LangGraph RCA pipelines on Kubernetes.</p><p>Complete Project Link : <a href="https://github.com/Machindra220/SRE-AI-Agent-Observability/tree/main">Machindra220/SRE-AI-Agent-Observability</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55e233d62091" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Fundamentals Every Kubernetes Engineer Must Know]]></title>
            <link>https://medium.com/@machindra220/linux-fundamentals-every-kubernetes-engineer-must-know-c8d679979992?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d679979992</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes-pods]]></category>
            <category><![CDATA[linux-permission]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 08:50:42 GMT</pubDate>
            <atom:updated>2026-10-07T08:50:42.026Z</atom:updated>
            <content:encoded><![CDATA[<p>Every Kubernetes Pod is a Linux process. If you skip Linux, you hit walls the moment something breaks in production.</p><h3>Why Linux Is Not Optional for Kubernetes Engineers</h3><p>Most people learn Kubernetes through kubectl commands and YAML files. That works until something breaks in production at 2 AM.</p><p>When a Pod crashes with exit code 137, when a node shows “disk pressure” despite having free space, when your app drops requests during deployments — none of those problems are solved with YAML. They are solved by understanding what is actually happening at the Linux level.</p><p>Here is the core truth: <strong>every Kubernetes Pod is a Linux process</strong>. The container runtime (containerd) uses Linux namespaces to give it an isolated view of the system, and cgroups to limit its CPU and memory. kubectl is a convenient abstraction over that reality.</p><p>This article covers the six Linux concepts that will make you a significantly better Kubernetes engineer:</p><ol><li>Processes and the /proc filesystem</li><li>Inodes and why disks “fill up” without using space</li><li>File permissions and how they map to Pod security</li><li>Signals — how Kubernetes actually stops containers</li><li>Sockets — how Kubernetes components talk to each other</li><li>How it all connects to containers and Pods</li></ol><p>Every concept comes with commands you can run right now in a Linux terminal or WSL.</p><h3>Processes and the /proc Filesystem</h3><p>A <strong>process</strong> is a running program. Linux assigns every process a unique Process ID (PID) and tracks its state: memory, open files, owner, and signals.</p><p>Processes form a tree. Every process (except PID 1) has a parent. PID 1 is the init system (systemd on most Linux distros). Every container you run is ultimately a child of PID 1 on the host machine.</p><pre>Linux Host (Kubernetes Node)<br>│<br>└── systemd (PID 1)<br>      ├── containerd (PID 847)<br>      │     └── container-shim (PID 2201)<br>      │           └── your app / Pod  ← host PID 2350, NSpid 1<br>      ├── kubelet (PID 923)<br>      └── sshd (PID 1102)</pre><h3>The /proc filesystem</h3><p>/proc is not a real directory. It is a <strong>virtual filesystem</strong> the kernel exposes so you can read process state as files. Every number you see inside /proc is a PID.</p><pre>ls /proc              # see all running process IDs<br>cat /proc/$$/status   # $$ = your current shell&#39;s PID</pre><p>Key fields in /proc/&lt;PID&gt;/status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heViNRIgj7a8bm5l88K3jQ.png" /></figure><h3>The NSpid trick containers use</h3><p>When you run a container, the container runtime calls unshare() to create a new PID namespace. Inside that namespace, your app thinks it is <strong>PID 1</strong>. But on the host, you can find it under its real PID in /proc.</p><pre># On the host, find your container&#39;s real PID:<br>cat /proc/2350/status | grep NSpid<br># NSpid: 1    ← container thinks it is PID 1<br># Pid: 2350   ← host knows the truth</pre><p>This is how kubectl exec works — it enters the container&#39;s namespace by following /proc/&lt;host-PID&gt;/ns/.</p><h3>Inodes: Why “Disk Full” Happens With Free Space</h3><p>Every file on Linux has two parts that live separately:</p><ul><li><strong>The name</strong> — stored in a directory entry, just a pointer</li><li><strong>The inode</strong> — stores everything else: size, permissions, owner, timestamps, and pointers to the actual data blocks on disk</li></ul><p>When you create a file, Linux allocates one inode. The filesystem has a fixed number of inodes, set when it was formatted. You can run out of inodes before you run out of disk space.</p><pre># Check inode usage across filesystems<br>df -i<br><br># Output:<br># Filesystem     Inodes   IUsed   IFree IUse%<br># /dev/sdd     67108864  162064 66946800   1%<br><br># Inspect a file&#39;s inode<br>stat testfile<br># Inode: 80826   Links: 2</pre><h3>Hard links: two names, one inode</h3><pre>touch myfile<br>ln myfile myfile-copy          # hard link<br>ls -lai myfile myfile-copy     # same inode number!<br># 80826 -rw-r--r-- 2 ...  myfile<br># 80826 -rw-r--r-- 2 ...  myfile-copy</pre><p>Both names point to inode 80826. The 2 in the permissions column is the <strong>link count</strong>. Data is deleted only when the link count reaches zero. This is why deleting a file does not always free disk space immediately.</p><h3>Why this breaks Kubernetes nodes</h3><p>Kubernetes nodes run many containers. Each container has many small files (logs, temp files, lock files). A node can hit inode exhaustion while showing 60% disk space free.</p><p>Symptom: no space left on device errors even with free disk.</p><pre># Diagnose inode exhaustion on a node<br>df -i<br># If IUse% is near 100% on /dev/sda or similar, that is your problem<br><br># Clean up: remove unused container images and logs<br>sudo crictl rmi --prune<br>sudo journalctl --vacuum-time=1d</pre><p>The DiskPressure node condition in Kubernetes fires when inodes drop below the eviction threshold, not just when bytes run out.</p><h3>File Permissions: What rwxr-xr-x Actually Means</h3><p>Every file and directory in Linux has three permission sets and an owner.</p><pre>ls -la /etc/hosts<br># -rw-r--r-- 1 root root 221 Jan 1 00:00 /etc/hosts</pre><p>Breaking down -rw-r--r--:</p><pre>-   rw-   r--   r--<br>|    |     |     |<br>|    |     |     others (everyone else): read only<br>|    |     group (root group): read only<br>|    owner (root): read + write<br>file type: - = file, d = directory, l = symlink</pre><h3>Numeric permissions (you will see these in Kubernetes)</h3><p>Each permission set (owner/group/others) maps to a number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*k0iSSfNUL4eavS-fYRa1tQ.png" /><figcaption>Permission Symbols and Values</figcaption></figure><p>Add them: rw- = 4+2+0 = <strong>6</strong>, r-- = 4+0+0 = <strong>4</strong>, rwx = 4+2+1 = <strong>7</strong></p><p>So rw-r--r-- = <strong>644</strong>. You will see this in Kubernetes securityContext.</p><pre>stat -c &quot;%a %U %G %n&quot; /etc/hosts<br># 644 root root /etc/hosts<br><br>chmod 600 myfile    # owner read+write only, nobody else<br>chmod 755 script.sh # owner rwx, everyone else rx</pre><h3>How this maps directly to Kubernetes</h3><p>In a Pod spec, the securityContext block sets Linux permissions:</p><pre>securityContext:<br>  runAsUser: 1000       # run as UID 1000, not root (UID 0)<br>  runAsGroup: 3000      # primary group = GID 3000<br>  fsGroup: 2000         # all mounted volume files owned by GID 2000<br>  runAsNonRoot: true    # fail if image tries to run as root</pre><p>These are not Kubernetes inventions. They set the Uid and Gid fields in /proc/&lt;PID&gt;/status of your container process. If your app tries to write a file it does not own, you get Permission denied — a Linux error, not a Kubernetes error.</p><h3>Signals: How Kubernetes Actually Stops Containers</h3><p>A <strong>signal</strong> is a message you send to a running process. Think of it as a text message — the process can read it, react, or in some cases ignore it.</p><p>Two signals matter most for Kubernetes:</p><p>SignalNumberMessageCan the app ignore it?SIGTERM15&quot;Please shut down when ready”Yes — app decides how to reactSIGKILL9&quot;Die immediately, no choice”No — kernel kills it instantly</p><h3>The termination sequence</h3><p>When you run kubectl delete pod, Kubernetes does <strong>not</strong> immediately kill your container:</p><pre>1. kubectl delete pod<br>   → API server sets deletionTimestamp<br><br>2. Endpoint removed from Service<br>   → new traffic stops routing to this Pod<br><br>3. preStop hook executes<br>   → e.g. sleep 5 to let in-flight requests finish<br><br>4. SIGTERM sent to PID 1<br>   → graceful shutdown begins — app should handle this<br><br>5. ┌─────────────────────────────────────────┐<br>   │  terminationGracePeriodSeconds = 30s    │<br>   │  if app exits cleanly → done ✓          │<br>   │  if still running after 30s → SIGKILL  │<br>   └─────────────────────────────────────────┘<br><br>6. SIGKILL sent (if needed)<br>   → kernel kills instantly, no cleanup possible<br>   → exit code 137</pre><h3>Exit codes tell you what happened</h3><pre>128 + signal number = exit code<br><br>Exit code 143 = 128 + 15 = received SIGTERM (clean shutdown)<br>Exit code 137 = 128 + 9  = killed by SIGKILL (grace period expired)<br>Exit code 0   = process exited cleanly on its own<br>Exit code 1   = process crashed with an error</pre><p>If you see exit code 137 in kubectl describe pod, your app did not handle SIGTERM — it got force-killed after 30 seconds.</p><h3>How to handle SIGTERM in your app</h3><pre># Python example<br>import signal, sys<br><br>def handle_sigterm(sig, frame):<br>    print(&quot;SIGTERM received, finishing in-flight requests...&quot;)<br>    # finish current work, close DB connections<br>    sys.exit(0)<br><br>signal.signal(signal.SIGTERM, handle_sigterm)</pre><p>Always handle SIGTERM. Set terminationGracePeriodSeconds to match your slowest request, not the default 30s.</p><h3>Sockets: How Kubernetes Components Talk to Each Other</h3><p>A <strong>socket</strong> is a communication endpoint — like a phone jack that processes plug into to talk to each other.</p><p>Two types matter for Kubernetes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faB07KC5M22z2lYnjDRFwQ.png" /><figcaption><strong>Socket Types</strong></figcaption></figure><h3>The command you need: ss</h3><p>ss replaces the old netstat command. The flags you will use constantly:</p><pre>ss -tlnp   # TCP (-t), Listening (-l), Numeric ports (-n), show Process (-p)<br>ss -xlnp   # Unix sockets (-x), Listening, Numeric, show Process</pre><h3>What you see on a real Kubernetes node</h3><pre>$ ss -tlnp<br>State   Local Address:Port   Process<br>LISTEN  127.0.0.1:6443       # Kubernetes API server<br>LISTEN  127.0.0.1:10250      # kubelet HTTPS API<br>LISTEN  127.0.0.1:10257      # controller-manager<br>LISTEN  127.0.0.1:10259      # scheduler<br>LISTEN  *:443                # ingress controller (HTTPS)<br>LISTEN  *:80                 # ingress controller (HTTP)</pre><pre>$ ss -xlnp<br>Netid  Local Address<br>u_str  /var/run/docker.sock            # containerd/Docker<br>u_str  /run/containerd/containerd.sock # container runtime<br>u_str  /run/WSL/475_interop            # WSL bridge</pre><h3>Why Unix sockets exist in Kubernetes</h3><p>When kubelet needs to start a container, it does not make an HTTP request over the network. It calls the container runtime (containerd) via a <strong>Unix socket</strong> at /run/containerd/containerd.sock. This is the Container Runtime Interface (CRI).</p><p>Unix sockets are faster (no network stack), and they only work on the same machine — which is exactly what you want for local inter-process communication.</p><pre># Verify the container runtime socket exists<br>ls -la /run/containerd/containerd.sock<br># If missing: containerd is not running, kubelet cannot start any containers</pre><p><strong>Troubleshooting pattern:</strong> If kubectl exec stops working on a node, check that port 10250 (kubelet) is still listening with ss -tlnp | grep 10250.</p><h3>Putting It All Together: A Pod Is Just a Linux Process</h3><p>After all six concepts, here is the complete picture.</p><p>When you run kubectl apply -f pod.yaml, this is what actually happens on the Linux host:</p><ol><li><strong>API server</strong> receives the request, stores the Pod spec in etcd, listening on TCP socket port 6443</li><li><strong>Scheduler</strong> finds a node for the Pod, listening on port 10259</li><li><strong>kubelet</strong> on that node sees the new Pod, calls containerd via Unix socket /run/containerd/containerd.sock</li><li><strong>containerd</strong> calls unshare() to create new Linux <strong>namespaces</strong> (PID, net, mnt, uts) — isolation</li><li>containerd calls the <strong>CNI plugin</strong> to assign a network namespace and IP address</li><li>containerd applies <strong>cgroup</strong> limits (CPU = cpu.max, memory = memory.limit_in_bytes) — resource limits</li><li>Your app process starts with NSpid: 1 inside the container, but the host sees its real PID in /proc</li><li>kubelet runs your <strong>liveness and readiness probes</strong> by making HTTP requests or running exec commands inside the container’s namespace</li><li>When the Pod is deleted, kubelet sends <strong>SIGTERM</strong> (signal 15), waits terminationGracePeriodSeconds, then sends <strong>SIGKILL</strong> (signal 9) if needed</li></ol><h3>The mental model that changes everything</h3><pre>Kubernetes Pod<br>  = Linux process(es)<br>  + PID namespace       (isolated process IDs)<br>  + network namespace   (isolated IP and ports)<br>  + mount namespace     (isolated filesystem view)<br>  + cgroup              (CPU and memory limits)<br>  + securityContext     (UID/GID/permissions)</pre><p>Every time you see a confusing Kubernetes error, ask: what is happening at the Linux level? That question leads to the answer faster than any documentation.</p><h3>Commands to have in your muscle memory</h3><pre># Process inspection<br>ps aux                          # all running processes<br>cat /proc/&lt;PID&gt;/status          # process details<br>ls /proc/&lt;PID&gt;/ns/              # process namespaces<br><br># Filesystem<br>df -h                           # disk space<br>df -i                           # inode usage (the other kind of disk full)<br>stat &lt;file&gt;                     # inode, permissions, timestamps<br>ls -lai                         # inode numbers for files<br><br># Permissions<br>chmod 600 &lt;file&gt;                # set permissions numerically<br>stat -c &quot;%a %U %G&quot; &lt;file&gt;      # show octal permissions + owner<br><br># Signals<br>kill -15 &lt;PID&gt;                  # SIGTERM (polite)<br>kill -9 &lt;PID&gt;                   # SIGKILL (forced)<br># exit code 137 = killed by SIGKILL<br># exit code 143 = received SIGTERM and exited<br><br># Sockets<br>ss -tlnp                        # TCP listening sockets + process<br>ss -xlnp                        # Unix domain sockets<br>ss -tlnp | grep 6443            # is the API server listening?<br>ss -tlnp | grep 10250           # is kubelet running?</pre><p><em>Next in this series: Linux Namespaces and cgroups — the two kernel features that make containers possible.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d679979992" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Terraform Module Calls Actually Work — Variables, Outputs, and the Dependency Chain]]></title>
            <link>https://medium.com/@machindra220/how-terraform-module-calls-actually-work-variables-outputs-and-the-dependency-chain-5ef72e5d551c?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ef72e5d551c</guid>
            <category><![CDATA[aws-vpc-terraform]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 03:01:04 GMT</pubDate>
            <atom:updated>2026-09-30T03:01:04.784Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve seen a lot of engineer&#39;s copy-paste Terraform code without really understanding what’s happening between the files. I was one of them early on. You run terraform apply, things get created, and you move on.</p><p>But when something breaks — wrong subnet passed to EKS, OIDC issuer URL not available yet, node group failing because the cluster isn’t ready — you need to understand exactly how the wiring works. Not just what to write, but <em>why</em> it’s written that way.</p><p>This is what I learned while building a production SRE platform on AWS. Let me walk you through the complete flow.</p><h3>The Three-File Pattern Every Module Follows</h3><p>Every Terraform module, no matter how complex, has the same three files:</p><pre>modules/vpc/<br>├── variables.tf   ← what the module needs (inputs)<br>├── main.tf        ← what the module creates (resources)<br>└── outputs.tf     ← what the module exposes (outputs)</pre><p>This isn’t convention for convention’s sake. It’s a clean separation of concerns — inputs, logic, outputs. Once you internalize this pattern, you can read any Terraform module you’ve never seen before and understand it in minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dk_tymBC9xK90n2nQQZnQ.png" /><figcaption>Terraform Modules Call Flow</figcaption></figure><h3>The Orchestrator: dev/main.tf</h3><p>Here’s the thing most tutorials skip over. dev/main.tf doesn&#39;t create any AWS resources directly. It has no resource blocks. Its only job is to call modules and wire them together.</p><p>Think of it as the conductor of an orchestra. It doesn’t play any instruments. It tells each section when to start and what to play.</p><p>This is what a module call looks like:</p><pre>module &quot;vpc&quot; {<br>  source = &quot;../../modules/vpc&quot;<br><br>  project_name       = var.project_name<br>  environment        = var.environment<br>  vpc_cidr           = var.vpc_cidr<br>  availability_zones = var.availability_zones<br>}</pre><p>Three things happening here:</p><p><strong>source</strong> — tells Terraform where the module code lives. It reads every .tf file in that folder and executes them.</p><p><strong>Input arguments</strong> — every key = value line after source is passing a value into the module. The module can&#39;t read var.* from the environment directly. You must hand it in explicitly.</p><p><strong>No </strong><strong>resource blocks</strong> — dev/main.tf never creates a VPC, subnet, or security group. The module does that internally.</p><h3>How Variables Flow: The Answer Sheet Analogy</h3><p>There are two files involved in variables and they have a clear separation of responsibility.</p><p>variables.tf is the <strong>question sheet</strong> — it declares what values are needed, their types, and optionally a default:</p><pre>variable &quot;eks_node_instance_type&quot; {<br>  description = &quot;EC2 instance type for worker nodes&quot;<br>  type        = string<br>  default     = &quot;t3.medium&quot;<br>}</pre><p>terraform.tfvars is the <strong>answer sheet</strong> — it provides the actual values:</p><pre>eks_node_instance_type = &quot;t3.small&quot;</pre><p>The .tfvars file always wins over defaults. If you set t3.small in .tfvars but the default is t3.medium, Terraform uses t3.small. Every time.</p><p>The .tfvars file is gitignored. You commit .tfvars.example as a template for teammates, but never the actual values file — because in real projects it will eventually contain secrets, account IDs, or environment-specific settings that shouldn&#39;t live in version control.</p><p>When dev/main.tf calls a module with vpc_cidr = var.vpc_cidr, Terraform resolves var.vpc_cidr from the .tfvars file and passes the resolved value into the module. The module receives a plain string — it never knows where the value came from.</p><h3>Inside the Module: How Resources Use Variables</h3><p>Once variables are passed in, the module’s main.tf uses them to build real AWS resources:</p><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block           = var.vpc_cidr          # ← resolved at runtime<br>  enable_dns_support   = true<br>  enable_dns_hostnames = true<br><br>  tags = {<br>    Name = &quot;${var.project_name}-${var.environment}-vpc&quot;<br>  }<br>}</pre><p>var.vpc_cidr here refers to the module&#39;s own variables.tf, not the environment&#39;s. Each module has its own variable scope. This is important — variables don&#39;t leak between modules.</p><p>AWS provisions the resource and assigns it a runtime-generated ID — something like vpc-0a1b2c3d4e5f. You cannot know this ID before terraform apply runs. This is where outputs become essential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oic2nY9aSieya2svBVbB_A.png" /><figcaption>Terraform main module flow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMEqrjkJPuExLpq1VhoteQ.png" /><figcaption>Terraform outputs flow</figcaption></figure><h3>How Outputs Work: The Return Value of a Module</h3><p>After a resource is created, outputs.tf captures its runtime values and names them so other modules can use them:</p><pre>output &quot;vpc_id&quot; {<br>  description = &quot;VPC ID&quot;<br>  value       = aws_vpc.main.id<br>}<br><br>output &quot;private_subnet_ids&quot; {<br>  description = &quot;List of private subnet IDs&quot;<br>  value       = aws_subnet.private[*].id<br>}</pre><p>aws_vpc.main.id is a reference to the live resource Terraform just created. At plan time this is an unknown value — shown as (known after apply) in the plan output. At apply time it becomes the real AWS-assigned ID.</p><p>Once exposed as an output, any other module in dev/main.tf can consume it:</p><pre>module &quot;eks&quot; {<br>  source = &quot;../../modules/eks&quot;<br><br>  vpc_id             = module.vpc.vpc_id           # ← VPC module output<br>  private_subnet_ids = module.vpc.private_subnet_ids  # ← VPC module output<br>}</pre><p>The syntax module.vpc.vpc_id has exactly three parts:</p><pre>module  .  vpc  .  vpc_id<br>  │          │        │<br>keyword   module    output<br>          label     name in<br>          in        outputs.tf<br>          main.tf</pre><p>module — keyword telling Terraform to look in a module, not a local variable or resource.<br> vpc — matches the label you gave the module block in dev/main.tf.<br> vpc_id — matches the output name in modules/vpc/outputs.tf.</p><p>All three must match exactly. A typo in any one of them and Terraform will error at plan time — before touching any infrastructure.</p><h3>The Hidden Superpower: Implicit Dependencies</h3><p>Here’s the part that took me a while to fully appreciate.</p><p>When EKS module references module.vpc.vpc_id, Terraform doesn&#39;t just get the value — it automatically understands that EKS depends on VPC. It builds a dependency graph internally and ensures VPC is fully created before EKS begins.</p><p>You never write this:</p><pre># You do NOT need this — Terraform figures it out<br>module &quot;eks&quot; {<br>  depends_on = [module.vpc]<br>}</pre><p>The output reference IS the dependency declaration. This is how Terraform achieves safe parallel execution — it can create independent resources simultaneously (like ECR and VPC which don’t depend on each other), while strictly sequencing dependent ones.</p><p>In our platform the dependency chain looks like this:</p><pre>VPC → EKS → IAM/IRSA<br>            ↑<br>           ECR (independent, runs in parallel with VPC)</pre><p>Terraform figures all of this out by tracing the module.*.* references in dev/main.tf. You just write the references. Terraform handles the ordering.</p><h3>Putting It All Together: The Complete Flow</h3><p>Here’s the end-to-end picture when you run terraform apply:</p><p><strong>1. Terraform reads </strong><strong>terraform.tfvars</strong> and resolves all var.* values.</p><p><strong>2. Terraform reads </strong><strong>dev/main.tf</strong> and builds the dependency graph by tracing all module.*.* references.</p><p><strong>3. Terraform executes independent modules in parallel.</strong> VPC and ECR have no dependencies between them — they start simultaneously.</p><p><strong>4. VPC module runs.</strong> Resources are created, AWS assigns IDs. outputs.tf captures those IDs.</p><p><strong>5. EKS module starts</strong> — because it referenced module.vpc.vpc_id, it was waiting. Now it has the real VPC ID and private subnet IDs.</p><p><strong>6. EKS creates its cluster and node group</strong> inside the VPC subnets. The OIDC provider is created, capturing the cluster’s identity URL.</p><p><strong>7. IAM module starts</strong> — it was waiting for module.eks.oidc_provider_arn. Now it has it and can create the IRSA role with the correct trust policy condition.</p><p><strong>8. All modules complete.</strong> Terraform prints the dev/outputs.tf values to the terminal — your live cluster endpoint, ECR URL, IRSA role ARN, everything you need for the next phase.</p><p>The entire infrastructure — VPC, EKS cluster, node group, ECR, IAM/IRSA, Secrets Manager — provisioned from a single terraform apply. Reproducible. Modular. Auditable.</p><h3>Why This Structure Matters for SRE Work</h3><p>In SRE we care deeply about reproducibility and auditability. Terraform modules give you both.</p><p>Every resource is described in code. Every change goes through terraform plan before it touches production. Every module is independently testable. When something goes wrong in production, you can look at the Terraform code and know exactly what exists and why.</p><p>The module pattern also enforces consistency. Your dev environment and prod environment call the same modules — only the variable values differ. The VPC topology is identical. The EKS configuration is identical. The IRSA setup is identical. The only difference is instance size, node count, and environment name.</p><p>That consistency is what makes runbooks reliable. “Restart the node group” is the same procedure in both environments because the architecture is the same.</p><h3>One Thing I Got Wrong Early On</h3><p>I initially tried to put everything in one giant main.tf file. No modules, no separation. It worked for a few resources.</p><p>Then I needed to reuse the same VPC setup in a second environment. I was copying and editing hundreds of lines. Then I needed to change the subnet CIDR scheme across all environments. I was doing find-and-replace across multiple files and missing things.</p><p>The module pattern isn’t complexity for its own sake. It’s the answer to “how do I manage this at scale without it becoming unmaintainable.” Once you build the module once, you call it as many times as you need with different variables. One change to the module propagates everywhere.</p><p>That’s the real value. Not the syntax. The leverage.</p><p><em>Currently building an open-source AIOps Reliability Platform on AWS — EKS, ArgoCD, OpenTelemetry, Chaos Engineering. Sharing every step as I build it. Follow along.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef72e5d551c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How IRSA Works With IAM and EKS — And Why You Should Never Hardcode AWS Credentials in a Pod]]></title>
            <link>https://medium.com/@machindra220/how-irsa-works-with-iam-and-eks-and-why-you-should-never-hardcode-aws-credentials-in-a-pod-3c4b55797d0e?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c4b55797d0e</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-iam]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 02:41:01 GMT</pubDate>
            <atom:updated>2026-09-28T02:41:01.672Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started working with Kubernetes on AWS, I did what most engineers do early on — I passed AWS credentials as environment variables into my pods. It worked. The app could talk to S3, call APIs, do what it needed to do.</p><p>Then I started thinking about what happens if someone gets into that container. Or if the image leaks. Or if a junior engineer accidentally commits the .env file. Suddenly that &quot;working&quot; solution felt like a ticking clock.</p><p>That’s when I properly learned IRSA — IAM Roles for Service Accounts — and it changed how I think about workload identity entirely.</p><h3>The Problem With Credentials in Pods</h3><p>Let me be direct about what hardcoding credentials actually means in practice:</p><pre># The wrong way — seen this in too many real codebases<br>env:<br>  - name: AWS_ACCESS_KEY_ID<br>    value: &quot;AKIAIOSFODNN7EXAMPLE&quot;<br>  - name: AWS_SECRET_ACCESS_KEY<br>    value: &quot;wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY&quot;</pre><p>These credentials are static. They don’t expire unless you manually rotate them. They have no scope — if that key has S3 access, anyone who gets hold of it has S3 access. And they’re sitting in your pod spec, potentially in your Git history, potentially in your container image layers.</p><p>This isn’t a theoretical risk. This is how AWS accounts get compromised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7crFt4lUa5VvTvGKVg_6A.png" /><figcaption>IRSA Concept wrong vs right</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBgqqRd83KDb7RyLN1Y80w.png" /><figcaption>IRSA Concept workflow</figcaption></figure><h3>What IRSA Actually Does</h3><p>IRSA is AWS’s answer to this problem. The core idea is simple: instead of giving your pod credentials, you give it an <em>identity and</em> let AWS figure out what that identity is allowed to do.</p><p>Here’s the mechanism in plain terms:</p><p>Your EKS cluster has an OIDC (OpenID Connect) provider. Think of it as a notary — it can sign certificates that say “yes, this token genuinely came from this Kubernetes cluster, from this specific service account, in this specific namespace.”</p><p>When your pod starts, Kubernetes automatically mounts a signed JWT token into the pod filesystem. No action needed from you. It just appears at /var/run/secrets/tokens/.</p><p>When your app (via the AWS SDK) needs to make an AWS API call, it takes that JWT token and sends it to AWS STS (Security Token Service) with a request: “I want to assume this IAM role.” STS checks two things — is the JWT signature valid (did it really come from your EKS OIDC provider?), and does the trust policy on the IAM role allow this specific service account to assume it?</p><p>If both checks pass, STS hands back temporary credentials — an access key, secret, and session token — valid for one hour. The AWS SDK uses those credentials automatically. No intervention from you.</p><p>One hour later, the SDK silently gets new credentials. You never manage rotation. You never store a secret.</p><h3>The Three Things You Configure</h3><p>Making IRSA work requires exactly three pieces. Get all three right and it just works.</p><p><strong>Piece 1 — Enable the OIDC provider on EKS</strong></p><p>This tells AWS to trust tokens signed by your EKS cluster:</p><pre>resource &quot;aws_iam_openid_connect_provider&quot; &quot;eks&quot; {<br>  url             = aws_eks_cluster.main.identity[0].oidc[0].issuer<br>  client_id_list  = [&quot;sts.amazonaws.com&quot;]<br>  thumbprint_list = [data.tls_certificate.eks.certificates[0].sha1_fingerprint]<br>}</pre><p>You do this once per cluster. After this, AWS knows your cluster exists and can verify tokens it issues.</p><p><strong>Piece 2 — Create an IAM role with a trust policy</strong></p><p>This is the most important part. The trust policy locks the role to one specific service account — not “any pod in the cluster”, not “any pod in this namespace”. One service account, one namespace.</p><pre>resource &quot;aws_iam_role&quot; &quot;app_irsa&quot; {<br>  name = &quot;sre-aiops-app-irsa-role&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Effect    = &quot;Allow&quot;<br>      Action    = &quot;sts:AssumeRoleWithWebIdentity&quot;<br>      Principal = {<br>        Federated = aws_iam_openid_connect_provider.eks.arn<br>      }<br>      Condition = {<br>        StringEquals = {<br>          &quot;${local.oidc_issuer}:sub&quot; = &quot;system:serviceaccount:default:sre-aiops-app&quot;<br>          &quot;${local.oidc_issuer}:aud&quot; = &quot;sts.amazonaws.com&quot;<br>        }<br>      }<br>    }]<br>  })<br>}</pre><p>The Condition block is the lock. It says: only allow this role to be assumed if the token&#39;s sub claim exactly matches system:serviceaccount:default:sre-aiops-app. Any other pod, any other service account — denied.</p><p>Then attach a permissions policy to the role with only what the app actually needs:</p><pre>resource &quot;aws_iam_role_policy&quot; &quot;app_permissions&quot; {<br>  role = aws_iam_role.app_irsa.id<br><br>  policy = jsonencode({<br>    Statement = [<br>      {<br>        Effect   = &quot;Allow&quot;<br>        Action   = [&quot;s3:GetObject&quot;, &quot;s3:PutObject&quot;]<br>        Resource = &quot;${aws_s3_bucket.app.arn}/*&quot;<br>      },<br>      {<br>        Effect   = &quot;Allow&quot;<br>        Action   = [&quot;secretsmanager:GetSecretValue&quot;]<br>        Resource = aws_secretsmanager_secret.app.arn<br>      }<br>    ]<br>  })<br>}</pre><p>Least privilege, scoped to exactly the resources this specific app touches.</p><p><strong>Piece 3 — Annotate the Kubernetes service account</strong></p><p>This is the link that connects the Kubernetes world to the AWS world. One annotation on the service account:</p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: sre-aiops-app<br>  namespace: default<br>  annotations:<br>    eks.amazonaws.com/role-arn: arn:aws:iam::502274764708:role/sre-aiops-app-irsa-role</pre><p>When EKS sees this annotation, it knows to inject the OIDC token into any pod using this service account. That’s it. The annotation is the binding between the K8s identity and the AWS identity.</p><h3>The Full Runtime Flow</h3><p>Here’s what actually happens when your pod makes an AWS API call, traced end to end:</p><ol><li>Pod starts → K8s mounts a signed JWT into the pod at a well-known path</li><li>AWS SDK in your app reads the JWT automatically (it knows where to look)</li><li>SDK calls sts:AssumeRoleWithWebIdentity with the JWT + the role ARN from the annotation</li><li>STS verifies the JWT signature using the OIDC provider’s public key</li><li>STS checks the role’s trust policy — does this service account match the condition?</li><li>Match → STS returns temporary credentials (valid 1 hour)</li><li>SDK uses those credentials to call S3, Bedrock, Secrets Manager, whatever</li><li>One hour later → SDK silently repeats steps 2–7 in the background</li></ol><p>From your application code’s perspective, nothing changes. You still use the standard AWS SDK. The SDK handles the IRSA token exchange transparently via the credential provider chain. You write zero authentication code.</p><h3>Why This Matters for Production SRE Work</h3><p>The operational properties of IRSA are what make it genuinely valuable at scale:</p><p><strong>No secrets to rotate.</strong> Credentials expire after an hour automatically. You don’t need a secrets rotation Lambda, you don’t need reminders to rotate IAM keys, you don’t need to coordinate a secret change across teams.</p><p><strong>Blast radius is contained.</strong> If a pod is compromised, the attacker gets one-hour credentials scoped to exactly what that service account is allowed to do. Compare that to a long-lived access key that could do anything the IAM user can do.</p><p><strong>Full audit trail.</strong> Every AWS API call made through an IRSA role appears in CloudTrail tagged with the role ARN. You know exactly which workload made which call, when, and what it did.</p><p><strong>No drift between environments.</strong> Instead of managing different .env files for dev, staging, and prod, each environment has its own OIDC provider and IAM roles. The application code is identical across environments.</p><p><strong>Compliance-friendly.</strong> Most compliance frameworks (SOC2, ISO 27001, PCI) require credential rotation and access logging. IRSA gives you both by default, without any extra tooling.</p><h3>Common Mistakes I’ve Seen</h3><p><strong>Forgetting the OIDC thumbprint.</strong> The thumbprint_list in the OIDC provider resource is easy to miss. Without it, the provider registration fails. Use data.tls_certificate to fetch it dynamically in Terraform rather than hardcoding it.</p><p><strong>Too-broad trust policy conditions.</strong> I’ve seen trust policies that use StringLike with wildcards instead of StringEquals. That means any service account matching the pattern can assume the role. Always use StringEquals and be explicit about the exact namespace and service account name.</p><p><strong>Not setting </strong><strong>fsGroup in the pod security context.</strong> The projected token volume needs the right filesystem permissions. If your pod runs as a non-root user (which it should), set fsGroup in the pod spec so the token file is readable.</p><p><strong>Reusing one IRSA role across multiple services.</strong> It’s tempting to create one “app” role. Don’t. One role per service. The blast radius argument applies here — if the order service and the payment service share a role, a compromise of either affects both.</p><h3>Wrapping Up</h3><p>IRSA isn’t complicated once you see it clearly — it’s a token exchange. Kubernetes vouches for the pod’s identity, AWS STS validates that voucher, and hands back temporary credentials. The three pieces (OIDC provider, IAM trust policy, service account annotation) are the wiring that makes it work.</p><p>If you’re running workloads on EKS and still using static IAM user credentials, this is the single highest-impact security improvement you can make. It costs nothing extra, requires no additional services, and eliminates an entire category of credential-related risk.</p><p>In my current build — an AIOps Reliability Platform on AWS — IRSA is a non-negotiable foundation. Every service that touches AWS has its own scoped role. Zero static credentials anywhere in the cluster.</p><p>That’s how production security should work.</p><p><em>Building a production-grade SRE platform on AWS with EKS, ArgoCD, OpenTelemetry, and Chaos Engineering. Follow along for more posts on real SRE practices.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c4b55797d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-powered SRE Agent — a LangGraph-based system that automatically triages production alerts]]></title>
            <link>https://medium.com/@machindra220/ai-powered-sre-agent-a-langgraph-based-system-that-automatically-triages-production-alerts-66f342f19623?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f342f19623</guid>
            <category><![CDATA[ai-observability]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 15:09:46 GMT</pubDate>
            <atom:updated>2026-09-13T15:09:46.976Z</atom:updated>
            <content:encoded><![CDATA[<p>Building something I’m genuinely excited about. 🚀</p><p>I’m working on an AI-powered SRE Agent — a LangGraph-based system that automatically triages production alerts, retrieves the right runbook using RAG, and generates structured Root Cause Analysis reports using Gemini LLM.</p><p>Here’s the full stack:</p><p>🧠 LangGraph — 4-node agentic pipeline<br>↳ alert_parser → runbook_retriever → diagnoser → rca_writer</p><p>📚 RAG Pipeline<br>↳ fastembed (BAAI/bge-small-en-v1.5) for local embeddings<br>↳ pgvector (PostgreSQL) as the vector database<br>↳ 19 runbook chunks indexed and searchable by semantic similarity</p><p>🤖 Gemini gemini-3.6-flash for LLM reasoning<br>↳ Returns structured JSON: root_cause, evidence, steps, confidence</p><p>📊 FastAPI with ddtrace → Datadog APM<br>↳ Every triage call traced end-to-end<br>↳ HTML RCA reports with confidence badges (green/amber/red)</p><p>Real results so far:<br>✅ Pod Restart (OOMKilled) → 95% confidence, correct runbook retrieved<br>✅ High Error Rate → api-5xx.md retrieved correctly<br>✅ High Latency → high-latency.md retrieved correctly<br>✅ API Availability → api-availability.md retrieved correctly</p><p>What’s next (Phase 20):<br>↳ LLM evals with ragas (answer relevance, faithfulness, context recall)<br>↳ Prometheus metrics for AI quality scores<br>↳ Grafana dashboard for AI observability</p><p>This project is built to demonstrate real agentic AI skills for SRE and AI Platform Engineering roles — not just tutorials, but a working system that produces real SRE artifacts.</p><p>🔗 Repo: <a href="https://github.com/Machindra220/SRE-AI-Agent-Observability">https://github.com/Machindra220/SRE-AI-Agent-Observability</a></p><p>Would love feedback from anyone working in AIOps, SRE, or AI Platform Engineering! 🙌</p><p>#SRE #AIOps #LangGraph #RAG #pgvector #Gemini #AIObservability #Python #FastAPI #LLM #AIAgent</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f342f19623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Giving AI Agents a Long-Term Memory: An SRE’s Guide to RAG and Vector Databases]]></title>
            <link>https://medium.com/@machindra220/giving-ai-agents-a-long-term-memory-an-sres-guide-to-rag-and-vector-databases-ba129c896d22?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba129c896d22</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-08-05T13:01:02.187Z</atom:updated>
            <content:encoded><![CDATA[<p>In [Phase 1], we transformed Large Language Models (LLMs) from passive chatbots into active workers by giving them <strong>Tools</strong>. But as any Site Reliability Engineer knows, tools are useless if you don’t have the context or runbooks to know <em>when</em> and <em>how</em> to use them.</p><p>Standard LLMs suffer from two major memory constraints:</p><ol><li><strong>Training Cutoffs:</strong> They don’t know your private company code, real-time infrastructure status, or internal post-mortems.</li><li><strong>Context Window Limits:</strong> You cannot feed a 500-page internal SRE runbook into every prompt without incurring massive latency, skyrocketing token costs, or exceeding context limits.</li></ol><p>To solve this, we give AI agents two distinct types of memory using <strong>Retrieval-Augmented Generation (RAG)</strong> and <strong>Vector Databases</strong>.</p><h3>1. Short-Term vs. Long-Term Memory in AI</h3><p>Understanding how AI stores and retrieves information starts with distinguishing between short-term and long-term memory:</p><p><strong>Short-Term Memory (The Context Window):</strong></p><ul><li><strong>What it is:</strong> The active text payload passed in a single API request (including recent chat history).</li><li><strong>Importance:</strong> Allows the agent to maintain a coherent conversation and remember immediate context during a single session.</li><li><strong>Limitation:</strong> Ephemeral and expensive. Once the session ends or the context window fills up, that information is lost or truncated.</li></ul><p><strong>Long-Term Memory (Vector Databases &amp; RAG):</strong></p><ul><li><strong>What it is:</strong> External persistent storage where millions of documents, runbooks, and historical incidents are indexed mathematically.</li><li><strong>Importance:</strong> Enables agents to query vast institutional knowledge instantly on demand, without polluting the context window with irrelevant data.</li></ul><h3>2. The 4-Step RAG Pipeline Mechanics</h3><p><strong>Retrieval-Augmented Generation (RAG)</strong> bridges long-term memory with the LLM’s short-term context window through a four-step pipeline:</p><pre>[ Raw Document 📄 ] ──► [ 1. Chunking 🧩 ] ──► [ 2. Embedding 🔢 ] ──► [ 3. Vector DB Search 🗄️ ] ──► [ 4. Prompt Injection 💡 ]</pre><h3>Step 1: Document Chunking</h3><ul><li><strong>Explanation:</strong> Breaking massive documents down into smaller, logical text blocks (e.g., 200–500 words).</li><li><strong>Importance:</strong> If a chunk is too large, it dilutes search accuracy. If it’s too small, critical troubleshooting context gets severed. In SRE, chunking by logical headers (e.g., ### OOM Killer Mitigation) ensures an entire incident resolution procedure stays intact.</li></ul><h3>Step 2: Vector Embeddings</h3><ul><li><strong>Explanation:</strong> Passing text chunks through an embedding model to convert words into numerical vectors (e.g., [0.023, -0.412, 0.891, ...]).</li><li><strong>Importance:</strong> Vectors represent <strong>semantic meaning</strong> rather than exact keywords. Searching for &quot;high memory usage&quot; can successfully retrieve a chunk titled &quot;Out of Memory (OOM) Management&quot; because their vectors sit close together in mathematical space.</li></ul><h3>Step 3: Vector Storage &amp; Spatial Search</h3><ul><li><strong>Explanation:</strong> Storing vectors in specialized databases (like ChromaDB or Qdrant) and calculating the distance/angle between them using <strong>Cosine Similarity</strong>.</li><li><strong>Importance:</strong> Allows the system to query millions of document chunks in milliseconds and retrieve only the top $K$ most relevant matches to the user’s prompt.</li></ul><h3>Step 4: Prompt Context Injection</h3><ul><li><strong>Explanation:</strong> Pasting <em>only</em> the top retrieved text chunks into the prompt behind the scenes before sending it to the LLM.</li><li><strong>Importance:</strong> Grounding the LLM’s answer in your exact documentation, keeping token usage low and responses fast.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnXNcp5xKEPqISCU_4ctfA.png" /></figure><h3>3. SRE Reliability &amp; Verification Layers</h3><p>In production, returning bad or irrelevant context from a vector search leads directly to LLM <strong>hallucinations</strong>. To make RAG reliable for critical infrastructure, we implement strict guardrails:</p><ul><li><strong>Similarity Thresholds:</strong> Setting a hard score cutoff (e.g., minimum 0.75 similarity). If no chunks meet this score, the retrieval step fails early.</li><li><strong>Re-ranking Models:</strong> Running a secondary scoring pass over top results to ensure retrieved paragraphs directly address the user’s explicit question.</li><li><strong>Graceful Degradation:</strong> If relevant internal runbooks are not found, the agent explicitly declines to answer and escalates to an on-call engineer rather than guessing.</li></ul><h3>4. Open-Source vs. AWS Enterprise Architecture</h3><p>Here is how our Phase 2 open-source components map directly to managed AWS cloud infrastructure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBtE3wHsV_-KAVaAsfGpqw.png" /><figcaption>Table: Open-Source Components and AWS Enterprise Components</figcaption></figure><h3>What’s Next?</h3><p>With <strong>Tools</strong> (Phase 1) and <strong>Memory</strong> (Phase 2) established, we are ready to combine multiple specialized agents into collaborative workflows!</p><p>let’s step into <strong>Phase 3: Multi-Agent Systems &amp; Complex Workflows</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba129c896d22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Passive LLMs to Autonomous AI Agents: An SRE’s Guide to Building Reliable Tool-Calling Systems]]></title>
            <link>https://medium.com/@machindra220/from-passive-llms-to-autonomous-ai-agents-an-sres-guide-to-building-reliable-tool-calling-systems-cbb9809d2ba8?source=rss-25ec73d0c597------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb9809d2ba8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Machindranath Wagare]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 07:08:55 GMT</pubDate>
            <atom:updated>2026-08-02T07:08:55.917Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started my AI learning journey, I used to think Large Language Models (LLMs) like ChatGPT were all-knowing digital assistants. But coming from a Site Reliability Engineering (SRE) background, I quickly realized a fundamental limitation: <strong>An LLM is just a brain in a jar.</strong></p><p>It can generate brilliant text, write complex code, and summarize logs. But on its own, an LLM cannot interact with the real world. It cannot execute a ping command, check server CPU usage, or restart a failing container.</p><p>To cross that bridge from <em>passive chatbot</em> to <em>active worker</em>, we need to build <strong>AI Agents</strong> 🤖.</p><p>In this first post of my AI learning series, I’m breaking down the absolute fundamentals of how AI Agents work under the hood, how they call external tools, and how we can apply core SRE reliability principles to keep them from breaking in production.</p><h3>1. What is an AI Agent?</h3><p>At its simplest level, an <strong>AI Agent</strong> takes a standard language model and equips it with three extra components:</p><ul><li><strong>The Brain (LLM) :</strong> Processes user requests and decides what to do next.</li><li><strong>Tools (Functions/APIs) :</strong> External Python scripts or web services that execute actual work.</li><li><strong>Memory :</strong> Tracks context and past actions across multiple steps.</li><li><strong>Planning Loop :</strong> A strategy to break complex tasks down step-by-step.</li></ul><h3>AI Agent = LLM + Tools + Memory + Planning Loop</h3><h3>2. The Big Misconception: Who Actually Runs the Code?</h3><p>When beginners hear that an “AI Agent runs a tool,” they often assume the LLM model executes Python code on its servers. <strong>This is false.</strong></p><p>Here is what actually happens:</p><pre>def check_cpu_usage() -&gt; str:<br>    &quot;&quot;&quot;Checks and returns the local server&#39;s current CPU usage percentage.&quot;&quot;&quot;<br>    return f&quot;CPU Usage: {psutil.cpu_percent()}%&quot;</pre><ol><li><strong>You define a Python tool</strong> with a clear description (docstring):</li><li><strong>Your code translates this function into a JSON Schema.</strong> This schema describes the tool’s name, purpose, and required parameters to the LLM.</li><li><strong>The LLM reads your prompt and selects a tool.</strong> Instead of running code, the LLM simply responds with a structured JSON request asking <em>your application</em> to run that function: “check_cpu_usage”.</li><li><strong>Your local Python app executes the function</strong> and feeds the resulting string back to the LLM.</li></ol><pre>{<br>  &quot;tool_to_call&quot;: &quot;check_cpu_usage&quot;,<br>  &quot;arguments&quot;: {}<br>}</pre><p>The LLM is strictly the <strong>decision maker</strong>. Your local application remains the <strong>executor</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgsqUqC2QZ__F3l2zjGz_A.png" /></figure><h3>3. The ReAct Pattern: Reason ➔ Act ➔ Observe</h3><p>To handle complex tasks, agents follow the <strong>ReAct (Reasoning + Acting)</strong> execution loop:</p><pre>[ User Request ] ➔ [ LLM Reasoning ] ➔ [ Action: Call Tool ]<br>                                                     │<br>[ Final Response ] 🏃 [ Read Result ] 🏃 [ Local Function Runs ]</pre><ul><li><strong>Thought:</strong> <em>“The user asked why the server is slow. I should check CPU usage first.”</em></li><li><strong>Action:</strong> Output a tool call request for check_cpu_usage.</li><li><strong>Observation:</strong> Read the result returned by local Python (CPU Usage: 94%).</li><li><strong>Final Answer:</strong> <em>“The server is slow because CPU utilization is currently at 94%.”</em></li></ul><h3>4. Hardening AI Tools with SRE Principles</h3><p>In production, tools fail. External APIs hang, databases time out, and services crash. If an agent calls a hanging tool without protection, the entire workflow freezes.</p><p>To make agentic tools production-ready, we apply three standard reliability patterns:</p><ul><li><strong>Timeouts ⏱️:</strong> Never let a tool wait indefinitely. Enforce hard limits (e.g., 5 seconds) on external network calls.</li><li><strong>Exponential Backoff 🔄:</strong> If an API call fails due to temporary network blips, retry with gradually increasing delays.</li><li><strong>Circuit Breakers ⚡:</strong> If a downstream tool fails consistently, “trip” the circuit breaker to fail fast immediately, saving local CPU and preventing traffic overload on the recovering service.</li></ul><h3>5. Connecting Open-Source to AWS Architecture ☁️</h3><p>If you are building on AWS, these open-source concepts map directly to managed cloud infrastructure:</p><p><strong>Open-Source Tooling 🐍 || Managed AWS Equivalent ☁️</strong></p><p>Ollama / Llama 3 =&gt; <strong>Amazon Bedrock</strong></p><p>LangChain Agent Loop =&gt; <strong>Amazon Bedrock Agents</strong></p><p>Local Python Tool =&gt; <strong>AWS Lambda</strong></p><h3>What’s Next?</h3><p>Understanding tool calling and reliability completes <strong>Phase 1</strong> of my journey! In next Phase, we will explore <strong>Vector Databases</strong> and <strong>Retrieval-Augmented Generation (RAG)</strong> to give our agents long-term memory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb9809d2ba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>