<?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 Gaurang Malvankar on Medium]]></title>
        <description><![CDATA[Stories by Gaurang Malvankar on Medium]]></description>
        <link>https://medium.com/@mgaurang123?source=rss-80c27f6cc0d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*21fnf1SmwF8PfCc7</url>
            <title>Stories by Gaurang Malvankar on Medium</title>
            <link>https://medium.com/@mgaurang123?source=rss-80c27f6cc0d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:48:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mgaurang123/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[Tokenmaxxing Claude Code: The Setup I Actually Use (And What I Skip)]]></title>
            <link>https://medium.com/@mgaurang123/tokenmaxxing-claude-code-the-setup-i-actually-use-and-what-i-skip-e9fe0343c0fb?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9fe0343c0fb</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tokenmaxxing]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 07:25:41 GMT</pubDate>
            <atom:updated>2026-11-28T07:25:41.266Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Read this first.</em></strong><em> This is my personal Claude Code usage pattern, not a universal recipe. You will find a lot of plugins, skills and “ultimate setups” online that are unnecessary, irrelevant to your work, and will eat your usage limits in a few prompts. This post stays away from the gimmicky stuff. The goal is </em><strong><em>tokenmaxxing</em></strong><em>: getting the maximum useful engineering output per token, not burning the maximum number of tokens.</em></blockquote><blockquote><strong><em>One more thing.</em></strong><em> None of this works if you do not understand the language, the project and the technology you are working in. Tokens are leverage on top of your knowledge. They do not replace it. Vibe coding is for people who do not understand the technology and just want to ride the AI wave. Everything below assumes you can read the diff, spot the wrong assumption, and tell the model when it is heading the wrong way.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWNRehQa6arSad8oteNV2A.png" /></figure><h3>The Problem: Most Tokens Are Wasted, Not Used</h3><p>If you hit your Claude Code limits early, the cause is rarely “I did too much real work”. It is usually one of these:</p><ul><li><strong>Context bloat.</strong> Every message re-sends the conversation so far. A long, wandering chat gets more expensive with every turn, and the model also gets worse as it fills with stale detail.</li><li><strong>Noisy tool output.</strong> git status, npm test, find, and kubectl logs dump hundreds of lines the model does not need.</li><li><strong>Verbose replies.</strong> Preamble, restated questions, closing summaries.</li><li><strong>Over-engineering.</strong> The model writes 300 lines where 30 would do, and then you spend more tokens reviewing and deleting.</li><li><strong>Exploration by grep.</strong> The model reads file after file to figure out how your codebase fits together, every single session.</li><li><strong>Vague prompts.</strong> Three rounds of clarification cost more than one good prompt.</li><li><strong>Always-on tooling.</strong> Every plugin and skill adds instructions to every request, whether you use it or not.</li></ul><p>Tokenmaxxing is attacking each of these directly, with the smallest number of moving parts.</p><pre>| Where tokens leak            | What fixes it                                    |<br>| ---------------------------- | ------------------------------------------------ |<br>| Noisy command output         | `rtk` (hook)                                     |<br>| Verbose replies              | `caveman` + `CLAUDE.md` answer style             |<br>| Over-built code              | `ponytail` + `karpathy-guidelines`               |<br>| Codebase exploration         | `graphify`                                       |<br>| Re-explaining the project    | `claude-mem`                                     |<br>| Stale / hallucinated APIs    | `context7`                                       |<br>| Long wandering chats         | One problem per chat, `/clear`                   |<br>| Vague prompts                | Prompt template                                  |<br>| Expensive model on easy work | Sonnet for routine tasks, Opus for complex tasks |</pre><h3>The Setup, Point by Point</h3><h4>1. Model: Opus 5.5 at medium effort, Sonnet for routine work</h4><p>Model choice is the biggest single lever on your limits, and it is free.</p><ul><li><strong>Opus 5.5 at medium effort</strong> is my default for work where reasoning quality matters: debugging across services, design decisions, reviewing a risky change.</li><li><strong>Sonnet</strong> handles routine work: boilerplate, small refactors, writing tests for an existing function, config edits, renaming things. Using it here stretches your limits significantly.</li><li><strong>Medium effort, not max.</strong> Higher reasoning effort means more thinking tokens. Most tasks do not need it. Raise it deliberately for the hard 10%, not by default for everything.</li></ul><p>The rule: if you could explain the change to a junior engineer in two sentences, it does not need your most expensive model.</p><h4>2. Plugins: caveman, ponytail, claude-mem, context7</h4><p>Four tools. Each one targets a specific leak. Each one also has a cost, and I will say what it is.</p><h4>caveman: shorter replies</h4><p>Caveman is a plugin/skill that makes the model answer in compressed prose: no filler, no pleasantries, fragments instead of paragraphs, while code, commands and errors stay exact.</p><ul><li><strong>What it saves:</strong> output tokens. The project reports about 65% on average across its benchmark prompts, with a wide range (roughly 22% to 87%) depending on the task.</li><li><strong>What it does not touch:</strong> thinking tokens, and your input context. It only shortens what the model writes back.</li><li><strong>Bonus:</strong> a caveman-compress sub-skill rewrites memory files like CLAUDE.md so every session starts with a smaller context.</li><li><strong>Cost:</strong> it adds its own instructions to each request, so on very short exchanges the saving shrinks.</li></ul><h4>ponytail: stop the over-engineering</h4><p>Ponytail is a minimalism plugin. It injects rules that push the agent toward the smallest change that works: reuse existing code, skip speculative abstractions, no new dependency when the platform already does it. The classic example is a date picker: instead of a custom component, the answer is an &lt;input type=&quot;date&quot;&gt;.</p><ul><li><strong>What it saves:</strong> the tokens spent generating code you did not need, and the tokens you spend reviewing and deleting it later. Less code also means less to maintain.</li><li><strong>Where the numbers come from:</strong> the project publishes its own benchmarks (large reductions in code size and cost on a FastAPI + React repo). Treat those as the author’s numbers, measure on your own codebase.</li><li><strong>Cost:</strong> shortcuts are marked in code, so you need to actually review them. It biases toward “small”, which is wrong when you genuinely need the abstraction.</li></ul><h4>claude-mem: do not re-explain your project every session</h4><p>Claude-mem hooks into the Claude Code lifecycle. It records what happens during a session, compresses it into structured observations, stores them in a local SQLite database, and injects a compact index of recent work into the next session.</p><ul><li><strong>What it saves:</strong> the first ten minutes of every session where you re-explain the architecture and the model re-reads files it already analyzed.</li><li><strong>Runs automatically:</strong> because it is a plugin using lifecycle hooks and not an MCP server the model has to remember to call, capture does not depend on the model’s judgment.</li><li><strong>Cost and caveats:</strong> it injects context at the start of every session, so noisy memory costs tokens. It runs a local background worker. <strong>Check the license before using it at work.</strong> At the time of writing it is not plain MIT, and a licence with non-commercial terms is a real problem inside a company.</li></ul><h4>context7: stop hallucinated APIs</h4><p>Context7 is an MCP server from Upstash that fetches current, version-specific library documentation and puts it into the prompt. It exposes two tools: one to resolve a library name to an ID, one to query its docs.</p><ul><li><strong>What it saves:</strong> the debug loop caused by the model confidently using an API that was renamed, deprecated, or never existed. One wrong-API round trip costs more than the docs lookup.</li><li><strong>Where it matters:</strong> fast-moving frameworks. Next.js, Spring Boot majors, FastAPI, anything with a breaking release in the last year or two.</li><li><strong>Cost:</strong> MCP tool definitions sit in context, and fetched docs are tokens too. Use it when the library moves fast, not for the standard library.</li></ul><h4>3. Skills: graphify and karpathy-guidelines</h4><h4>graphify: query the codebase instead of grepping it</h4><p>Graphify turns a folder (code, docs, configs) into a knowledge graph you can query. Code is parsed locally with tree-sitter AST analysis, so no model tokens are spent on the structure. It produces a graph, an interactive HTML view, and a GRAPH_REPORT.md listing the central nodes (&quot;god nodes&quot;) and communities.</p><ul><li><strong>What it saves:</strong> the exploration phase. Instead of the model reading ten files to learn how APIRouter connects to everything else, it asks the graph.</li><li><strong>Best fit:</strong> medium to large codebases you work in repeatedly. On a 5-file script it is pure overhead.</li><li><strong>Cost:</strong> you must keep the graph fresh after significant changes. Non-code assets (docs, PDFs, images) go through the model for extraction, which costs tokens, so scope what you feed it.</li></ul><pre>Without graph:   question -&gt; grep -&gt; read file -&gt; grep -&gt; read file -&gt; ... -&gt; answer<br>With graph:      question -&gt; read GRAPH_REPORT.md / query graph -&gt; read 1-2 files -&gt; answer</pre><h4>karpathy-guidelines: behavior, not capability</h4><p>This is a meta-skill, derived from Andrej Karpathy’s observations on LLM coding failure modes. It does not do a task. It constrains how the model approaches every task. Four ideas:</p><ol><li><strong>Think before coding.</strong> State assumptions, surface tradeoffs, ask when ambiguous.</li><li><strong>Simplicity first.</strong> Nothing speculative, no abstractions for single-use code.</li><li><strong>Surgical changes.</strong> Touch only what the request needs. No drive-by refactors.</li><li><strong>Goal-driven execution.</strong> Turn the task into verifiable success criteria so the model can loop on its own (“make the test pass”, not “make it work”).</li></ol><ul><li><strong>What it saves:</strong> rework. A diff that touches 15 unrelated lines costs review time and tokens to undo.</li><li><strong>Cost:</strong> it biases toward caution over speed. On trivial tasks that is mild overhead.</li></ul><blockquote><strong><em>Honest note on overlap.</em></strong><em> Caveman, ponytail, karpathy-guidelines, and my own </em><em>CLAUDE.md answer-style rules all push in the same direction: be brief, be minimal, do not over-build. That is deliberate reinforcement, but it is also redundancy, and each layer has an instruction cost. If you are building your own setup, add one at a time and measure. Do not install all four because a blog told you to.</em></blockquote><h4>4. Hooks: rtk and the graphify nudge</h4><p>Hooks run automatically at points in the Claude Code lifecycle. They are the cheapest kind of optimization, because they cost zero tokens until they fire.</p><h4>rtk (Rust Token Killer)</h4><p>A single Rust binary that sits between the shell and the model. When Claude runs a Bash command, a hook rewrites it (git status becomes rtk git status), and the output is filtered, grouped, truncated and de-duplicated before it enters the context window.</p><ul><li><strong>What it saves:</strong> the project reports 60 to 90% on common dev commands, for example around 150k tokens down to around 45k in a typical 30-minute session. Those are the project’s own estimates for medium-sized projects, so your mileage will vary. rtk gain shows your actual savings.</li><li><strong>Good fits for my stack:</strong> test runners (failures only), linters, git, container and Kubernetes log output.</li><li><strong>Limitation:</strong> the hook only fires on Bash tool calls. Claude Code’s built-in Read, Grep and Glob tools bypass it.</li><li><strong>Gotcha:</strong> there is another unrelated crate called rtk (Rust Type Kit). If rtk gain does not work, you installed the wrong one.</li></ul><h4>graphify hook</h4><p>A PreToolUse hook that fires before search operations. If a graph exists, it reminds the model to read the graph report before searching raw files. It nudges behavior instead of forcing it, which is what you want: the model can still ignore it when the graph is irrelevant.</p><h4>5. Instructions: one global CLAUDE.md</h4><p>My CLAUDE.md is global and it does two jobs: it defines the answer style (lead with the conclusion, no filler, no closing recap on short answers, flag tradeoffs early), and it pulls in RTK.md so the model knows about the rtk behavior.</p><p>Why global and not per-repo:</p><ul><li>The style rules apply everywhere, so one file beats twenty copies drifting apart.</li><li>Per-repo CLAUDE.md files get loaded every session in that repo. Keeping them out of the repos means nothing gets loaded that I did not choose.</li></ul><p><strong>The tradeoff you accept:</strong> project-specific conventions are not versioned with the repo, and teammates do not get them. I compensate with the prompt template below, which carries the project-specific context in each task. For a team of 20 that wants shared conventions, a small committed CLAUDE.md is a reasonable choice. My approach is a personal one.</p><h4>6. Commits and PRs: no Claude credit text</h4><p>Claude Code appends a co-author line to commits and a generated-with line to PRs by default. I turn both off in settings.json.</p><p>This is not about hiding the tooling. Those lines are noise in git log and PR descriptions, and in a team repo the commit history is a long-lived contract. Review accountability sits with the human who opened the PR, whichever tool wrote the first draft. Check your team&#39;s policy on AI disclosure before copying this.</p><h4>7. Repos: no .claude folders, no CLAUDE.md</h4><p>Everything comes from the global setup. The repos stay clean. This pairs with point 5: no hidden per-repo agent configuration, nothing to maintain across many services, nothing a teammate has to wonder about.</p><h3>The Habits That Matter More Than Any Plugin</h3><p>Plugins save a percentage. Habits save multiples. In my experience the five habits below are worth more than everything above combined.</p><p><strong>1. One problem per chat.</strong> A chat is a context window, and a context window is a cost that grows every turn. One task, one chat.</p><p><strong>2. New chat or </strong><strong>/clear every time you switch tasks.</strong> This is the single biggest saving, and in my usage it is about half of the effect. Old context from a finished task is pure drag on the next one.</p><p><strong>3. Think before you prompt.</strong> Spend a minute working out what you want. A rough analysis from you (“probably the IV is missing”) is worth more than three rounds of model exploration.</p><p><strong>4. Ask for proof.</strong> Require file:line, the exact output, or the exact error. It stops confident guessing and it makes review fast.</p><p><strong>5. Turn off what you do not use.</strong> Skill and plugin listings are part of every request. In my setup they added up to roughly 15k tokens per request. Audit them. If you have not invoked it in two weeks, disable it.</p><h3>The Prompt Template</h3><p>Structure beats cleverness. This template gets the model to the right answer in one pass because it carries the context that a repo-level CLAUDE.md would otherwise provide.</p><pre>Task: &lt;one line: what needs to happen&gt;<br>Type: bug | feature | change<br><br>Expected: &lt;what should happen / end result&gt;<br>Current:  &lt;what happens now, or &quot;doesn&#39;t exist yet&quot;&gt;<br><br>Where: &lt;files, functions, endpoints involved&gt;<br>Inputs/outputs: &lt;request, payload, response, status code, sample data&gt;<br>Evidence: &lt;exact error, logs, screenshot&gt; (bugs)<br>Constraints: &lt;must not break X, use library Y, match existing pattern Z&gt;<br>My analysis: &lt;your rough guess at cause or approach&gt;<br>Done when: &lt;how we verify: test passes, endpoint returns 200, UI shows X&gt;</pre><p><strong>Example: bug</strong></p><pre>Task: Fix payment link generation<br>Type: bug<br>Expected: Frontend gets 200 + valid payment URL.<br>Current: Frontend gets 500 + {&quot;error&quot;:&quot;Decryption failed&quot;}.<br>Where: generatePaymentLink() in services/payment.ts, POST /api/payment-link<br>Inputs/outputs: Request {orderId: 123, amount: 500} -&gt; 500 response<br>Evidence: &quot;Error: Invalid IV length&quot; in server logs<br>My analysis: Encryption may be missing the IV, or PAYMENT_SECRET env var isn&#39;t loading.<br>Done when: POST /api/payment-link returns 200 with a working URL.</pre><p><strong>Example: feature</strong></p><pre>Task: Add payment link expiry<br>Type: feature<br>Expected: Links expire after 24h; expired link returns 410 + message.<br>Current: Links never expire.<br>Where: generatePaymentLink() in services/payment.ts, GET /pay/:id<br>Constraints: Don&#39;t change existing link format.<br>My analysis: Store expiresAt on the link record, check it in GET /pay/:id.<br>Done when: Link older than 24h returns 410.</pre><p>Notice what each field does:</p><ul><li><strong>Where</strong> removes the exploration phase (this is what graphify does at the codebase level).</li><li><strong>Evidence</strong> removes the guessing.</li><li><strong>Constraints</strong> replace the per-repo CLAUDE.md.</li><li><strong>My analysis</strong> lets the model confirm or challenge your hypothesis instead of starting cold. This is also where your knowledge of the stack pays off.</li><li><strong>Done when</strong> is the karpathy-guidelines idea of a verifiable goal, written by you.</li></ul><h3>DOs and DON’Ts</h3><p><strong>DO</strong></p><ul><li>Measure before and after. rtk gain, caveman&#39;s stats, and your plan&#39;s usage view tell you what is working.</li><li>Add tools one at a time and keep only what shows a measurable benefit.</li><li>Use Sonnet for routine work and save the heavier model for hard problems.</li><li>Review every diff. Fewer tokens does not mean fewer bugs.</li><li>Check the license of every plugin before using it on company code.</li><li>Put project-specific context in the prompt when you choose not to keep it in the repo.</li></ul><p><strong>DON’T</strong></p><ul><li>Don’t install a plugin because it is popular. Install it because you can name the leak it fixes.</li><li>Don’t stack five tools that all do the same job.</li><li>Don’t run long, multi-topic chats.</li><li>Don’t use max effort by default.</li><li>Don’t accept “it should work” without evidence.</li><li>Don’t hand work to the model in a stack you cannot review. That is vibe coding, and it is where the expensive bugs come from.</li></ul><h3>Conclusion</h3><p>Tokenmaxxing is not a plugin list. It is a discipline: keep context small, keep output tight, keep changes minimal, and give the model precise instructions so it does the work once.</p><p>My setup is small on purpose. A model split (Opus at medium, Sonnet for routine), four plugins aimed at specific leaks, two skills that shape behavior and codebase navigation, two hooks that cost nothing until they fire, and one global CLAUDE.md. On top of that sit five habits and a prompt template. If you could only take one thing from this post, take the habits: one problem per chat, /clear when you switch, and a structured prompt.</p><p>And remember what makes it all work. The model is fast, but you are the one who knows whether the answer is right. Understand your language, your project and your technology first. Then the tokens multiply your skill instead of covering for its absence.</p><p><em>Want to go deeper? Check out </em><a href="https://github.com/rtk-ai/rtk"><em>rtk</em></a><em>, </em><a href="https://github.com/JuliusBrussee/caveman"><em>caveman</em></a><em>, </em><a href="https://github.com/DietrichGebert/ponytail"><em>ponytail</em></a><em>, </em><a href="https://github.com/thedotmack/claude-mem"><em>claude-mem</em></a><em>, </em><a href="https://github.com/upstash/context7"><em>context7</em></a><em>, </em><a href="https://github.com/Graphify-Labs/graphify"><em>graphify</em></a><em> and the </em><a href="https://github.com/forrestchang/andrej-karpathy-skills"><em>Karpathy guidelines skill</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9fe0343c0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes for Dummies: A Practical Guide for Backend Developers]]></title>
            <link>https://medium.com/@mgaurang123/kubernetes-for-dummies-a-practical-guide-for-backend-developers-71a0fae0be1d?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a0fae0be1d</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 07:22:55 GMT</pubDate>
            <atom:updated>2026-10-25T07:22:55.461Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve written a solid Python service. It has tests, a Dockerfile, and it runs fine on your laptop. Then someone asks you to run it in production with 3 replicas, zero downtime deploys, automatic restarts when it crashes, and the ability to scale up during traffic spikes. You also have to do this for the 40 other services your team owns.</p><p>Kubernetes was built for this problem.</p><p>This guide covers what people did before Kubernetes, why it exists, how its architecture works, which objects you’ll use every day, and how tools like Helm and Argo CD fit around it. It ends with real Python and Go code and a checklist of topics that come up in DevOps and SRE interviews.</p><p>It assumes you know containers and backend development. It does not assume you’ve run a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYyJPc-V4_EUmCs7-R6d5w.png" /></figure><h3>Life Before Kubernetes</h3><p>Deployment has gone through several eras, and each one fixed the previous era’s biggest pain.</p><h4>Bare metal and “pet” servers</h4><p>Applications ran directly on physical servers. Each server had a name and its own history of hand-applied config changes, and someone on the team remembered which one ran the billing job. If a server died, someone got paged at 3 AM to rebuild it by hand. Resource usage was poor because you couldn’t safely pack many apps onto one machine without dependency conflicts.</p><h4>Virtual machines</h4><p>VMware, Xen, and later AWS EC2 let you split one physical machine into many isolated VMs. Isolation and utilization improved, but each VM carried a full OS, booted in minutes, and still needed patching and configuration.</p><h4>Configuration management</h4><p>Chef, Puppet, Ansible, and SaltStack made server setup repeatable. You described what a server should look like, and the tool converged it to that state. This was a big step forward, but you were still managing servers. Deployments were often a fragile mix of scripts, SSH, and hope.</p><h4>Containers</h4><p>Docker (2013) packaged an app with its dependencies into a portable image that started in seconds. “Works on my machine” mostly went away. A new question replaced it:</p><blockquote><em>I have 500 containers across 50 machines. Which container runs where? What happens when one dies? How do they find each other? How do I roll out a new version without downtime?</em></blockquote><p>Answering that question is called <strong>container orchestration</strong>.</p><h4>Early orchestrators</h4><p>Several tools competed in this space:</p><ul><li><strong>Docker Swarm</strong>: simple and Docker-native, but limited for complex workloads.</li><li><strong>Apache Mesos + Marathon</strong>: powerful and used by Twitter and Airbnb, but complex to operate.</li><li><strong>HashiCorp Nomad</strong>: lightweight, and still a good choice today for some teams.</li><li><strong>AWS ECS</strong>: managed and simple, but tied to AWS.</li><li><strong>PaaS platforms</strong> like Heroku and Cloud Foundry: excellent developer experience, but little control and high cost at scale.</li></ul><p>Kubernetes won most of this market, and the reasons explain what it actually does.</p><h3>Why Kubernetes Was Built</h3><p>Google had been running containers at large scale internally for over a decade using a system called <strong>Borg</strong> (and later <strong>Omega</strong>). In 2014, Google open-sourced a new system built from those lessons. That system was Kubernetes, Greek for “helmsman.” Version 1.0 shipped in 2015, and Google donated it to the newly formed <strong>Cloud Native Computing Foundation (CNCF)</strong>. That vendor-neutral home is a large part of why AWS, Azure, Oracle, and everyone else adopted it.</p><h4>The core idea: desired state and reconciliation</h4><p>The design choice behind all of Kubernetes fits in one sentence:</p><blockquote><strong><em>You declare what you want. Kubernetes keeps working, forever, to make reality match.</em></strong></blockquote><p>You don’t tell Kubernetes “start 3 containers.” You tell it “there should always be 3 replicas of this app.” If a node dies and takes one replica with it, Kubernetes notices the gap between desired state (3) and actual state (2) and starts a new one. Nobody gets paged.</p><p>This is called a <strong>reconciliation loop</strong> (or control loop). Almost every part of Kubernetes is a loop like this:</p><pre>        ┌──────────────────────────────────────┐<br>        │                                      │<br>        ▼                                      │<br>  Observe actual state ──► Compare with ──► Take action<br>                           desired state     to close the gap</pre><p>The problems it solves</p><pre><br>| Problem                            | How Kubernetes handles it                                                       |<br>| ---------------------------------- | ------------------------------------------------------------------------------- |<br>| Where should this container run?   | Scheduling based on CPU and memory requests, constraints, and affinity.         |<br>| A container crashed                | Self-healing: Restarts the container or replaces the Pod.                       |<br>| A whole machine died               | Pods are rescheduled onto healthy nodes.                                        |<br>| How do services find each other?   | Service discovery through stable DNS names and virtual IPs.                     |<br>| Deploying without downtime         | Rolling updates and rollbacks.                                                  |<br>| Traffic spike                      | Horizontal autoscaling based on metrics.                                        |<br>| Config and secrets per environment | ConfigMaps and Secrets provide configuration at runtime.                        |<br>| Vendor lock-in                     | Consistent Kubernetes APIs across EKS, AKS, OKE, GKE, and on-premises clusters. |<br></pre><p>The last row deserves emphasis. Kubernetes gives you a <strong>standard API for running software</strong>, and that matters more than any individual feature. A huge ecosystem has been built on top of that standard API.</p><h3>The Architecture: Control Plane and Worker Nodes</h3><p>A Kubernetes cluster has two kinds of machines:</p><ol><li><strong>The control plane</strong>: the brain. It makes decisions and stores the state of the cluster.</li><li><strong>Worker nodes</strong>: the muscle. They run your actual application containers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTfe-OCgFhKS9-jrUo4xqQ.png" /></figure><p>On managed services like <strong>EKS, AKS, OKE, or GKE</strong>, the cloud provider runs the control plane for you. You mostly deal with worker nodes and your workloads. This is the right default for nearly every team.</p><h3>The Components, Explained in Plain English</h3><p>To make this concrete, picture a <strong>busy restaurant</strong>. Customers place orders, the kitchen cooks them, and managers make sure everything runs smoothly. The analogy will hold for most of the components below.</p><h4>Control Plane Components</h4><p><strong>kube-apiserver: the front desk</strong></p><p><strong>Analogy:</strong> The front desk where every order and every question goes. Nobody walks into the kitchen directly.</p><p><strong>Reality:</strong> The API server is the <strong>single entry point</strong> to the cluster. kubectl, your CI pipeline, Argo CD, the scheduler, and the kubelets on each node all talk to it over a REST API. It handles:</p><ul><li><strong>Authentication</strong>: who are you?</li><li><strong>Authorization (RBAC)</strong>: are you allowed to do this?</li><li><strong>Admission control</strong>: should this request be modified or rejected? Policy tools like OPA Gatekeeper and Kyverno plug in here.</li><li><strong>Validation and persistence</strong>: it’s the only component that reads from and writes to etcd.</li></ul><p>The API server is stateless, so you can run several replicas behind a load balancer for high availability.</p><p><strong>etcd: the order book</strong></p><p><strong>Analogy:</strong> The restaurant’s master ledger. Every order, every table assignment, every change is written here. If you lose the ledger, you lose track of everything.</p><p><strong>Reality:</strong> etcd is a distributed, strongly consistent key-value store that holds <strong>the entire state of the cluster</strong>: every Deployment, Pod, Secret, and ConfigMap. It uses the Raft consensus algorithm, which is why production clusters run 3 or 5 etcd members (an odd number keeps quorum).</p><p>Operationally, etcd is the most critical piece of the cluster. <strong>If etcd is lost without a backup, the cluster’s state is gone.</strong> On self-managed clusters, etcd backups are not optional. On managed Kubernetes, the provider handles this.</p><p><strong>kube-scheduler: the host who seats guests</strong></p><p><strong>Analogy:</strong> The host who looks at a new party of guests and decides which table they sit at, based on party size, available seats, and special requests (“we want a window seat”).</p><p><strong>Reality:</strong> When a new Pod is created, it has no node assigned. The scheduler watches for these unscheduled pods and picks the best node for each one. It works in two phases:</p><ol><li><strong>Filtering</strong>: which nodes <em>can</em> run this pod? (Enough CPU and memory? Matching node selectors? Tolerates the node’s taints?)</li><li><strong>Scoring</strong>: of the eligible nodes, which is <em>best</em>? (Spread replicas across zones, balance resource usage, honor affinity rules.)</li></ol><p>The scheduler only <em>decides</em>. It writes the decision back to the API server, and the kubelet on that node does the actual work.</p><p><strong>kube-controller-manager: the floor managers</strong></p><p><strong>Analogy:</strong> A team of floor managers, each responsible for one thing. One makes sure every table has the right number of waiters. Another checks that no table has been forgotten.</p><p><strong>Reality:</strong> This single process runs many <strong>controllers</strong>, each one a reconciliation loop for a specific resource type:</p><ul><li><strong>Deployment controller</strong>: manages ReplicaSets for rolling updates.</li><li><strong>ReplicaSet controller</strong>: ensures the right number of pods exist.</li><li><strong>Node controller</strong>: notices when nodes stop reporting and marks them unhealthy.</li><li><strong>Job controller</strong>: runs pods to completion.</li><li><strong>EndpointSlice controller</strong>: keeps track of which pod IPs back each Service.</li></ul><p><strong>cloud-controller-manager: the supplier liaison</strong></p><p><strong>Analogy:</strong> The person who calls external suppliers when the restaurant needs something it can’t make in-house.</p><p><strong>Reality:</strong> This component integrates with your cloud provider’s APIs. When you create a Service of type LoadBalancer, this is what provisions an AWS NLB or an Azure Load Balancer. It also handles node lifecycle and cloud routes.</p><h4>Worker Node Components</h4><p><strong>Node: the kitchen station</strong></p><p>A <strong>node</strong> is a machine (VM or physical) that runs your workloads. Each node runs a few agents that connect it to the control plane.</p><p><strong>kubelet: the station chef</strong></p><p><strong>Analogy:</strong> The chef at each station. They take tickets assigned to their station, cook the dishes, and report back when something is ready or burnt.</p><p><strong>Reality:</strong> The kubelet is an agent running on every node. It:</p><ul><li>Watches the API server for pods assigned to its node.</li><li>Tells the container runtime to start and stop containers.</li><li>Runs <strong>liveness, readiness, and startup probes</strong>.</li><li>Reports pod and node status back to the API server.</li><li>Mounts volumes and injects Secrets and ConfigMaps.</li></ul><p>If the kubelet on a node stops reporting, the control plane eventually considers that node lost and reschedules its pods.</p><p><strong>Container runtime: the stove</strong></p><p><strong>Analogy:</strong> The stove. The chef decides what to cook; the stove does the cooking.</p><p><strong>Reality:</strong> The software that actually runs containers, accessed through the <strong>Container Runtime Interface (CRI)</strong>. Today this is usually <strong>containerd</strong> or <strong>CRI-O</strong>. Kubernetes removed its direct Docker Engine integration (dockershim) in v1.24. Your Docker-built images still work fine because they follow the OCI image standard.</p><p><strong>kube-proxy: the waiter routing orders</strong></p><p><strong>Analogy:</strong> The waiter who knows that “table 12’s order” should go to whichever chef is free right now.</p><p><strong>Reality:</strong> kube-proxy runs on every node and implements <strong>Services</strong>. When a pod calls orders-api:80, kube-proxy’s iptables or IPVS rules route that traffic to one of the healthy backing pods. Some CNI plugins (like Cilium) replace kube-proxy entirely using eBPF.</p><p>Add-ons you’ll always encounter</p><ul><li><strong>CNI plugin</strong> (Calico, Cilium, AWS VPC CNI, Azure CNI): gives every pod its own IP address and enforces NetworkPolicies.</li><li><strong>CoreDNS</strong>: the cluster DNS server. It’s why http://orders-api.orders.svc.cluster.local resolves.</li><li><strong>metrics-server</strong>: provides CPU and memory metrics used by the HorizontalPodAutoscaler and kubectl top.</li></ul><h3>Kubernetes Objects You Should Know</h3><p>Objects are the nouns of Kubernetes. You describe them in YAML, submit them to the API server, and controllers make them real.</p><h4>Workloads</h4><pre>| Object         | What it is                                                                    | When you use it                                          |<br>| -------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------- |<br>| Pod            | Smallest deployable unit. One or more containers sharing network and storage. | Rarely created directly. Higher-level objects manage it. |<br>| ReplicaSet     | Keeps a specified number of identical Pods running.                            | Usually managed indirectly through Deployments.          |<br>| Deployment     | Manages ReplicaSets and supports rolling updates and rollbacks.                | Stateless services. The default choice for backend APIs. |<br>| StatefulSet    | Provides stable Pod identities and persistent storage.                         | Databases, Kafka, and applications requiring stable identity. |<br>| DaemonSet      | Runs a Pod on each eligible node.                                               | Log shippers, monitoring agents, and networking components. |<br>| Job            | Runs Pods until a task completes successfully.                                  | Database migrations and batch processing.                |<br>| CronJob        | Creates Jobs on a schedule.                                                     | Nightly reports and scheduled cleanup tasks.             |<br></pre><h4>Networking</h4><pre>| Object                  | What it is                                                                                                      |<br>| ----------------------- | --------------------------------------------------------------------------------------------------------------- |<br>| Service (ClusterIP)     | Provides a stable internal IP and DNS name for a set of Pods. The default Service type.                         |<br>| Service (NodePort)      | Exposes a Service on a port across cluster nodes.                                                               |<br>| Service (LoadBalancer)  | Exposes a Service through a cloud or supported load balancer.                                                   |<br>| Ingress                 | Routes HTTP/HTTPS traffic to Services using host and path rules. Requires an Ingress controller.                |<br>| Gateway API             | Provides a more expressive model for managing network traffic into Kubernetes.                                  |<br>| NetworkPolicy           | Defines rules controlling traffic between Pods and other endpoints. Enforcement requires a compatible plugin.   |<br></pre><h4>Configuration and Storage</h4><pre>| Object                          | What it is                                                                                                      |<br>| ------------------------------- | --------------------------------------------------------------------------------------------------------------- |<br>| ConfigMap                       | Stores non-sensitive configuration, such as environment variables and application settings.                     |<br>| Secret                          | Stores sensitive data, such as passwords and tokens. Base64 encoding is not encryption. Enable encryption at rest and restrict RBAC access. |<br>| PersistentVolume (PV)           | Represents storage available to the cluster, such as a cloud disk or network volume.                            |<br>| PersistentVolumeClaim (PVC)     | Requests storage for an application, such as 20 GiB of persistent disk space.                                   |<br>| StorageClass                    | Defines storage types and enables dynamic provisioning of PersistentVolumes.                                    |<br></pre><h4>Organization, Security, and Reliability</h4><pre>| Object                            | What it is                                                                                                      |<br>| --------------------------------- | --------------------------------------------------------------------------------------------------------------- |<br>| Namespace                         | Organizes cluster resources into logical groups, often by team or environment.                                  |<br>| ServiceAccount                    | Provides an identity for a Pod or process that authenticates with the Kubernetes API.                           |<br>| Role / ClusterRole + Binding      | Defines and grants RBAC permissions. Follow the principle of least privilege.                                   |<br>| HorizontalPodAutoscaler (HPA)     | Automatically adjusts Pod replicas based on CPU, memory, or supported custom metrics.                           |<br>| PodDisruptionBudget (PDB)         | Limits voluntary disruptions to help maintain availability during operations such as node drains.               |<br>| ResourceQuota / LimitRange        | Controls namespace resource consumption, including aggregate quotas and per-container or per-Pod limits.        |<br></pre><h4>Labels and selectors: the glue</h4><p>Objects find each other through <strong>labels</strong>, not names. A Service doesn’t know which pods it routes to. It has a selector like app: orders-api, and it routes to whatever pods currently carry that label. This loose coupling explains a lot of Kubernetes behavior, and a typo in a label is one of the most common causes of “my Service has no endpoints.”</p><h3>How the Components Work Together</h3><p>Here is the full chain of events when you run kubectl apply -f deployment.yaml for a Deployment with 3 replicas.</p><pre> You            API Server        etcd     Controllers      Scheduler      kubelet (node)<br>  │                 │               │           │               │                │<br>  │ apply YAML ───► │ authn/authz   │           │               │                │<br>  │                 │ admission ──► │ store     │               │                │<br>  │                 │               │ Deployment│               │                │<br>  │                 │ ◄──── watch ──┼───────────┤               │                │<br>  │                 │       Deployment ctrl creates ReplicaSet  │                │<br>  │                 │       ReplicaSet ctrl creates 3 Pods      │                │<br>  │                 │       (nodeName empty)                    │                │<br>  │                 │ ◄──── watch ──┼───────────┼───────────────┤                │<br>  │                 │       Scheduler picks nodes, binds pods   │                │<br>  │                 │ ◄──── watch ──┼───────────┼───────────────┼────────────────┤<br>  │                 │       kubelet sees pod assigned to it     │ pull image,    │<br>  │                 │                                           │ start container│<br>  │                 │ ◄─────────────────────────────── status: Running, Ready ───┤<br>  │                 │       EndpointSlice updated, kube-proxy routes traffic     │</pre><p>Step by step:</p><ol><li><strong>kubectl</strong> sends the Deployment to the <strong>API server</strong>.</li><li>The API server authenticates you, checks RBAC, runs admission controllers, validates the object, and stores it in <strong>etcd</strong>.</li><li>The <strong>Deployment controller</strong> (watching the API server) sees a new Deployment and creates a <strong>ReplicaSet</strong>.</li><li>The <strong>ReplicaSet controller</strong> sees it needs 3 pods and has 0, so it creates 3 Pod objects. They have no node yet.</li><li>The <strong>scheduler</strong> sees 3 unscheduled pods, picks a node for each, and writes the assignment back.</li><li>The <strong>kubelet</strong> on each chosen node sees a pod assigned to it, tells <strong>containerd</strong> to pull the image and start the container, and sets up networking via the <strong>CNI plugin</strong>.</li><li>The kubelet runs the <strong>readiness probe</strong>. Once it passes, the pod is marked Ready.</li><li>The <strong>EndpointSlice controller</strong> adds the pod’s IP to the Service, and <strong>kube-proxy</strong> on every node updates its routing rules. Traffic starts flowing.</li></ol><p>Note that <strong>no component tells another what to do directly.</strong> Everything goes through the API server. Each component watches for changes it cares about and reacts. This loose coupling is what makes Kubernetes resilient and extensible.</p><h4>What happens when things break</h4><ul><li><strong>Container crashes</strong>: kubelet restarts it with exponential backoff. If it keeps crashing, you see CrashLoopBackOff.</li><li><strong>Liveness probe fails</strong>: kubelet kills and restarts the container.</li><li><strong>Readiness probe fails</strong>: the pod is removed from Service endpoints. It stays running, it just stops receiving traffic.</li><li><strong>Node dies</strong>: the node controller marks it NotReady. After a timeout (around 5 minutes by default), pods are evicted and the ReplicaSet controller creates replacements on healthy nodes.</li></ul><p>That 5-minute window is a real failure mode. Run at least 2 replicas spread across zones so a single node failure doesn’t cause an outage.</p><h3>Hands-On: Deploying a Python Service</h3><p>Let’s deploy a FastAPI service the way you would in production, then interact with the cluster programmatically from Python and Go.</p><h4>1. A Kubernetes-friendly Python app</h4><p>A service that runs well on Kubernetes has separate liveness and readiness endpoints and shuts down cleanly on SIGTERM.</p><pre># app/main.py<br>import logging<br>import os<br>from contextlib import asynccontextmanager<br><br>from fastapi import FastAPI, Response, status<br><br>logging.basicConfig(level=os.getenv(&quot;LOG_LEVEL&quot;, &quot;INFO&quot;))<br>log = logging.getLogger(&quot;orders-api&quot;)<br><br>state = {&quot;ready&quot;: False}<br><br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    # Open DB pools, warm caches, etc. before accepting traffic.<br>    state[&quot;ready&quot;] = True<br>    log.info(&quot;ready to serve traffic&quot;)<br>    yield<br>    # Uvicorn calls this on SIGTERM. Close pools and flush buffers here.<br>    state[&quot;ready&quot;] = False<br>    log.info(&quot;shutting down&quot;)<br><br><br>app = FastAPI(lifespan=lifespan)<br><br><br>@app.get(&quot;/healthz&quot;)<br>def liveness():<br>    # Liveness answers one question: is this process stuck?<br>    # Never check downstream dependencies here, or a DB blip<br>    # will restart every pod in the fleet at once.<br>    return {&quot;status&quot;: &quot;alive&quot;}<br><br><br>@app.get(&quot;/readyz&quot;)<br>def readiness(response: Response):<br>    if not state[&quot;ready&quot;]:<br>        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE<br>        return {&quot;status&quot;: &quot;not ready&quot;}<br>    return {&quot;status&quot;: &quot;ready&quot;}<br><br><br>@app.get(&quot;/orders/{order_id}&quot;)<br>def get_order(order_id: str):<br>    return {&quot;id&quot;: order_id, &quot;region&quot;: os.getenv(&quot;REGION&quot;, &quot;unknown&quot;)}</pre><p>The comment in liveness() points at a classic production incident. A liveness probe that checks the database turns a 10-second DB failover into a full fleet restart storm.</p><h4>2. Dockerfile</h4><pre>FROM python:3.12-slim<br><br>ENV PYTHONDONTWRITEBYTECODE=1 \<br>    PYTHONUNBUFFERED=1<br><br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY app/ app/<br><br>RUN useradd --uid 10001 --no-create-home appuser<br>USER 10001<br><br>EXPOSE 8000<br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h4>3. The Kubernetes manifests</h4><pre># k8s/config.yaml<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: orders-config<br>  namespace: orders<br>data:<br>  LOG_LEVEL: &quot;INFO&quot;<br>  REGION: &quot;ap-south-1&quot;</pre><pre># k8s/deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: orders-api<br>  namespace: orders<br>  labels:<br>    app: orders-api<br>spec:<br>  replicas: 3<br>  revisionHistoryLimit: 5<br>  strategy:<br>    type: RollingUpdate<br>    rollingUpdate:<br>      maxSurge: 1<br>      maxUnavailable: 0<br>  selector:<br>    matchLabels:<br>      app: orders-api<br>  template:<br>    metadata:<br>      labels:<br>        app: orders-api<br>    spec:<br>      serviceAccountName: orders-api<br>      terminationGracePeriodSeconds: 30<br>      topologySpreadConstraints:<br>        - maxSkew: 1<br>          topologyKey: topology.kubernetes.io/zone<br>          whenUnsatisfiable: ScheduleAnyway<br>          labelSelector:<br>            matchLabels:<br>              app: orders-api<br>      securityContext:<br>        runAsNonRoot: true<br>        runAsUser: 10001<br>      containers:<br>        - name: api<br>          image: ghcr.io/acme/orders-api:1.4.2<br>          ports:<br>            - containerPort: 8000<br>          envFrom:<br>            - configMapRef:<br>                name: orders-config<br>          env:<br>            - name: DATABASE_URL<br>              valueFrom:<br>                secretKeyRef:<br>                  name: orders-secrets<br>                  key: database-url<br>          resources:<br>            requests:<br>              cpu: 250m<br>              memory: 256Mi<br>            limits:<br>              memory: 512Mi<br>          readinessProbe:<br>            httpGet:<br>              path: /readyz<br>              port: 8000<br>            periodSeconds: 5<br>            failureThreshold: 3<br>          livenessProbe:<br>            httpGet:<br>              path: /healthz<br>              port: 8000<br>            initialDelaySeconds: 10<br>            periodSeconds: 10<br>            failureThreshold: 3<br>          lifecycle:<br>            preStop:<br>              exec:<br>                command: [&quot;sleep&quot;, &quot;5&quot;]<br>          securityContext:<br>            allowPrivilegeEscalation: false<br>            readOnlyRootFilesystem: true<br>            capabilities:<br>              drop: [&quot;ALL&quot;]</pre><p>A few deliberate choices here:</p><ul><li><strong>maxUnavailable: 0</strong> means rollouts never drop below 3 ready pods.</li><li><strong>Pinned image tag</strong> (1.4.2, never latest) so rollbacks are meaningful and deploys are reproducible.</li><li><strong>Memory limit but no CPU limit.</strong> A memory limit protects the node from leaks (the container gets OOMKilled). CPU limits cause throttling that shows up as unexplained p99 latency spikes, so many teams set CPU requests only. This is a team-level policy decision. If you run multi-tenant clusters with strict quotas, you may need CPU limits.</li><li><strong>preStop sleep</strong> gives kube-proxy and load balancers a few seconds to stop sending traffic before the app receives SIGTERM. Without it, you’ll see a handful of 502s on every deploy.</li><li><strong>Topology spread</strong> places replicas across availability zones.</li></ul><pre># k8s/service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: orders-api<br>  namespace: orders<br>spec:<br>  selector:<br>    app: orders-api<br>  ports:<br>    - port: 80<br>      targetPort: 8000<br>---<br>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: orders-api<br>  namespace: orders<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: orders-api<br>  minReplicas: 3<br>  maxReplicas: 15<br>  metrics:<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target:<br>          type: Utilization<br>          averageUtilization: 70<br>---<br>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: orders-api<br>  namespace: orders<br>spec:<br>  minAvailable: 2<br>  selector:<br>    matchLabels:<br>      app: orders-api</pre><p>HPA utilization is calculated against <strong>requests</strong>, which is one more reason to set requests based on real measurements instead of guesses.</p><h4>4. Deploy and operate</h4><pre>kubectl create namespace orders<br>kubectl apply -f k8s/<br><br>kubectl -n orders rollout status deployment/orders-api<br>kubectl -n orders get pods -o wide<br>kubectl -n orders port-forward svc/orders-api 8080:80<br>curl localhost:8080/orders/42<br><br># Something went wrong? Roll back to the previous ReplicaSet.<br>kubectl -n orders rollout undo deployment/orders-api</pre><h4>5. Talking to the Kubernetes API from Python</h4><p>Anything kubectl does, your code can do through the API. Here’s a small script that flags unhealthy pods. It works both locally (kubeconfig) and inside the cluster (service account).</p><pre># tools/pod_health.py<br>import sys<br><br>from kubernetes import client, config<br><br>BAD_REASONS = {&quot;CrashLoopBackOff&quot;, &quot;ImagePullBackOff&quot;, &quot;ErrImagePull&quot;, &quot;CreateContainerConfigError&quot;}<br><br><br>def load_config() -&gt; None:<br>    try:<br>        config.load_incluster_config()<br>    except config.ConfigException:<br>        config.load_kube_config()<br><br><br>def unhealthy_containers(namespace: str, restart_threshold: int = 3):<br>    v1 = client.CoreV1Api()<br>    for pod in v1.list_namespaced_pod(namespace).items:<br>        for cs in pod.status.container_statuses or []:<br>            waiting = cs.state.waiting<br>            reason = waiting.reason if waiting else None<br>            last = cs.last_state.terminated<br>            last_reason = last.reason if last else None<br>            if reason in BAD_REASONS or cs.restart_count &gt;= restart_threshold:<br>                yield pod.metadata.name, cs.name, cs.restart_count, reason or last_reason<br><br><br>if __name__ == &quot;__main__&quot;:<br>    load_config()<br>    ns = sys.argv[1] if len(sys.argv) &gt; 1 else &quot;default&quot;<br>    found = False<br>    for pod, container, restarts, reason in unhealthy_containers(ns):<br>        found = True<br>        print(f&quot;{pod}/{container}\trestarts={restarts}\treason={reason}&quot;)<br>    sys.exit(1 if found else 0)</pre><p>The last_reason check is useful because OOMKilled shows up in the <em>previous</em> termination state, not the current one. That detail trips people up in debugging and in interviews.</p><p>If you run this inside the cluster, grant only what it needs:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: pod-reader<br>  namespace: orders<br>rules:<br>  - apiGroups: [&quot;&quot;]<br>    resources: [&quot;pods&quot;]<br>    verbs: [&quot;get&quot;, &quot;list&quot;]<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: pod-health-reader<br>  namespace: orders<br>subjects:<br>  - kind: ServiceAccount<br>    name: pod-health<br>    namespace: orders<br>roleRef:<br>  kind: Role<br>  name: pod-reader<br>  apiGroup: rbac.authorization.k8s.io</pre><h4>6. The same idea in Go with client-go</h4><p>Kubernetes itself is written in Go, and client-go is the library that operators and controllers are built on. Here’s a rollout health report for Deployments:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;path/filepath&quot;<br> &quot;time&quot;<br><br> metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br> &quot;k8s.io/client-go/kubernetes&quot;<br> &quot;k8s.io/client-go/rest&quot;<br> &quot;k8s.io/client-go/tools/clientcmd&quot;<br>)<br><br>func restConfig() (*rest.Config, error) {<br> if cfg, err := rest.InClusterConfig(); err == nil {<br>  return cfg, nil<br> }<br> home, err := os.UserHomeDir()<br> if err != nil {<br>  return nil, err<br> }<br> return clientcmd.BuildConfigFromFlags(&quot;&quot;, filepath.Join(home, &quot;.kube&quot;, &quot;config&quot;))<br>}<br><br>func main() {<br> namespace := &quot;orders&quot;<br> if len(os.Args) &gt; 1 {<br>  namespace = os.Args[1]<br> }<br><br> cfg, err := restConfig()<br> if err != nil {<br>  log.Fatalf(&quot;load config: %v&quot;, err)<br> }<br> clientset, err := kubernetes.NewForConfig(cfg)<br> if err != nil {<br>  log.Fatalf(&quot;create client: %v&quot;, err)<br> }<br><br> ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)<br> defer cancel()<br><br> deployments, err := clientset.AppsV1().Deployments(namespace).List(ctx, metav1.ListOptions{})<br> if err != nil {<br>  log.Fatalf(&quot;list deployments: %v&quot;, err)<br> }<br><br> for _, d := range deployments.Items {<br>  desired := int32(1)<br>  if d.Spec.Replicas != nil {<br>   desired = *d.Spec.Replicas<br>  }<br>  healthy := d.Status.ReadyReplicas == desired &amp;&amp; d.Status.UpdatedReplicas == desired<br>  fmt.Printf(&quot;%-30s desired=%d ready=%d updated=%d healthy=%t\n&quot;,<br>   d.Name, desired, d.Status.ReadyReplicas, d.Status.UpdatedReplicas, healthy)<br> }<br>}</pre><p>When a list-and-check script grows into “watch for changes and react,” you’re writing a controller. At that point, use <strong>controller-runtime</strong> or <strong>Kubebuilder</strong> instead of hand-rolling watch loops.</p><h3>Kubernetes with Helm and Argo CD</h3><p>Raw YAML works for one service in one environment. With 40 services across dev, staging, and prod, you’d be maintaining hundreds of near-identical files. Helm and Argo CD exist to manage that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjdwR7w5b2O_n5xB1ZxuFw.png" /></figure><h4>Helm: the package manager</h4><p><strong>Helm</strong> packages Kubernetes manifests into <strong>charts</strong>: templated YAML plus a values.yaml file with per-environment settings.</p><pre>orders-api/<br>├── Chart.yaml<br>├── values.yaml<br>├── values-prod.yaml<br>└── templates/<br>    ├── deployment.yaml<br>    ├── service.yaml<br>    ├── hpa.yaml<br>    └── pdb.yaml</pre><pre># values.yaml<br>image:<br>  repository: ghcr.io/acme/orders-api<br>  tag: &quot;1.4.2&quot;<br>replicaCount: 2<br>resources:<br>  requests:<br>    cpu: 250m<br>    memory: 256Mi<br>  limits:<br>    memory: 512Mi<br>autoscaling:<br>  enabled: false</pre><pre># values-prod.yaml<br>replicaCount: 3<br>autoscaling:<br>  enabled: true<br>  minReplicas: 3<br>  maxReplicas: 15</pre><pre># templates/deployment.yaml (excerpt)<br>spec:<br>  {{- if not .Values.autoscaling.enabled }}<br>  replicas: {{ .Values.replicaCount }}<br>  {{- end }}<br>  template:<br>    spec:<br>      containers:<br>        - name: api<br>          image: &quot;{{ .Values.image.repository }}:{{ .Values.image.tag }}&quot;<br>          resources:<br>            {{- toYaml .Values.resources | nindent 12 }}</pre><pre>helm upgrade --install orders-api ./orders-api \<br>  -n orders -f values-prod.yaml --atomic --timeout 5m</pre><p>--atomic rolls back automatically if the release fails. Helm is also how you install third-party software: ingress-nginx, cert-manager, Prometheus, and External Secrets all ship as charts.</p><p>A word of caution: Helm templates get hard to read fast. For a 20-person team, the highest-leverage move is usually <strong>one shared internal chart</strong> that all services use with different values, rather than 40 custom charts that drift apart. <strong>Kustomize</strong> (built into kubectl) is a template-free alternative based on overlays, and some teams prefer it for in-house services.</p><h4>Argo CD: GitOps delivery</h4><p>The traditional CI/CD model has your pipeline run kubectl apply or helm upgrade against the cluster. That means CI holds cluster-admin credentials, and nothing notices if someone manually changes the cluster later.</p><p><strong>GitOps</strong> flips this around. Git is the source of truth, and an agent <em>inside</em> the cluster pulls changes and reconciles. <strong>Argo CD</strong> is the most popular implementation (Flux is the main alternative).</p><pre> Developer ──► PR to app repo ──► CI (GitHub Actions / Jenkins)<br>                                     │  build, test, push image<br>                                     │  bump image tag in config repo<br>                                     ▼<br>                              ┌─────────────┐<br>                              │ Config repo │  (Helm values / Kustomize)<br>                              └──────┬──────┘<br>                                     │ Argo CD watches<br>                                     ▼<br>                              ┌─────────────┐   compares desired (Git)<br>                              │   Argo CD   │   vs actual (cluster),<br>                              │ (in-cluster)│   syncs the difference<br>                              └──────┬──────┘<br>                                     ▼<br>                              Kubernetes API</pre><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: orders-api-prod<br>  namespace: argocd<br>spec:<br>  project: backend<br>  source:<br>    repoURL: https://github.com/acme/k8s-config.git<br>    targetRevision: main<br>    path: charts/orders-api<br>    helm:<br>      valueFiles:<br>        - values-prod.yaml<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: orders<br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true<br>    syncOptions:<br>      - CreateNamespace=true</pre><p>Look familiar? Argo CD is the same reconciliation idea as Kubernetes itself, applied one level higher. Kubernetes reconciles the cluster against etcd. Argo CD reconciles etcd against Git.</p><p>What you gain:</p><ul><li><strong>Audit trail</strong>: every production change is a Git commit with a reviewer.</li><li><strong>Rollback</strong>: git revert.</li><li><strong>Drift correction</strong>: selfHeal undoes manual kubectl edit changes.</li><li><strong>Security</strong>: CI never needs cluster credentials.</li></ul><p>prune: true deletes resources removed from Git. Make sure your team understands this before enabling it on production apps, since a bad merge can delete live resources.</p><h3>When to Use Kubernetes (and When Not To)</h3><p>Kubernetes is powerful, and it is also a lot of operational surface area. Use it when it solves problems you actually have.</p><h4>Good fit</h4><ul><li><strong>Many services</strong> (roughly 10 or more) owned by multiple teams that benefit from one standard deployment platform.</li><li>You need <strong>multi-cloud, hybrid, or on-prem portability</strong>.</li><li>You have, or can build, <strong>platform engineering capacity</strong>. Even managed Kubernetes needs people who own upgrades, networking, observability, and security.</li><li>You want the <strong>ecosystem</strong>: operators for Kafka and Postgres, service meshes, GitOps, policy engines, autoscalers like Karpenter.</li><li>Workloads are mixed: APIs, workers, batch jobs, and cron jobs on shared infrastructure.</li></ul><h4>Poor fit</h4><ul><li><strong>A handful of services and a small team.</strong> AWS ECS on Fargate, Azure Container Apps, Cloud Run, or even a PaaS will get you to production faster with a fraction of the ops burden.</li><li><strong>Event-driven or spiky low-traffic workloads</strong> where Lambda or Azure Functions are cheaper and simpler.</li><li><strong>Nobody owns the platform.</strong> An unowned cluster drifts, falls behind on upgrades (minor versions get support for roughly 14 months), and becomes a security liability.</li><li><strong>Stateful systems your team can’t run well.</strong> Running Postgres on Kubernetes with an operator is viable, but RDS or Aurora is usually the better call unless you have a strong reason.</li></ul><p>A useful rule of thumb: <strong>adopt Kubernetes because operating many services without a common platform is hurting you, not because it looks good on a résumé.</strong> If you do adopt it, use a managed control plane (EKS, AKS, OKE) and start with boring defaults.</p><h3>Important Components for DevOps / SRE Interviews</h3><p>Interviewers rarely ask you to recite definitions. They ask what happens, why, and how you’d debug it. These are the topics that come up most often.</p><h4>Architecture and internals</h4><ul><li>Walk through what happens on kubectl apply (the sequence covered above).</li><li>Why is etcd critical, why an odd number of members, and how do you back it up and restore it?</li><li>What happens when the control plane goes down? (Running pods keep running. Nothing new gets scheduled, and self-healing stops.)</li><li>How does the scheduler decide placement? Know filtering vs scoring, taints and tolerations, node affinity, and pod anti-affinity.</li></ul><h4>Pod lifecycle and health</h4><ul><li><strong>Liveness vs readiness vs startup probes</strong>, and why liveness should never check dependencies.</li><li>Pod phases (Pending, Running, Succeeded, Failed, Unknown) and what Pending usually means (insufficient resources, unbound PVC, unsatisfiable affinity).</li><li>Graceful shutdown: preStop → SIGTERM → grace period → SIGKILL.</li><li>Init containers and sidecars.</li></ul><h4>Resources and scheduling</h4><ul><li><strong>Requests vs limits.</strong> Requests drive scheduling. Limits are enforced at runtime.</li><li><strong>QoS classes</strong>: Guaranteed, Burstable, BestEffort, and which pods get evicted first under node pressure.</li><li>OOMKilled (exceeded memory limit) vs CPU throttling (exceeded CPU limit).</li><li>HPA vs VPA vs Cluster Autoscaler / Karpenter.</li></ul><h4>Networking</h4><ul><li>How a request reaches a pod: DNS → Service ClusterIP → kube-proxy rules → pod IP.</li><li>ClusterIP vs NodePort vs LoadBalancer vs Ingress.</li><li>What a CNI plugin does, and why NetworkPolicies need a CNI that supports them.</li><li>Default-deny NetworkPolicy as a security baseline.</li></ul><h4>Security</h4><ul><li>RBAC: Role vs ClusterRole, binding to ServiceAccounts, least privilege.</li><li>Why Secrets aren’t secure by default, and how to fix that (encryption at rest, External Secrets, Vault, Sealed Secrets).</li><li>Pod Security Standards (restricted profile), non-root containers, read-only filesystems.</li><li>Workload identity (IRSA / EKS Pod Identity, Azure Workload Identity) instead of static cloud keys.</li></ul><h4>Deployments and reliability</h4><ul><li>Rolling update parameters (maxSurge, maxUnavailable) and kubectl rollout undo.</li><li>Blue/green and canary deployments (Argo Rollouts, Flagger).</li><li>PodDisruptionBudgets and safe node drains during upgrades.</li><li>Cluster upgrade strategy: control plane first, then node groups, one minor version at a time.</li></ul><h4>The debugging toolkit</h4><p>Expect a scenario like “a pod is in CrashLoopBackOff, walk me through it.” This is a solid flow:</p><pre>kubectl get pods -n orders                               # what state is it in?<br>kubectl describe pod &lt;pod&gt; -n orders                     # events: scheduling, probe failures, OOMKilled, image pull errors<br>kubectl logs &lt;pod&gt; -n orders --previous                  # logs from the crashed container, not the new one<br>kubectl get events -n orders --sort-by=.lastTimestamp    # recent cluster-level events<br>kubectl top pod -n orders                                # actual CPU/memory usage<br>kubectl get endpointslices -n orders -l kubernetes.io/service-name=orders-api   # is the Service routing to anything?<br>kubectl debug -it &lt;pod&gt; -n orders --image=busybox --target=api   # ephemeral debug container</pre><pre>| Symptom                  | Usual suspects                                                                    |<br>| ------------------------ | ---------------------------------------------------------------------------------- |<br>| `Pending`                | Insufficient CPU/memory, taints, unbound PVC, or affinity rules.                   |<br>| `ImagePullBackOff`       | Wrong image tag, missing registry pull secret, or registry rate limits.             |<br>| `CrashLoopBackOff`       | Startup error, missing config/secret, bad command, or failing liveness probe.       |<br>| `OOMKilled`               | Memory limit too low or a genuine memory leak.                                     |<br>| Service returns nothing  | Label/selector mismatch, failing readiness probe, or incorrect `targetPort`.        |<br>| 502s during deploys      | Missing `preStop` delay or application not handling `SIGTERM` gracefully.           |<br></pre><p>Being able to explain <em>why</em> each of these happens matters more than memorizing commands, and it’s what separates strong candidates.</p><h3>Conclusion</h3><p>Kubernetes looks intimidating because it has a lot of moving parts, but the core is simple. You declare desired state through the API server. That state is stored in etcd. A set of independent controllers, the scheduler, and the kubelets on each node keep working until reality matches it. Self-healing, rolling updates, service discovery, and autoscaling all follow from that one idea.</p><p>For backend developers, the practical takeaways are:</p><ul><li>Make your apps Kubernetes-friendly: separate liveness and readiness probes, clean SIGTERM handling, config from the environment, and logs to stdout.</li><li>Learn the core objects deeply (Deployment, Service, ConfigMap, Secret, HPA, PDB) before reaching for anything exotic.</li><li>Set resource requests from real measurements, because scheduling and autoscaling both depend on them.</li><li>Standardize delivery with a shared Helm chart and GitOps through Argo CD so your 40th service is as easy to ship as your first.</li><li>Be honest about whether you need Kubernetes at all. A managed container service is often the better answer for small teams.</li></ul><p>Start with a managed cluster, deploy one real service end to end, break it on purpose, and debug it. That loop will teach you more than any amount of reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a0fae0be1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Karpenter: The Smarter Way to Autoscale Your Kubernetes Cluster]]></title>
            <link>https://medium.com/@mgaurang123/karpenter-the-smarter-way-to-autoscale-your-kubernetes-cluster-83337b7cf409?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/83337b7cf409</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[karpenter]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sun, 31 May 2026 13:51:20 GMT</pubDate>
            <atom:updated>2026-05-31T13:51:20.122Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How JioHotstar tamed sudden IPL traffic bursts, and how you can do the same for your platform.</blockquote><p>Every team running Kubernetes at scale has hit the same wall. Traffic spikes. Pods start pending. The cluster autoscaler crawls through its decision loop. By the time new nodes are ready, your p99 latency has already wrecked your SLA and your on-call phone is blowing up.</p><p>This isn’t a new problem. But for a long time, the tools we had were either too slow, too rigid, or too expensive to run correctly. Karpenter changes that.</p><p>In this post we will walk through what Karpenter actually is, why it was built, how it interacts with horizontal pod autoscalers, how it works alongside KEDA for event-driven workloads, how JioHotstar used it to handle the chaos of live IPL streaming, and what you need to know before you deploy it in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*o0zdpVzGqR2A33kvSsvcGw.png" /></figure><h3>The Autoscaling Problem Nobody Talks About Enough</h3><p>Before Karpenter, the default approach to Kubernetes node autoscaling was the <strong>Cluster Autoscaler (CA)</strong>. It works. Sort of.</p><p>Here is what the flow looks like with CA:</p><pre>Pod goes Pending<br>    |<br>    v<br>CA polls Kubernetes API (every ~10s by default)<br>    |<br>    v<br>CA evaluates which node group can fit the pod<br>    |<br>    v<br>CA sends a scale-up request to the cloud provider<br>    |<br>    v<br>Node provisioning starts (can take 2-5 minutes)<br>    |<br>    v<br>Node joins cluster<br>    |<br>    v<br>Pod gets scheduled</pre><p>The polling gap alone introduces 10–60 seconds of delay before CA even decides to act. Then cloud provider provisioning adds another 2–5 minutes. For bursty workloads, that is an eternity.</p><p>Beyond latency, there are deeper structural problems:</p><p><strong>Node group rigidity.</strong> CA operates on pre-configured node groups. You define the instance type, the AZ, the capacity type (on-demand vs spot) in advance. If a pod needs something slightly different, it either gets stuck or lands on a suboptimal node that wastes money.</p><p><strong>Bin-packing is an afterthought.</strong> CA does not try to tightly pack pods onto nodes. You often end up with nodes that are 40–60% utilized because the autoscaler does not know how to consolidate.</p><p><strong>Scale-down is conservative.</strong> CA waits 10 minutes by default before removing an underutilized node. At scale, that idle time turns into real cost.</p><p><strong>Multi-AZ scheduling is clunky.</strong> CA manages separate node groups per AZ. Getting spread-awareness right requires careful config and often breaks under uneven traffic.</p><p>These are the problems that led AWS to build Karpenter and eventually open-source it under the Kubernetes SIG.</p><h3>What is Karpenter?</h3><p>Karpenter is an open-source, flexible, high-performance Kubernetes node provisioner. It was built by AWS and donated to the CNCF. It is now vendor-neutral, with providers for AWS, Azure, and others.</p><p>The key architectural difference: <strong>Karpenter watches for unschedulable pods directly and provisions exactly the right node for them, in real time.</strong></p><p>It does not use node groups. It does not poll. It reacts.</p><pre>Pod goes Pending<br>    |<br>    v<br>Karpenter watches pod spec (resources, node selectors, affinity, tolerations)<br>    |<br>    v<br>Karpenter queries cloud API for optimal instance type<br>    |<br>    v<br>Node provisioned and registered directly<br>    |<br>    v<br>Pod scheduled (total time: ~60 seconds end to end on AWS)</pre><p>That is a 3–5x improvement in provisioning speed compared to CA in most benchmarks.</p><p>The project lives at <a href="https://github.com/aws/karpenter">github.com/aws/karpenter</a> and the provider-agnostic core at <a href="https://github.com/kubernetes-sigs/karpenter">github.com/kubernetes-sigs/karpenter</a>.</p><h3>How Karpenter Works</h3><p>Karpenter has two core concepts: <strong>NodePool</strong> and <strong>NodeClaim</strong>.</p><h4>NodePool</h4><p>A NodePool is the policy object. It defines constraints on what kinds of nodes Karpenter is allowed to provision. Think of it as the envelope of acceptable compute.</p><pre>apiVersion: karpenter.sh/v1<br>kind: NodePool<br>metadata:<br>  name: general-purpose<br>spec:<br>  template:<br>    spec:<br>      nodeClassRef:<br>        group: karpenter.k8s.aws<br>        kind: EC2NodeClass<br>        name: default<br>      requirements:<br>        - key: karpenter.sh/capacity-type<br>          operator: In<br>          values: [&quot;spot&quot;, &quot;on-demand&quot;]<br>        - key: node.kubernetes.io/instance-type<br>          operator: In<br>          values: [&quot;m5.large&quot;, &quot;m5.xlarge&quot;, &quot;m6i.large&quot;, &quot;m6i.xlarge&quot;, &quot;c5.large&quot;, &quot;c5.xlarge&quot;]<br>        - key: topology.kubernetes.io/zone<br>          operator: In<br>          values: [&quot;ap-south-1a&quot;, &quot;ap-south-1b&quot;, &quot;ap-south-1c&quot;]<br>  limits:<br>    cpu: &quot;1000&quot;<br>    memory: &quot;4000Gi&quot;<br>  disruption:<br>    consolidationPolicy: WhenUnderutilized<br>    consolidateAfter: 30s</pre><h4>EC2NodeClass (AWS-specific)</h4><p>This defines the AMI, subnet, security groups, and instance profile for the nodes Karpenter creates on AWS.</p><pre>apiVersion: karpenter.k8s.aws/v1<br>kind: EC2NodeClass<br>metadata:<br>  name: default<br>spec:<br>  amiSelectorTerms:<br>    - alias: al2023@latest<br>  subnetSelectorTerms:<br>    - tags:<br>        karpenter.sh/discovery: my-cluster<br>  securityGroupSelectorTerms:<br>    - tags:<br>        karpenter.sh/discovery: my-cluster<br>  role: &quot;KarpenterNodeRole-my-cluster&quot;<br>  blockDeviceMappings:<br>    - deviceName: /dev/xvda<br>      ebs:<br>        volumeSize: 50Gi<br>        volumeType: gp3<br>        iops: 3000<br>        throughput: 125</pre><h3>NodeClaim</h3><p>A NodeClaim is the machine-level object Karpenter creates and manages for each physical node. You normally do not create these directly. Karpenter creates them when a pod is unschedulable and deletes them during consolidation.</p><h4>The Scheduling Loop</h4><p>When a pod is pending:</p><ol><li>Karpenter reads the pod’s resource requests, node selectors, affinity rules, tolerations, and topology spread constraints.</li><li>It simulates placement against existing nodes. If the pod fits, Karpenter does nothing.</li><li>If not, it queries the cloud provider for available instance types that match the NodePool constraints and satisfy the pod’s needs.</li><li>It picks the cheapest option that fits, preferring spot over on-demand when the NodePool allows it.</li><li>It creates the node directly via cloud API and registers it with the cluster.</li></ol><h4>Consolidation</h4><p>This is where Karpenter earns its keep operationally. When consolidationPolicy: WhenUnderutilized is set:</p><ul><li>Karpenter continuously evaluates whether nodes can be bin-packed more tightly.</li><li>If pods on a node can be moved to other existing nodes, Karpenter drains and terminates that node.</li><li>This happens automatically, continuously, without you doing anything.</li></ul><p>The result: your cluster self-optimizes. Idle nodes disappear. You stop paying for compute you are not using.</p><h3>Karpenter vs HPA: Do They Replace Each Other?</h3><p>Short answer: <strong>No, they solve different layers of the problem and work best together.</strong></p><pre>+--------------------------------------------------+<br>|                   Your App Traffic               |<br>+--------------------------------------------------+<br>           |<br>           v<br>+--------------------------------------------------+<br>|   HPA / KEDA (Pod-level autoscaling)             |<br>|   Scales: replica count based on CPU/memory      |<br>|   or custom metrics (queue depth, RPS, etc.)     |<br>+--------------------------------------------------+<br>           |<br>           v (Pods become Pending)<br>+--------------------------------------------------+<br>|   Karpenter (Node-level autoscaling)             |<br>|   Scales: actual EC2 / cloud nodes               |<br>|   Responds to unschedulable pods                 |<br>+--------------------------------------------------+</pre><p><strong>HPA (Horizontal Pod Autoscaler)</strong> reacts to metrics and adjusts the number of pod replicas. It knows nothing about nodes.</p><p><strong>Karpenter</strong> reacts to unschedulable pods and provisions or removes nodes. It knows nothing about your application metrics.</p><p>They are complementary. HPA creates demand (more pods), Karpenter fulfills capacity (more nodes). Remove either one and you have a broken system:</p><ul><li>Without HPA, your pods never scale out and Karpenter never gets triggered.</li><li>Without Karpenter (or CA), pods go pending and your workload degrades.</li></ul><p><strong>The replacement story is about Cluster Autoscaler, not HPA.</strong> Karpenter is a drop-in replacement for CA with significantly better performance and cost efficiency. You would typically run either Karpenter or CA, not both.</p><h3>Saving Real Money with Karpenter</h3><p>The cost savings come from three mechanisms:</p><h4>1. Spot Instance Flexibility</h4><p>CA requires you to pre-define spot node groups by instance type. If your chosen instance type gets reclaimed by AWS, you need a fallback group. Managing this is operationally painful and most teams do not get it right.</p><p>Karpenter accepts a list of instance types and capacity types in a single NodePool. When scheduling a pod, it will choose the cheapest available spot instance that fits. If spot is unavailable, it falls back to on-demand automatically. You get optimal spot utilization without managing N node groups.</p><p>Spot instances typically save 60–80% vs on-demand. On a $50K/month compute bill, that is $30–40K in savings.</p><h4>2. Continuous Consolidation</h4><p>Without consolidation, Kubernetes clusters bloat. Pods get scheduled on nodes, some pods scale down, and you are left with partially-loaded nodes. Most teams do not have a process to reclaim these.</p><p>Karpenter’s consolidation loop runs continuously. It will move pods and kill nodes without you doing anything. In practice, most teams see 20–40% reduction in node count after enabling consolidation.</p><h4>3. Right-Sized Nodes</h4><p>Because Karpenter can pick from many instance types, it finds the best fit for pending pods. A pod requesting 3 CPUs and 6Gi memory will get scheduled on a 4-CPU node rather than an 8-CPU node that CA might have spun up because it was the only available node group.</p><h3>Karpenter + KEDA: The Dream Combo</h3><p>If Karpenter handles node-level scaling and HPA handles pod-level scaling based on CPU/memory, there is still a gap: <strong>event-driven scaling</strong>.</p><p>What if your pods need to scale based on:</p><ul><li>Kafka consumer lag</li><li>SQS queue depth</li><li>Redis queue length</li><li>HTTP request rate from a custom metrics source</li></ul><p>This is where KEDA (Kubernetes Event Driven Autoscaler) comes in. KEDA adds external metric sources to the autoscaling stack.</p><p><strong>I have written a deep-dive on KEDA here:</strong> <a href="https://medium.com/@mgaurang123/keda-event-driven-autoscaling-for-kubernetes-that-actually-saves-you-money-42cc40c35415">KEDA: Event-Driven Autoscaling for Kubernetes That Actually Saves You Money</a></p><p>The Karpenter + KEDA architecture looks like this:</p><pre>+--------------------------------------------------+<br>|  External Event Source                           |<br>|  (Kafka lag, SQS depth, Redis queue, HTTP RPS)   |<br>+--------------------------------------------------+<br>           |<br>           v<br>+--------------------------------------------------+<br>|   KEDA ScaledObject                              |<br>|   Triggers pod replica changes based on events   |<br>+--------------------------------------------------+<br>           |<br>           v (Pods scale out, some go Pending)<br>+--------------------------------------------------+<br>|   Karpenter                                      |<br>|   Provisions exact node capacity for new pods    |<br>+--------------------------------------------------+<br>           |<br>           v (Traffic drops, KEDA scales pods down)<br>+--------------------------------------------------+<br>|   Karpenter Consolidation                        |<br>|   Removes now-empty or underutilized nodes       |<br>+--------------------------------------------------+</pre><p>The combination means your infrastructure scales with actual business events, not lagging CPU metrics. A Kafka consumer can go from 2 replicas to 50 replicas in under 2 minutes based on consumer lag, and Karpenter will have the nodes ready before the pods are stuck pending for long.</p><p><strong>Where this saves serious money:</strong> Traditional approaches over-provision to handle bursts. With KEDA + Karpenter, you provision at idle (minimal cost), scale up fast when events arrive, and scale back down completely when they are gone. For batch workloads and streaming ingest, the savings can be 50–70% compared to always-on over-provisioned clusters.</p><h3>How JioHotstar Solved Node Scaling at Live Match Scale</h3><p>JioHotstar (formerly Disney+ Hotstar, now part of Reliance’s JioStar) runs one of the largest streaming platforms in the world. During live IPL cricket matches, they routinely see 30–50 million concurrent users, with traffic spikes that happen in seconds, not minutes.</p><p>The challenges they faced were a textbook case of why traditional autoscaling breaks:</p><h4>The Problem</h4><p><strong>Unpredictable burst traffic.</strong> When a bowler gets a wicket or a batsman hits a six, millions of users refresh streams simultaneously. These spikes are 5–10x over baseline and happen in under 30 seconds.</p><p><strong>Pre-match ramp-up.</strong> An hour before a match starts, traffic climbs aggressively. With CA, they had to pre-provision nodes manually and guess capacity. Over-provision and you burn money. Under-provision and you drop streams.</p><p><strong>Cost at scale.</strong> Running enough on-demand capacity to handle peak IPL traffic 24/7 would cost a staggering amount. Most of that capacity would sit idle for 20+ hours a day.</p><p><strong>Multi-region complexity.</strong> Traffic is geographically concentrated but spiky within each region. Managing node groups per region per AZ per instance type was becoming unmanageable.</p><h4>The Solution with Karpenter</h4><p>JioHotstar’s engineering team moved their Kubernetes worker nodes to Karpenter-managed provisioning with the following architecture:</p><p><strong>NodePool Strategy:</strong></p><ul><li>Separate NodePools for streaming workloads vs. backend API workloads vs. batch jobs.</li><li>Streaming NodePools configured with a wide list of instance types (c5, c6i, m5, m6i in multiple sizes) to maximize spot availability.</li><li>Burst NodePools that accept on-demand when spot capacity is constrained (which happens when millions of users across India are all trying to scale at the same time during a major match).</li></ul><p><strong>Pre-warming with Karpenter.</strong> Rather than waiting for pods to go pending, the JioHotstar team uses a two-phase approach:</p><ol><li>Before match start, their capacity management system creates placeholder “balloon” pods that request compute resources but do very little work. These cause Karpenter to provision nodes in advance.</li><li>When real traffic arrives, the balloon pods are evicted (they have low priority), real streaming pods take their place, and Karpenter has nodes already warm and ready.</li></ol><p>This pattern eliminates cold-start latency. Real pods never wait for node provisioning.</p><p><strong>KEDA Integration for Stream Workers.</strong> JioHotstar’s stream processing workers consume from internal Kafka topics that track viewer session events. They use KEDA ScaledObjects watching consumer group lag. When a match starts and lag spikes, KEDA scales stream workers from baseline to peak in under 90 seconds. Karpenter ensures nodes are available to receive those new pods.</p><p><strong>Cost Outcome.</strong> By running 70–80% of their workload on spot instances during non-peak hours and aggressively consolidating after matches end, JioHotstar reportedly reduced compute costs for their streaming infrastructure significantly compared to static capacity planning. The exact numbers are not publicly disclosed, but the architecture pattern is well-documented in their engineering presentations at KubeCon and AWS re:Invent.</p><p>The key insight from their experience: <strong>Karpenter is not just an autoscaler, it is a capacity management system.</strong> When you treat it that way and design your NodePools and workload priorities around it, the results are dramatically better than trying to patch CA with more node groups.</p><h3>Code Examples</h3><h4>Python: Kubernetes Client to Monitor Karpenter Node Status</h4><p>This script connects to your cluster, lists all Karpenter-managed nodes, and reports their capacity type and utilization. Useful for building dashboards or cost attribution tools.</p><pre>import os<br>from kubernetes import client, config<br>from kubernetes.client.rest import ApiException<br>from dataclasses import dataclass<br>from typing import Optional<br><br><br>@dataclass<br>class KarpenterNode:<br>    name: str<br>    instance_type: str<br>    capacity_type: str  # spot or on-demand<br>    zone: str<br>    cpu_capacity: str<br>    memory_capacity: str<br>    phase: str<br>    nodepool: Optional[str]<br><br><br>def load_kube_config():<br>    &quot;&quot;&quot;Load from in-cluster config or fallback to kubeconfig.&quot;&quot;&quot;<br>    try:<br>        config.load_incluster_config()<br>    except config.ConfigException:<br>        config.load_kube_config()<br><br><br>def list_karpenter_nodes() -&gt; list[KarpenterNode]:<br>    load_kube_config()<br>    v1 = client.CoreV1Api()<br><br>    try:<br>        nodes = v1.list_node(<br>            label_selector=&quot;karpenter.sh/registered=true&quot;<br>        )<br>    except ApiException as e:<br>        print(f&quot;Error listing nodes: {e}&quot;)<br>        return []<br><br>    result = []<br>    for node in nodes.items:<br>        labels = node.metadata.labels or {}<br>        capacity = node.status.capacity or {}<br>        conditions = node.status.conditions or []<br><br>        phase = &quot;Unknown&quot;<br>        for condition in conditions:<br>            if condition.type == &quot;Ready&quot;:<br>                phase = &quot;Ready&quot; if condition.status == &quot;True&quot; else &quot;NotReady&quot;<br>                break<br><br>        result.append(KarpenterNode(<br>            name=node.metadata.name,<br>            instance_type=labels.get(&quot;node.kubernetes.io/instance-type&quot;, &quot;unknown&quot;),<br>            capacity_type=labels.get(&quot;karpenter.sh/capacity-type&quot;, &quot;unknown&quot;),<br>            zone=labels.get(&quot;topology.kubernetes.io/zone&quot;, &quot;unknown&quot;),<br>            cpu_capacity=capacity.get(&quot;cpu&quot;, &quot;unknown&quot;),<br>            memory_capacity=capacity.get(&quot;memory&quot;, &quot;unknown&quot;),<br>            phase=phase,<br>            nodepool=labels.get(&quot;karpenter.sh/nodepool&quot;),<br>        ))<br><br>    return result<br><br><br>def print_node_report(nodes: list[KarpenterNode]):<br>    spot_count = sum(1 for n in nodes if n.capacity_type == &quot;spot&quot;)<br>    od_count = sum(1 for n in nodes if n.capacity_type == &quot;on-demand&quot;)<br><br>    print(f&quot;\n{&#39;=&#39;*70}&quot;)<br>    print(f&quot;Karpenter Node Report | Total: {len(nodes)} | Spot: {spot_count} | On-Demand: {od_count}&quot;)<br>    print(f&quot;{&#39;=&#39;*70}&quot;)<br>    print(f&quot;{&#39;NODE NAME&#39;:&lt;40} {&#39;TYPE&#39;:&lt;15} {&#39;CAPACITY&#39;:&lt;10} {&#39;ZONE&#39;:&lt;15} {&#39;STATUS&#39;}&quot;)<br>    print(f&quot;{&#39;-&#39;*70}&quot;)<br><br>    for node in sorted(nodes, key=lambda n: n.capacity_type):<br>        print(<br>            f&quot;{node.name:&lt;40} &quot;<br>            f&quot;{node.instance_type:&lt;15} &quot;<br>            f&quot;{node.capacity_type:&lt;10} &quot;<br>            f&quot;{node.zone:&lt;15} &quot;<br>            f&quot;{node.phase}&quot;<br>        )<br><br>    print(f&quot;{&#39;=&#39;*70}\n&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    nodes = list_karpenter_nodes()<br>    if not nodes:<br>        print(&quot;No Karpenter-managed nodes found.&quot;)<br>    else:<br>        print_node_report(nodes)</pre><h4>Python: Auto-generate Karpenter NodePool Manifests from Config</h4><p>This is useful when you have multiple teams needing different NodePool configurations. Instead of writing YAML by hand, generate it programmatically.</p><pre>import yaml<br>from dataclasses import dataclass, field<br>from typing import Optional<br><br><br>@dataclass<br>class NodePoolConfig:<br>    name: str<br>    nodeclass_name: str<br>    capacity_types: list[str]<br>    instance_types: list[str]<br>    zones: list[str]<br>    cpu_limit: str<br>    memory_limit: str<br>    consolidate_after: str = &quot;30s&quot;<br>    ttl_seconds_until_expired: Optional[int] = None<br><br><br>def generate_nodepool_manifest(cfg: NodePoolConfig) -&gt; dict:<br>    spec = {<br>        &quot;template&quot;: {<br>            &quot;spec&quot;: {<br>                &quot;nodeClassRef&quot;: {<br>                    &quot;group&quot;: &quot;karpenter.k8s.aws&quot;,<br>                    &quot;kind&quot;: &quot;EC2NodeClass&quot;,<br>                    &quot;name&quot;: cfg.nodeclass_name,<br>                },<br>                &quot;requirements&quot;: [<br>                    {<br>                        &quot;key&quot;: &quot;karpenter.sh/capacity-type&quot;,<br>                        &quot;operator&quot;: &quot;In&quot;,<br>                        &quot;values&quot;: cfg.capacity_types,<br>                    },<br>                    {<br>                        &quot;key&quot;: &quot;node.kubernetes.io/instance-type&quot;,<br>                        &quot;operator&quot;: &quot;In&quot;,<br>                        &quot;values&quot;: cfg.instance_types,<br>                    },<br>                    {<br>                        &quot;key&quot;: &quot;topology.kubernetes.io/zone&quot;,<br>                        &quot;operator&quot;: &quot;In&quot;,<br>                        &quot;values&quot;: cfg.zones,<br>                    },<br>                ],<br>            }<br>        },<br>        &quot;limits&quot;: {<br>            &quot;cpu&quot;: cfg.cpu_limit,<br>            &quot;memory&quot;: cfg.memory_limit,<br>        },<br>        &quot;disruption&quot;: {<br>            &quot;consolidationPolicy&quot;: &quot;WhenUnderutilized&quot;,<br>            &quot;consolidateAfter&quot;: cfg.consolidate_after,<br>        },<br>    }<br><br>    if cfg.ttl_seconds_until_expired:<br>        spec[&quot;template&quot;][&quot;spec&quot;][&quot;expireAfter&quot;] = f&quot;{cfg.ttl_seconds_until_expired}s&quot;<br><br>    return {<br>        &quot;apiVersion&quot;: &quot;karpenter.sh/v1&quot;,<br>        &quot;kind&quot;: &quot;NodePool&quot;,<br>        &quot;metadata&quot;: {&quot;name&quot;: cfg.name},<br>        &quot;spec&quot;: spec,<br>    }<br><br><br>def main():<br>    configs = [<br>        NodePoolConfig(<br>            name=&quot;streaming-spot&quot;,<br>            nodeclass_name=&quot;default&quot;,<br>            capacity_types=[&quot;spot&quot;, &quot;on-demand&quot;],<br>            instance_types=[<br>                &quot;c5.large&quot;, &quot;c5.xlarge&quot;, &quot;c5.2xlarge&quot;,<br>                &quot;c6i.large&quot;, &quot;c6i.xlarge&quot;, &quot;c6i.2xlarge&quot;,<br>                &quot;m5.large&quot;, &quot;m5.xlarge&quot;,<br>            ],<br>            zones=[&quot;ap-south-1a&quot;, &quot;ap-south-1b&quot;, &quot;ap-south-1c&quot;],<br>            cpu_limit=&quot;2000&quot;,<br>            memory_limit=&quot;8000Gi&quot;,<br>            consolidate_after=&quot;60s&quot;,<br>        ),<br>        NodePoolConfig(<br>            name=&quot;api-on-demand&quot;,<br>            nodeclass_name=&quot;default&quot;,<br>            capacity_types=[&quot;on-demand&quot;],<br>            instance_types=[&quot;m6i.xlarge&quot;, &quot;m6i.2xlarge&quot;],<br>            zones=[&quot;ap-south-1a&quot;, &quot;ap-south-1b&quot;],<br>            cpu_limit=&quot;500&quot;,<br>            memory_limit=&quot;2000Gi&quot;,<br>            consolidate_after=&quot;120s&quot;,<br>        ),<br>    ]<br><br>    for cfg in configs:<br>        manifest = generate_nodepool_manifest(cfg)<br>        print(&quot;---&quot;)<br>        print(yaml.dump(manifest, default_flow_style=False))<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Karpenter NodePool for Spot with Fallback Pattern</h4><p>This is a production-ready NodePool setup that prioritizes spot but falls back to on-demand, with separate pools for different workload classes:</p><pre># streaming-nodepool.yaml<br>apiVersion: karpenter.sh/v1<br>kind: NodePool<br>metadata:<br>  name: streaming-burst<br>spec:<br>  template:<br>    metadata:<br>      labels:<br>        workload-type: streaming<br>    spec:<br>      nodeClassRef:<br>        group: karpenter.k8s.aws<br>        kind: EC2NodeClass<br>        name: streaming-nodeclass<br>      requirements:<br>        # Prefer spot, allow on-demand fallback<br>        - key: karpenter.sh/capacity-type<br>          operator: In<br>          values: [&quot;spot&quot;, &quot;on-demand&quot;]<br>        # Wide instance type selection for spot availability<br>        - key: node.kubernetes.io/instance-type<br>          operator: In<br>          values:<br>            - c5.xlarge<br>            - c5.2xlarge<br>            - c5.4xlarge<br>            - c6i.xlarge<br>            - c6i.2xlarge<br>            - c6i.4xlarge<br>            - c6a.xlarge<br>            - c6a.2xlarge<br>            - m5.xlarge<br>            - m5.2xlarge<br>            - m6i.xlarge<br>            - m6i.2xlarge<br>        - key: topology.kubernetes.io/zone<br>          operator: In<br>          values:<br>            - ap-south-1a<br>            - ap-south-1b<br>            - ap-south-1c<br>      # Drain before termination (important for streaming)<br>      terminationGracePeriod: 10m<br>  limits:<br>    cpu: &quot;4000&quot;<br>    memory: &quot;16000Gi&quot;<br>  disruption:<br>    # Consolidate quickly for cost savings<br>    consolidationPolicy: WhenUnderutilized<br>    consolidateAfter: 60s<br>    # Budget prevents simultaneous disruption of too many nodes<br>    budgets:<br>      - nodes: &quot;10%&quot;       # Only disrupt 10% of nodes at a time<br>      - schedule: &quot;0 2 * * *&quot;  # Allow full disruption at 2am UTC<br>        duration: 2h<br>        nodes: &quot;100%&quot;<br>  weight: 10<br>---<br># Low-priority balloon deployment for pre-warming<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: karpenter-balloon<br>  namespace: default<br>spec:<br>  replicas: 10<br>  selector:<br>    matchLabels:<br>      app: balloon<br>  template:<br>    metadata:<br>      labels:<br>        app: balloon<br>    spec:<br>      priorityClassName: low-priority-balloon<br>      containers:<br>        - name: pause<br>          image: public.ecr.aws/eks-distro/kubernetes/pause:3.7<br>          resources:<br>            requests:<br>              cpu: &quot;1&quot;<br>              memory: &quot;2Gi&quot;<br>      nodeSelector:<br>        workload-type: streaming<br>      tolerations:<br>        - key: &quot;karpenter.sh/disruption&quot;<br>          operator: &quot;Exists&quot;<br>          effect: &quot;NoSchedule&quot;<br>---<br>apiVersion: scheduling.k8s.io/v1<br>kind: PriorityClass<br>metadata:<br>  name: low-priority-balloon<br>value: -10<br>globalDefault: false<br>description: &quot;Low priority class for balloon pods used to pre-warm Karpenter nodes&quot;</pre><h3>Dos and Don’ts</h3><h4>DOs</h4><p><strong>Set resource requests on every container.</strong> Karpenter makes scheduling decisions entirely based on resource requests. If your containers have no requests, Karpenter cannot size nodes correctly and you will get over-provisioned or misaligned nodes. Treat unset requests as a production bug.</p><p><strong>Define wide instance type lists in your NodePools.</strong> Spot instance availability varies by instance type. The more options you give Karpenter, the better spot utilization you will get. A NodePool with 15 instance types will have dramatically better spot availability than one with 3.</p><p><strong>Use separate NodePools for different workload classes.</strong> Batch jobs, streaming workloads, and API services have different latency tolerances, cost profiles, and spot interruption tolerance. Give each its own NodePool with appropriate instance types and disruption budgets.</p><p><strong>Set disruption budgets.</strong> Without budgets, Karpenter could simultaneously drain many nodes during consolidation. In production, nodes: &quot;10%&quot; prevents consolidation from causing a cascading failure.</p><p><strong>Use topology spread constraints for zone balancing.</strong> Karpenter respects topologySpreadConstraints. Configure your critical workloads to spread across AZs so a spot interruption in one AZ does not take down all instances.</p><p><strong>Test spot interruption handling locally.</strong> AWS provides the <a href="https://docs.aws.amazon.com/fis/latest/userguide/fis-actions-reference.html">FIS Spot Interruption action</a>. Run it regularly to ensure your pods drain gracefully and Karpenter reprovisions correctly.</p><p><strong>Tag your nodes for cost attribution.</strong> Use nodeClassRef tags to label nodes by team, service, and environment. This makes cost allocation dashboards accurate.</p><h4>DON’TS</h4><p><strong>Do not run Karpenter and Cluster Autoscaler on the same node groups.</strong> They will conflict. Either migrate fully to Karpenter or keep CA managing its own dedicated node groups. Pick one.</p><p><strong>Do not use Karpenter for nodes that need manual lifecycle control.</strong> Stateful workloads that cannot be disrupted (e.g., single-node databases) should use static nodes outside Karpenter’s management scope.</p><p><strong>Do not set consolidation to </strong><strong>WhenEmpty only in production if cost matters.</strong> WhenEmpty only removes nodes with zero pods. WhenUnderutilized will actively pack pods tighter and remove underused nodes. Use the latter for meaningful cost savings.</p><p><strong>Do not ignore </strong><strong>terminationGracePeriod for long-running jobs.</strong> If Karpenter consolidates a node running a 30-minute batch job and your grace period is 30 seconds, that job dies. Set an appropriate grace period and use PodDisruptionBudgets.</p><p><strong>Do not put GPU workloads in general NodePools.</strong> GPU instances have wildly different costs and availability. Isolate them in dedicated NodePools with explicit instance families and use node taints to prevent non-GPU workloads from landing there.</p><p><strong>Do not skip setting limits on NodePools.</strong> Without CPU and memory limits, Karpenter will provision unboundedly if a misconfigured HPA goes rogue. Limits protect your cloud bill.</p><p><strong>Do not rely on Karpenter alone for pre-warming.</strong> Karpenter provisions nodes reactively. For predictable burst events (sports matches, sale launches), use the balloon pod pattern or Karpenter’s ExpireAfter with scheduled scale-ups to have capacity ready before you need it.</p><h3>Conclusion</h3><p>Kubernetes autoscaling has always had a node provisioning problem. The Cluster Autoscaler works, but its design of predefined node groups, polling-based reactions, and conservative scale-down makes it a poor fit for workloads that need to react in seconds, not minutes.</p><p>Karpenter fixes this at the architectural level. By watching pod scheduling events directly, querying cloud APIs for optimal instance fit, and running a continuous consolidation loop, it makes your cluster faster to scale, cheaper to run, and easier to operate.</p><p>When you pair Karpenter with KEDA, you get a complete autoscaling stack that reacts to actual business events rather than lagging infrastructure metrics. The result is infrastructure that scales precisely when needed and costs almost nothing when it is not.</p><p>JioHotstar’s architecture during IPL season is the most demanding test case for this stack in production. Their use of Karpenter for node provisioning, KEDA for event-driven pod scaling, and balloon pods for pre-warming shows what a mature Karpenter deployment looks like when the stakes are tens of millions of concurrent users.</p><p>The path to getting here is straightforward: start by replacing your Cluster Autoscaler with Karpenter, ensure all containers have resource requests set, define NodePools per workload class, enable consolidation, and layer KEDA on top for event-driven scaling.</p><p>The infrastructure cost savings are real. The operational simplicity is real. The performance improvement under burst is real. The only question is when you want to start.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83337b7cf409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents Simplified: A Backend Developer’s Honest Guide]]></title>
            <link>https://medium.com/@mgaurang123/ai-agents-simplified-a-backend-developers-honest-guide-498f5d1c8dc6?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/498f5d1c8dc6</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sat, 23 May 2026 15:51:36 GMT</pubDate>
            <atom:updated>2026-05-23T15:51:36.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone is talking about AI agents. Startups are raising millions on the promise of “agentic AI.” Enterprises are packaging them into products with names that sound like they were written by a committee of consultants. And somewhere in the middle of all the noise, you, a backend developer, are probably asking: “What actually <em>is</em> an agent, and do I actually need one?”</p><p>This post is going to cut through the jargon. No corporate buzzwords. No “paradigm shifts.” Just a clear explanation of what agents are, how they work, what they are good for, and how you can build one today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWazuKZR20HKANGBC9fyrw.png" /></figure><h3>What Is an AI Agent?</h3><p>An AI agent is a program that uses a language model (LLM) to decide what to do next, takes an action, observes the result, and repeats this loop until the task is done.</p><p>That is really it.</p><p>Think of it this way: a regular LLM call is like asking a colleague a question and getting an answer. An agent is like handing that colleague a laptop and a task and letting them figure it out step by step.</p><p>Here is the simplest mental model:</p><pre>+------------------+<br>|   You (or code)  |<br>|  give it a goal  |<br>+--------+---------+<br>         |<br>         v<br>+--------+---------+<br>|    LLM thinks    |  &lt;-- &quot;What should I do next?&quot;<br>+--------+---------+<br>         |<br>         v<br>+--------+---------+<br>|  Agent takes an  |  &lt;-- calls a tool, writes a file, hits an API<br>|     action       |<br>+--------+---------+<br>         |<br>         v<br>+--------+---------+<br>|  Observes result |  &lt;-- &quot;Did that work? What now?&quot;<br>+--------+---------+<br>         |<br>    loop back up<br>    until done</pre><p>No magic. No mystery. Just a loop where the LLM drives the decision-making.</p><h3>What Does an Agent Actually Do? And Why Do We Need It?</h3><p>Here is the thing about a plain LLM API call: it is stateless and single-shot. You send a prompt, you get a response. Done. It cannot take actions on its own, cannot call your database, cannot check an email, cannot loop until a condition is met.</p><p>An agent fills that gap.</p><h4>What an Agent Can Do</h4><ul><li>Call external tools and APIs (search the web, query a DB, send a message)</li><li>Make decisions based on what it observes</li><li>Keep going until the goal is complete, not just until one response is generated</li><li>Handle branching logic it figures out on its own</li></ul><h4>Why You Need It</h4><p>Most real-world tasks are not single-step. Consider:</p><ul><li>“Monitor this Jira board and ping Slack when a ticket stays in review for more than 48 hours.”</li><li>“Read this PDF contract, extract the payment terms, and update our billing system.”</li><li>“Triage incoming support emails, classify them, and draft a response for the top 10 priority ones.”</li></ul><p>None of these fit into a single prompt-response. They require a loop, tool use, and decision-making. That is the job of an agent.</p><h3>Workflow vs. Agent: What Is the Difference?</h3><p>This is where a lot of people get confused. Both workflows and agents use LLMs. Both automate things. But they are fundamentally different in who is driving.</p><h4>Workflow: You Drive</h4><p>In a workflow, a human (or a developer) has pre-defined every step. The LLM might help with one step (like generating a summary), but the flow itself is hardcoded. You decide the sequence.</p><pre>Step 1: Fetch emails<br>   |<br>Step 2: Send to LLM to classify<br>   |<br>Step 3: Store in DB based on category<br>   |<br>Step 4: Send Slack notification</pre><p>Every arrow here was written by a developer. The LLM is just a tool inside the pipeline.</p><h4>Agent: The LLM Drives</h4><p>In an agent, you hand the LLM a goal and a set of tools. The LLM decides the sequence. You do not pre-define the steps. The model figures out what to do next at runtime.</p><pre>Goal: &quot;Summarize and file the 5 most important emails from today&quot;<br><br>LLM decides:<br>  -&gt; &quot;I should list emails first&quot;<br>  -&gt; calls list_emails tool<br>  -&gt; &quot;Now I need to rank them&quot;<br>  -&gt; reasons about importance<br>  -&gt; &quot;Now I&#39;ll summarize the top 5&quot;<br>  -&gt; calls summarize tool per email<br>  -&gt; &quot;Now I&#39;ll store them&quot;<br>  -&gt; calls store_email tool<br>  -&gt; &quot;Done.&quot;</pre><p>The sequence was never hardcoded. The model figured it out.</p><h4>Quick Comparison</h4><pre>+-----------------------+---------------------------+<br>| Workflow              | Agent                     |<br>+-----------------------+---------------------------+<br>| Steps defined by dev  | Steps decided by LLM      |<br>| Predictable, rigid    | Flexible, dynamic         |<br>| Easier to debug       | Harder to debug           |<br>| Good for known paths  | Good for unknown paths    |<br>| Low LLM cost          | Higher LLM cost           |<br>+-----------------------+---------------------------+</pre><p>Neither is better. Use a workflow when you know all the steps. Use an agent when you do not.</p><h3>What Tasks Can Agents Replace?</h3><p>Here is where it gets practically useful. Agents are not here to replace developers. They are here to handle the repetitive, decision-light work that currently either eats your time or gets ignored.</p><h4>Developer Day-to-Day</h4><ul><li>Auto-triage GitHub issues: classify, label, assign to the right team</li><li>PR review assistant: point out obvious issues before human review</li><li>Dependency monitoring: scan changelogs and summarize breaking changes</li><li>Incident triage: correlate logs, find the offending service, draft a runbook entry</li></ul><h4>Data and Backend Work</h4><ul><li>Pipeline monitoring: detect anomalies, diagnose root cause, alert with context</li><li>Report generation: pull data from multiple sources, structure it, write the summary</li><li>Database cleanup: identify stale records based on business rules, flag or archive them</li></ul><h4>Communication and Operations</h4><ul><li>Email triage: classify incoming, draft responses for common cases</li><li>Meeting notes: transcribe, summarize, extract action items, file them</li><li>Onboarding: answer common setup questions, check environment, guide step by step</li></ul><h4>Anything That Is “Fetch, Think, Act, Repeat”</h4><p>If a task involves fetching information, making a decision, taking an action, and possibly doing that a few more times based on what you find, an agent fits perfectly.</p><h3>The Simplest Agent Structure (No Corporate Jargon)</h3><p>Let us break down the actual building blocks of an agent, using plain language. I will go through each part and tell you exactly what it is without wrapping it in marketing language.</p><h4>The Core Parts</h4><p><strong>1. The LLM (the brain)</strong></p><p>This is the model, GPT-4, Claude, Gemini, whatever. It reads the current situation and outputs either a decision (“I should call this tool”) or a final answer (“The task is done, here is the result”). It is not magic. It is pattern matching at massive scale.</p><p><strong>2. Tools (the hands)</strong></p><p>Tools are just functions your code exposes to the LLM. Search the web. Query a database. Send an email. Run a shell command. The LLM picks which tool to call and with what arguments. Your code actually executes it.</p><p><strong>3. Context / Memory</strong></p><p>This is just the conversation history. Everything the agent has seen so far: the original goal, the tools it called, the results it got. It is a list of messages. The LLM reads this list each turn to decide what to do next.</p><p>For longer tasks, you might store some of this outside the prompt (in a database or a vector store), then load back only what is relevant. That is what people call “memory.” It is just a way to manage what fits in the context window.</p><p><strong>4. The Loop (turns)</strong></p><p>Each “turn” is: send context to LLM, get a response, if the response calls a tool then run it and add the result to context, repeat. That is the loop. There is nothing fancier happening here.</p><p><strong>5. The Gateway / Entry Point</strong></p><p>This is just your API endpoint or function that kicks off the agent. A user sends a request, you create the initial context, and you start the loop.</p><p><strong>6. Token Management</strong></p><p>Tokens are what you pay for and what limits how much the LLM can read. As the context grows across turns, you have to make choices about what to keep, summarize, or cut. This is a real engineering concern but not a mysterious concept. It is just text length management.</p><p><strong>7. MCP (Model Context Protocol)</strong></p><p>MCP is a standard developed by Anthropic that defines how agents and tools communicate. Think of it as a consistent plug shape. Instead of every tool integration being a bespoke implementation, MCP makes tools interoperable across agents and frameworks. If you have heard of the Language Server Protocol (LSP) for IDEs, MCP is the same idea but for AI tools.</p><p><strong>8. Agent-to-Agent Communication</strong></p><p>Sometimes one agent spawns another to handle a sub-task, then gets the result back. The parent passes some of its context to the child so the child knows what is going on. This is just function calls between agents, or message passing. No different in concept from a microservice calling another microservice.</p><h4>The Full Picture in ASCII</h4><pre>+--------------------------------------------------+<br>|                  Your Application                |<br>|                                                  |<br>|  User sends goal                                 |<br>|        |                                         |<br>|        v                                         |<br>|  +----------+     +-----------+                  |<br>|  | Context  |----&gt;|    LLM    |                  |<br>|  | (memory) |&lt;----|  (brain)  |                  |<br>|  +----------+     +-----+-----+                  |<br>|                         |                        |<br>|              &quot;Call tool X with args Y&quot;           |<br>|                         |                        |<br>|                         v                        |<br>|                  +------+------+                 |<br>|                  |   Tools     |                 |<br>|                  | search_web  |                 |<br>|                  | query_db    |                 |<br>|                  | send_email  |                 |<br>|                  | run_cmd     |                 |<br>|                  +------+------+                 |<br>|                         |                        |<br>|              result appended to context          |<br>|                         |                        |<br>|                    loop repeats                  |<br>|                         |                        |<br>|              until LLM says &quot;done&quot;               |<br>+--------------------------------------------------+</pre><h3>Code Examples</h3><p>Let us build a minimal agent from scratch. No framework, no magic. Just the loop.</p><h4>Python</h4><pre>import json<br>import anthropic<br><br>client = anthropic.Anthropic()<br><br># Define tools the agent can use<br>tools = [<br>    {<br>        &quot;name&quot;: &quot;search_web&quot;,<br>        &quot;description&quot;: &quot;Search the internet for current information&quot;,<br>        &quot;input_schema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;query&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The search query&quot;}<br>            },<br>            &quot;required&quot;: [&quot;query&quot;]<br>        }<br>    },<br>    {<br>        &quot;name&quot;: &quot;save_to_file&quot;,<br>        &quot;description&quot;: &quot;Save text content to a file&quot;,<br>        &quot;input_schema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;filename&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                &quot;content&quot;: {&quot;type&quot;: &quot;string&quot;}<br>            },<br>            &quot;required&quot;: [&quot;filename&quot;, &quot;content&quot;]<br>        }<br>    }<br>]<br><br># Simulate tool execution (replace with real logic)<br>def execute_tool(tool_name: str, tool_input: dict) -&gt; str:<br>    if tool_name == &quot;search_web&quot;:<br>        # Replace with real search API call<br>        return f&quot;[Search results for &#39;{tool_input[&#39;query&#39;]}&#39;: Found 3 relevant articles about the topic.]&quot;<br>    <br>    if tool_name == &quot;save_to_file&quot;:<br>        with open(tool_input[&quot;filename&quot;], &quot;w&quot;) as f:<br>            f.write(tool_input[&quot;content&quot;])<br>        return f&quot;File &#39;{tool_input[&#39;filename&#39;]}&#39; saved successfully.&quot;<br>    <br>    return &quot;Unknown tool.&quot;<br><br>def run_agent(goal: str, max_turns: int = 10) -&gt; str:<br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>    <br>    for turn in range(max_turns):<br>        print(f&quot;\n--- Turn {turn + 1} ---&quot;)<br>        <br>        response = client.messages.create(<br>            model=&quot;claude-sonnet-4-20250514&quot;,<br>            max_tokens=4096,<br>            tools=tools,<br>            messages=messages<br>        )<br>        <br>        # Add assistant response to context<br>        messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response.content})<br>        <br>        # If the model is done, return the final text<br>        if response.stop_reason == &quot;end_turn&quot;:<br>            for block in response.content:<br>                if hasattr(block, &quot;text&quot;):<br>                    print(f&quot;Agent finished: {block.text}&quot;)<br>                    return block.text<br>        <br>        # If the model wants to use a tool, run it<br>        if response.stop_reason == &quot;tool_use&quot;:<br>            tool_results = []<br>            <br>            for block in response.content:<br>                if block.type == &quot;tool_use&quot;:<br>                    print(f&quot;Agent calling tool: {block.name} with {block.input}&quot;)<br>                    result = execute_tool(block.name, block.input)<br>                    print(f&quot;Tool result: {result}&quot;)<br>                    <br>                    tool_results.append({<br>                        &quot;type&quot;: &quot;tool_result&quot;,<br>                        &quot;tool_use_id&quot;: block.id,<br>                        &quot;content&quot;: result<br>                    })<br>            <br>            # Append tool results back into context<br>            messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: tool_results})<br>        <br>    return &quot;Agent hit max turns without completing.&quot;<br><br><br>if __name__ == &quot;__main__&quot;:<br>    result = run_agent(<br>        goal=&quot;Search for the latest news on Go 1.24 features and save a summary to &#39;go_news.txt&#39;&quot;<br>    )<br>    print(f&quot;\nFinal result: {result}&quot;)</pre><p>This is the full agent loop in under 80 lines. The LLM decides when to call tools, what arguments to pass, and when it is done. Your code just runs the loop and executes whatever tool the model picks.</p><h3>The Parts You Will Eventually Need (When Scale Demands It)</h3><p>The basics above will get you surprisingly far. But here is a realistic look at when the more “advanced” concepts actually matter and what they are, plainly.</p><p><strong>Persistent Memory:</strong> When your context window fills up across long tasks, you start summarizing or offloading older turns to a database. Load back only what is relevant. Not magical, just context window management.</p><p><strong>MCP (Model Context Protocol):</strong> When you want your agent to work with tools from other systems (a teammate’s server, a vendor’s integration) without writing custom glue code for each one. MCP gives you a standard interface so tools are plug-and-play.</p><p><strong>Agent-to-Agent (Orchestrator + Subagent):</strong> When a task is too complex for one agent to handle well, you split it. One agent manages the high-level goal. It spins up specialized subagents for sub-tasks (research, writing, QA) and collects their results. It passes only the relevant slice of context to each subagent, not the full history.</p><p><strong>Token Management:</strong> Once you run agents at scale, you start caring about how many tokens each turn consumes. You cache repeated context (like system prompts and tool definitions), summarize old turns, and trim what does not matter. This is cost optimization and performance, not a mystical discipline.</p><h3>Practical Advice Before You Build</h3><p>A few things you will learn the hard way if no one tells you upfront:</p><p>Start with a workflow, not an agent. If the steps are known, hardcode them. Agents add unpredictability. Only reach for an agent when the steps genuinely vary at runtime.</p><p>Give the agent clear, narrow goals. “Do all my work” will fail. “Search for X, summarize it, save it to Y” will succeed. Scope matters enormously.</p><p>Instrument the loop. Log every turn, every tool call, every result. Debugging an agent without logs is guesswork.</p><p>Set a max turn limit always. An agent can loop forever if it gets confused. Always cap turns and handle the case where it does not finish.</p><p>Test each tool independently before plugging it into the agent. A bad tool silently causes the agent to make bad decisions. Trust but verify.</p><h3>Conclusion</h3><p>An AI agent is not a product, a platform, or a paradigm shift. It is a loop. It is an LLM with access to tools, running in a cycle until the job is done.</p><p>The complexity that companies sell you on (gateways, memory layers, orchestration fabrics) is real for large-scale production systems, but none of it is required to get started. Build the loop, give it tools, watch it work.</p><p>The most valuable thing you can do right now is pick one repetitive task in your workflow, write two or three tool functions around it, and hand it to an agent. The loop is maybe 50 lines of code. The value of what it automates can be much larger.</p><p>Start small. Instrument everything. Scale what works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498f5d1c8dc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KEDA: Event-Driven Autoscaling for Kubernetes That Actually Saves You Money]]></title>
            <link>https://medium.com/@mgaurang123/keda-event-driven-autoscaling-for-kubernetes-that-actually-saves-you-money-42cc40c35415?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/42cc40c35415</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sat, 16 May 2026 16:45:34 GMT</pubDate>
            <atom:updated>2026-05-16T16:45:34.964Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been running workloads on Kubernetes for any length of time, you have probably bumped into the same frustration: the default Horizontal Pod Autoscaler (HPA) scales on CPU and memory, but your actual bottleneck is a queue depth, a Kafka lag, or the number of messages sitting in an Azure Service Bus topic.</p><p>You end up doing one of two things. Either you over-provision so you are always ready for spikes (expensive), or you write custom metrics pipelines just to feed the HPA with the right numbers (painful and fragile).</p><p>KEDA was built to solve exactly this. It is an open-source Kubernetes autoscaler that lets you scale your workloads based on real-world event sources: queues, streams, databases, HTTP traffic, cron schedules, and more. And it does something the standard HPA cannot do out of the box: it can scale your deployments all the way down to zero when there is no work to do, and back up the moment work arrives.</p><p>This post covers what KEDA is, why it exists, how to get it running in your cluster, and how it quietly reduces your cloud spend without you having to babysit your infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXyuj5PFajjfkX8gu0hzmA.png" /></figure><h3>What is KEDA?</h3><p>KEDA stands for <strong>Kubernetes Event-Driven Autoscaling</strong>. It is a CNCF (Cloud Native Computing Foundation) graduated project, meaning it has gone through rigorous community review and is considered production-ready.</p><p>At its core, KEDA is a Kubernetes controller that extends the standard HPA. It sits between your event source (a Kafka topic, an SQS queue, a Redis list, etc.) and the Kubernetes scheduler, translating “how much work is pending” into a pod count.</p><p>Here is a high-level picture of how the pieces fit together:</p><pre>┌──────────────────────┐      polls metrics      ┌──────────────────────┐      updates HPA      ┌──────────────────────┐      scales      ┌─────────────────────────┐<br>│     Event Source     │ ─────────────────────▶ │    KEDA Controller   │ ────────────────────▶ │    Kubernetes HPA    │ ─────────────▶ │  Application Workload  │<br>│----------------------│                         │----------------------│                       │----------------------│                │-------------------------│<br>│ Kafka / SQS / Redis  │                         │ ScaledObject         │                       │ Calculates Replicas  │                │ Deployment              │<br>│ HTTP / Prometheus    │                         │ Trigger Evaluation   │                       │ Based on Metrics     │                │ StatefulSet / Job       │<br>└──────────────────────┘                         │ External Metrics     │                       └──────────────────────┘                └─────────────────────────┘<br>                                                 └──────────────────────┘</pre><p>KEDA ships with <strong>50+ built-in scalers</strong> covering:</p><ul><li>Message queues: AWS SQS, Azure Service Bus, RabbitMQ, ActiveMQ</li><li>Streaming platforms: Apache Kafka, AWS Kinesis, Azure Event Hubs</li><li>Caches and data stores: Redis, PostgreSQL, MySQL, MongoDB</li><li>Cloud-native services: GCP Pub/Sub, Datadog metrics, Prometheus metrics</li><li>HTTP traffic (via the KEDA HTTP Add-on)</li><li>Cron schedules for time-based scaling</li></ul><p>If your event source is not on the list, you can write a custom external scaler using gRPC.</p><h3>Why Was KEDA Introduced?</h3><p>To understand why KEDA exists, you need to understand what Kubernetes gives you by default and where it falls short.</p><h4>The Problem with CPU/Memory-Based Autoscaling</h4><p>The standard HPA watches CPU and memory utilization. This works well for stateless web services where high traffic correlates with high CPU. But it completely breaks down for event-driven workloads.</p><p>Consider a worker service that consumes messages from an SQS queue. When the queue has 10,000 messages:</p><ul><li>CPU might still be low if workers are waiting on I/O (database calls, API requests)</li><li>Memory might be flat because the queue messages are small</li><li>But you desperately need more workers to drain the queue quickly</li></ul><p>The HPA would look at your idle CPU and decide: “Everything looks fine, no scaling needed.” Meanwhile your queue grows and your SLAs are being violated.</p><h4>The Gap KEDA Fills</h4><p>Before KEDA, teams had a few options, none of them great:</p><ol><li><strong>Always-on over-provisioning</strong>: Run enough pods to handle your peak load 24/7. Simple, but you pay for idle capacity constantly.</li><li><strong>Custom metrics adapters</strong>: Set up Prometheus, write custom exporters, configure the Kubernetes custom metrics API, and feed that to HPA. Works, but it is a lot of plumbing to maintain.</li><li><strong>Hand-rolled autoscaling logic</strong>: Write your own controller that watches the queue and patches deployment replicas directly. This is reinventing the wheel and is typically fragile.</li></ol><p>KEDA was introduced to close this gap cleanly. It was originally created by Microsoft and Red Hat and donated to the CNCF in 2019. The design goal was simple: make it trivially easy to scale any Kubernetes workload based on any event source, without requiring custom metrics infrastructure.</p><p>The zero-scale capability was another key motivation. Cloud compute is billed by the second. If a workload has nothing to do at 3am, it should run zero replicas. KEDA makes this the default behavior, not an afterthought.</p><h3>How KEDA Works Under the Hood</h3><p>KEDA installs two main components in your cluster:</p><p><strong>1. The KEDA Operator</strong>: Watches for ScaledObject and ScaledJob custom resources you create. When it sees one, it creates and manages a corresponding HPA on your behalf.</p><p><strong>2. The Metrics Server (keda-operator-metrics-apiserver)</strong>: Implements the Kubernetes external metrics API. This is how the HPA gets the custom metric values from KEDA. The operator polls your event source, computes the current metric value (e.g., queue depth), and exposes it via this API.</p><p>The flow for each scaling decision:</p><pre>1. KEDA polls the event source every [pollingInterval] seconds<br>2. Gets the current metric value (e.g., 450 messages in queue)<br>3. Exposes this as an external metric via the metrics API<br>4. HPA reads the metric, computes desired replicas = ceil(metric / threshold)<br>5. HPA patches your Deployment/StatefulSet replica count<br>6. Kubernetes scheduler places pods on nodes</pre><p>For <strong>scale-to-zero</strong>, KEDA bypasses the HPA entirely. When the metric value drops to zero, KEDA directly patches the target resource to 0 replicas. When the metric becomes non-zero again, KEDA scales up to at least 1 replica, then hands control back to the HPA.</p><h3>Setting Up KEDA in Your Kubernetes Cluster</h3><h4>Prerequisites</h4><ul><li>Kubernetes 1.24 or higher</li><li>kubectl configured for your cluster</li><li>Helm 3 (recommended installation method)</li></ul><h4>Installing KEDA with Helm</h4><pre># Add the KEDA Helm repo<br>helm repo add kedacore https://kedacore.github.io/charts<br>helm repo update<br><br># Install KEDA into its own namespace<br>helm install keda kedacore/keda \<br>  --namespace keda \<br>  --create-namespace</pre><h4>Verifying the Installation</h4><pre>kubectl get pods -n keda<br><br># You should see something like:<br># NAME                                               READY   STATUS    RESTARTS   AGE<br># keda-operator-7d9c8b6f5-xp2q9                     1/1     Running   0          2m<br># keda-operator-metrics-apiserver-6b4d8c9f7-n8kl2   1/1     Running   0          2m<br># keda-admission-webhooks-5f7c6d8b9-m3kp1            1/1     Running   0          2m</pre><pre># Confirm the custom resource definitions are registered<br>kubectl get crd | grep keda<br><br># scaledobjects.keda.sh<br># scaledjobs.keda.sh<br># triggerauthentications.keda.sh<br># clustertriggerauthentications.keda.sh</pre><p>Installing via kubectl (without Helm)</p><pre>kubectl apply --server-side \<br>  -f https://github.com/kedacore/keda/releases/download/v2.13.1/keda-2.13.1.yaml</pre><h3>Core Concepts: ScaledObjects and ScaledJobs</h3><h4>ScaledObject</h4><p>A ScaledObject is what you create to enable autoscaling for a Deployment, StatefulSet, or any custom resource that has a /scale subresource. You define it alongside your workload.</p><p>Here is a minimal example that scales a worker deployment based on an AWS SQS queue:</p><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: order-processor-scaler<br>  namespace: production<br>spec:<br>  scaleTargetRef:<br>    name: order-processor          # Name of your Deployment<br>  pollingInterval: 15              # Check queue every 15 seconds<br>  cooldownPeriod: 60               # Wait 60s before scaling down<br>  minReplicaCount: 0               # Scale to zero when queue is empty<br>  maxReplicaCount: 20              # Never exceed 20 pods<br>  triggers:<br>    - type: aws-sqs-queue<br>      authenticationRef:<br>        name: keda-trigger-auth-aws  # Reference to TriggerAuthentication<br>      metadata:<br>        queueURL: https://sqs.us-east-1.amazonaws.com/123456789/order-queue<br>        queueLength: &quot;10&quot;           # Target: 10 messages per pod<br>        awsRegion: us-east-1</pre><p>With this config, KEDA will:</p><ul><li>Scale to 0 pods when the queue is empty</li><li>Scale up when messages arrive (1 pod per 10 messages, up to 20)</li><li>Wait 60 seconds of empty queue before scaling back to 0</li></ul><h4>ScaledJob</h4><p>A ScaledJob is used for batch workloads where each job processes a fixed unit of work and then exits. Instead of scaling a long-running deployment, it creates new Kubernetes Job objects as the event source grows.</p><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledJob<br>metadata:<br>  name: image-resize-job<br>  namespace: production<br>spec:<br>  jobTargetRef:<br>    template:<br>      spec:<br>        containers:<br>          - name: image-resizer<br>            image: myapp/image-resizer:latest<br>        restartPolicy: Never<br>  pollingInterval: 30<br>  maxReplicaCount: 50<br>  triggers:<br>    - type: rabbitmq<br>      metadata:<br>        queueName: image-resize-tasks<br>        host: amqp://rabbitmq.production.svc.cluster.local<br>        queueLength: &quot;1&quot;  # One job per message</pre><h4>TriggerAuthentication</h4><p>Most scalers need credentials to access the event source. Rather than putting secrets directly in the ScaledObject, KEDA provides a TriggerAuthentication resource that separates credentials from scaling config.</p><pre>apiVersion: keda.sh/v1alpha1<br>kind: TriggerAuthentication<br>metadata:<br>  name: keda-trigger-auth-aws<br>  namespace: production<br>spec:<br>  secretTargetRef:<br>    - parameter: awsAccessKeyID<br>      name: aws-credentials<br>      key: AWS_ACCESS_KEY_ID<br>    - parameter: awsSecretAccessKey<br>      name: aws-credentials<br>      key: AWS_SECRET_ACCESS_KEY</pre><p>You can also use pod identity (IAM roles for service accounts in EKS, Workload Identity in GKE) to avoid static credentials entirely, which is the recommended approach in production.</p><h3>Code Examples</h3><h4>Python: Publishing Events to Trigger Scaling</h4><p>This is a producer script that pushes messages to an SQS queue. As this publishes work, KEDA will detect the growing queue and scale your consumer pods accordingly.</p><pre>import boto3<br>import json<br>import time<br>import logging<br>from dataclasses import dataclass, asdict<br>from typing import Optional<br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br><br>@dataclass<br>class OrderEvent:<br>    order_id: str<br>    customer_id: str<br>    total_amount: float<br>    items_count: int<br>    priority: str = &quot;normal&quot;<br><br><br>class OrderPublisher:<br>    &quot;&quot;&quot;<br>    Publishes order events to SQS.<br>    KEDA will watch this queue and scale the consumer deployment<br>    based on the number of messages waiting.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, queue_url: str, region: str = &quot;us-east-1&quot;):<br>        self.queue_url = queue_url<br>        self.sqs = boto3.client(&quot;sqs&quot;, region_name=region)<br><br>    def publish(self, event: OrderEvent) -&gt; Optional[str]:<br>        try:<br>            response = self.sqs.send_message(<br>                QueueUrl=self.queue_url,<br>                MessageBody=json.dumps(asdict(event)),<br>                MessageAttributes={<br>                    &quot;Priority&quot;: {<br>                        &quot;StringValue&quot;: event.priority,<br>                        &quot;DataType&quot;: &quot;String&quot;,<br>                    }<br>                },<br>            )<br>            message_id = response[&quot;MessageId&quot;]<br>            logger.info(f&quot;Published order {event.order_id} -&gt; MessageId: {message_id}&quot;)<br>            return message_id<br>        except Exception as e:<br>            logger.error(f&quot;Failed to publish order {event.order_id}: {e}&quot;)<br>            return None<br><br>    def publish_batch(self, events: list[OrderEvent]) -&gt; dict:<br>        &quot;&quot;&quot;<br>        SQS supports up to 10 messages per batch.<br>        Batching reduces API calls and is cheaper.<br>        &quot;&quot;&quot;<br>        results = {&quot;success&quot;: 0, &quot;failed&quot;: 0}<br><br>        # Chunk into groups of 10<br>        for i in range(0, len(events), 10):<br>            batch = events[i : i + 10]<br>            entries = [<br>                {<br>                    &quot;Id&quot;: str(idx),<br>                    &quot;MessageBody&quot;: json.dumps(asdict(event)),<br>                }<br>                for idx, event in enumerate(batch)<br>            ]<br><br>            try:<br>                response = self.sqs.send_message_batch(<br>                    QueueUrl=self.queue_url,<br>                    Entries=entries,<br>                )<br>                results[&quot;success&quot;] += len(response.get(&quot;Successful&quot;, []))<br>                results[&quot;failed&quot;] += len(response.get(&quot;Failed&quot;, []))<br>            except Exception as e:<br>                logger.error(f&quot;Batch send failed: {e}&quot;)<br>                results[&quot;failed&quot;] += len(batch)<br><br>        return results<br><br><br>def simulate_order_spike(publisher: OrderPublisher, count: int = 500):<br>    &quot;&quot;&quot;<br>    Simulates a burst of orders.<br>    Watch your KEDA-managed pods scale up in response.<br>    &quot;&quot;&quot;<br>    import uuid<br>    import random<br><br>    logger.info(f&quot;Simulating {count} orders. Watch KEDA scale your consumer pods...&quot;)<br><br>    events = [<br>        OrderEvent(<br>            order_id=str(uuid.uuid4()),<br>            customer_id=f&quot;cust_{random.randint(1000, 9999)}&quot;,<br>            total_amount=round(random.uniform(10.0, 500.0), 2),<br>            items_count=random.randint(1, 10),<br>            priority=random.choice([&quot;normal&quot;, &quot;high&quot;]),<br>        )<br>        for _ in range(count)<br>    ]<br><br>    result = publisher.publish_batch(events)<br>    logger.info(f&quot;Batch publish complete: {result}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    QUEUE_URL = &quot;https://sqs.us-east-1.amazonaws.com/123456789/order-queue&quot;<br><br>    publisher = OrderPublisher(queue_url=QUEUE_URL)<br>    simulate_order_spike(publisher, count=500)<br><br>    # KEDA polling interval is 15s.<br>    # Within ~15-30 seconds you should see pods scaling up.<br>    # Run: kubectl get pods -w -n production</pre><h4>Go: A Consumer Worker That KEDA Scales</h4><p>This is the consumer side. KEDA will run as many copies of this worker as needed to drain the queue, then scale it down to zero when the queue is empty.</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br><br> &quot;github.com/aws/aws-sdk-go-v2/aws&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/config&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/sqs&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/sqs/types&quot;<br>)<br><br>// OrderEvent mirrors the structure published by the Python producer<br>type OrderEvent struct {<br> OrderID      string  `json:&quot;order_id&quot;`<br> CustomerID   string  `json:&quot;customer_id&quot;`<br> TotalAmount  float64 `json:&quot;total_amount&quot;`<br> ItemsCount   int     `json:&quot;items_count&quot;`<br> Priority     string  `json:&quot;priority&quot;`<br>}<br><br>type OrderWorker struct {<br> client   *sqs.Client<br> queueURL string<br> logger   *log.Logger<br>}<br><br>func NewOrderWorker(queueURL string) (*OrderWorker, error) {<br> cfg, err := config.LoadDefaultConfig(context.Background())<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;failed to load AWS config: %w&quot;, err)<br> }<br><br> return &amp;OrderWorker{<br>  client:   sqs.NewFromConfig(cfg),<br>  queueURL: queueURL,<br>  logger:   log.New(os.Stdout, &quot;[order-worker] &quot;, log.LstdFlags),<br> }, nil<br>}<br><br>// processOrder is your business logic. Replace this with your actual work.<br>func (w *OrderWorker) processOrder(event OrderEvent) error {<br> w.logger.Printf(&quot;Processing order %s for customer %s (amount: $%.2f, priority: %s)&quot;,<br>  event.OrderID, event.CustomerID, event.TotalAmount, event.Priority)<br><br> // Simulate processing time (DB write, API call, etc.)<br> processingTime := 100 * time.Millisecond<br> if event.Priority == &quot;high&quot; {<br>  processingTime = 50 * time.Millisecond<br> }<br> time.Sleep(processingTime)<br><br> return nil<br>}<br><br>// deleteMessage removes the message from the queue after successful processing.<br>// If we crash before this, SQS will redeliver the message. This is intentional.<br>func (w *OrderWorker) deleteMessage(ctx context.Context, msg types.Message) error {<br> _, err := w.client.DeleteMessage(ctx, &amp;sqs.DeleteMessageInput{<br>  QueueUrl:      aws.String(w.queueURL),<br>  ReceiptHandle: msg.ReceiptHandle,<br> })<br> return err<br>}<br><br>// Run is the main polling loop. KEDA will scale up more instances of this<br>// worker based on queue depth. Each instance runs its own loop.<br>func (w *OrderWorker) Run(ctx context.Context) {<br> w.logger.Println(&quot;Worker starting. Polling for messages...&quot;)<br><br> for {<br>  select {<br>  case &lt;-ctx.Done():<br>   w.logger.Println(&quot;Context cancelled, worker shutting down gracefully&quot;)<br>   return<br>  default:<br>   w.poll(ctx)<br>  }<br> }<br>}<br><br>func (w *OrderWorker) poll(ctx context.Context) {<br> // Long-poll for up to 20 seconds. This reduces empty API calls significantly.<br> result, err := w.client.ReceiveMessage(ctx, &amp;sqs.ReceiveMessageInput{<br>  QueueUrl:            aws.String(w.queueURL),<br>  MaxNumberOfMessages: 10,         // Process up to 10 messages per poll<br>  WaitTimeSeconds:     20,         // Long-polling: wait up to 20s for messages<br>  VisibilityTimeout:   60,         // Message invisible to other workers for 60s<br> })<br> if err != nil {<br>  if ctx.Err() != nil {<br>   return // Context cancelled, exit cleanly<br>  }<br>  w.logger.Printf(&quot;Error receiving messages: %v&quot;, err)<br>  time.Sleep(5 * time.Second) // Back off on error<br>  return<br> }<br><br> if len(result.Messages) == 0 {<br>  // No messages. KEDA will eventually scale this pod down.<br>  return<br> }<br><br> for _, msg := range result.Messages {<br>  var event OrderEvent<br>  if err := json.Unmarshal([]byte(*msg.Body), &amp;event); err != nil {<br>   w.logger.Printf(&quot;Failed to unmarshal message %s: %v&quot;, *msg.MessageId, err)<br>   continue // Leave message in queue for retry<br>  }<br><br>  if err := w.processOrder(event); err != nil {<br>   w.logger.Printf(&quot;Failed to process order %s: %v&quot;, event.OrderID, err)<br>   continue // SQS will redeliver after visibility timeout<br>  }<br><br>  // Delete only after successful processing (at-least-once delivery)<br>  if err := w.deleteMessage(ctx, msg); err != nil {<br>   w.logger.Printf(&quot;Failed to delete message for order %s: %v&quot;, event.OrderID, err)<br>  }<br> }<br>}<br><br>func main() {<br> queueURL := os.Getenv(&quot;SQS_QUEUE_URL&quot;)<br> if queueURL == &quot;&quot; {<br>  log.Fatal(&quot;SQS_QUEUE_URL environment variable is required&quot;)<br> }<br><br> worker, err := NewOrderWorker(queueURL)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to create worker: %v&quot;, err)<br> }<br><br> // Graceful shutdown: wait for SIGTERM (sent by Kubernetes during pod termination)<br> ctx, cancel := context.WithCancel(context.Background())<br> defer cancel()<br><br> sigCh := make(chan os.Signal, 1)<br> signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)<br><br> go func() {<br>  sig := &lt;-sigCh<br>  log.Printf(&quot;Received signal %v, initiating graceful shutdown...&quot;, sig)<br>  cancel()<br> }()<br><br> worker.Run(ctx)<br> log.Println(&quot;Worker exited cleanly.&quot;)<br>}</pre><h4>The Kubernetes Deployment for the Go Worker</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-processor<br>  namespace: production<br>spec:<br>  replicas: 0   # Start at zero. KEDA will manage this.<br>  selector:<br>    matchLabels:<br>      app: order-processor<br>  template:<br>    metadata:<br>      labels:<br>        app: order-processor<br>    spec:<br>      terminationGracePeriodSeconds: 90  # Give workers time to finish current messages<br>      containers:<br>        - name: order-processor<br>          image: myapp/order-processor:latest<br>          env:<br>            - name: SQS_QUEUE_URL<br>              valueFrom:<br>                secretKeyRef:<br>                  name: sqs-config<br>                  key: queue_url<br>          resources:<br>            requests:<br>              cpu: &quot;100m&quot;<br>              memory: &quot;128Mi&quot;<br>            limits:<br>              cpu: &quot;500m&quot;<br>              memory: &quot;256Mi&quot;<br>---<br>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: order-processor-scaler<br>  namespace: production<br>spec:<br>  scaleTargetRef:<br>    name: order-processor<br>  pollingInterval: 15<br>  cooldownPeriod: 60<br>  minReplicaCount: 0<br>  maxReplicaCount: 30<br>  triggers:<br>    - type: aws-sqs-queue<br>      authenticationRef:<br>        name: aws-trigger-auth<br>      metadata:<br>        queueURL: https://sqs.us-east-1.amazonaws.com/123456789/order-queue<br>        queueLength: &quot;10&quot;<br>        awsRegion: us-east-1</pre><h4>A Kafka Scaler Example</h4><p>For teams using Kafka instead of SQS, here is how the ScaledObject looks:</p><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: kafka-consumer-scaler<br>  namespace: production<br>spec:<br>  scaleTargetRef:<br>    name: kafka-order-consumer<br>  pollingInterval: 10<br>  cooldownPeriod: 120<br>  minReplicaCount: 1      # Keep at least 1 for Kafka (consumer group coordination)<br>  maxReplicaCount: 25<br>  triggers:<br>    - type: kafka<br>      metadata:<br>        bootstrapServers: kafka-broker-0.kafka:9092,kafka-broker-1.kafka:9092<br>        consumerGroup: order-processors<br>        topic: orders<br>        lagThreshold: &quot;50&quot;   # Scale up when consumer lag exceeds 50 messages per partition<br>        offsetResetPolicy: latest</pre><p>Note: For Kafka, it is usually safer to set minReplicaCount: 1 because consumer group rebalancing can be slow when scaling from zero.</p><h3>How KEDA Cuts Your Cloud Bills with Zero-to-Scale</h3><p>This is the part most articles gloss over, but it is genuinely significant.</p><h4>The Zero-Replica Feature</h4><p>Traditional autoscaling has a hard floor. You cannot scale below the minimum HPA replica count, and most teams set that to 2 or 3 for availability. This means your worker services are always running, always consuming node resources, even at 3am when there is nothing to process.</p><p>KEDA removes this floor. When there are zero messages in your queue, it patches the deployment to 0 replicas. Zero pods means zero resource consumption on that node. If all workloads on a node scale to zero, the node itself can be removed by the cluster autoscaler (Karpenter, GKE Autopilot, AKS Cluster Autoscaler).</p><h4>A Real-World Cost Example</h4><p>Imagine you have 5 worker deployments, each running a minimum of 3 pods with 0.5 CPU and 512Mi memory. At baseline (off-peak hours, roughly 12 hours per day):</p><pre>Without KEDA:<br>  5 deployments x 3 pods x 0.5 CPU = 7.5 CPU cores always reserved<br>  5 deployments x 3 pods x 512Mi  = 7.5 GB memory always reserved<br><br>  Typical cost on a mid-tier cloud instance:<br>  ~3 nodes (t3.xlarge at ~$150/month each) = $450/month baseline<br><br>With KEDA (zero-scale during off-peak 12h):<br>  Off-peak pods = 0 across all 5 deployments<br>  Nodes can shrink from 3 -&gt; 1 during off-peak<br>  Savings: ~$300/month on compute = $3,600/year</pre><p>This is a conservative estimate for a small cluster. At larger scale, the savings compound.</p><h4>Scale-to-Zero is Not Just for Workers</h4><p>KEDA is increasingly being used with the HTTP Add-on to scale web services to zero for non-production environments. Staging and development environments that sit idle 16+ hours a day are ideal candidates. A staging environment that auto-scales to zero at night can save 60–70% of its running cost with zero manual intervention.</p><h4>The Scaling Math: How Replicas Are Calculated</h4><p>KEDA uses a simple formula that is worth understanding:</p><pre>desiredReplicas = ceil(currentMetricValue / targetMetricValue)<br><br>Example (SQS):<br>  currentMetricValue = 450 messages in queue<br>  targetMetricValue  = 10 messages per pod (set in ScaledObject)<br>  desiredReplicas    = ceil(450 / 10) = 45 pods (capped at maxReplicaCount)</pre><p>You tune the queueLength or lagThreshold parameter to control how aggressively KEDA scales. A lower threshold means more pods for the same queue depth (faster processing, higher cost). A higher threshold means fewer pods (slower processing, lower cost). This is a business tradeoff you tune based on your SLA requirements.</p><h4>Cooldown Period: Avoiding Thrashing</h4><p>The cooldownPeriod is critical for cost control. It prevents KEDA from scaling down too aggressively and then immediately scaling back up (which wastes pod startup time and creates noisy cluster activity). A value between 60 and 300 seconds is typical depending on how bursty your workload is.</p><h3>Pros and Cons of KEDA</h3><h4>Pros</h4><p><strong>Rich ecosystem of scalers out of the box.</strong> With 50+ built-in scalers, chances are your event source is already supported. You write a YAML file, not a custom metrics pipeline.</p><p><strong>True zero-to-scale.</strong> The ability to scale to zero replicas is a genuine differentiator from standard HPA. This directly translates to lower cloud bills, especially for batch and background workloads.</p><p><strong>Works alongside existing HPA.</strong> KEDA does not replace your HPA. It extends it. You can still scale on CPU/memory alongside custom event metrics by adding both triggers to your ScaledObject.</p><p><strong>CNCF graduated project.</strong> KEDA is not a side project. It is a production-proven, CNCF-graduated tool with strong support from Microsoft, Red Hat, and a large contributor community.</p><p><strong>Separation of authentication concerns.</strong> The TriggerAuthentication resource keeps credentials separate from scaling config, which makes it easier to manage secrets across environments.</p><p><strong>Works with any scalable Kubernetes resource.</strong> Deployments, StatefulSets, custom resources (anything with a /scale subresource) are all fair game.</p><p><strong>Custom external scalers.</strong> If you have a niche event source, you can implement a custom scaler using gRPC and register it with KEDA. The extension model is clean and well documented.</p><h4>Cons</h4><p><strong>Scale-from-zero has cold start latency.</strong> When a deployment is at 0 replicas and the first message arrives, KEDA needs to spin up a pod. This takes time: KEDA polling interval (up to 15s) + pod scheduling time + container startup time. For latency-sensitive workloads, this can be noticeable. Mitigation: set minReplicaCount: 1 if cold start latency is not acceptable.</p><p><strong>Polling-based, not push-based.</strong> KEDA polls your event source on an interval. This means there is always some lag between “work arrived” and “scaling decision made.” Most teams find 10–15 second polling intervals acceptable, but it is not instantaneous.</p><p><strong>Operational overhead of TriggerAuthentication.</strong> Managing credentials for 10+ scalers across multiple namespaces can get complex. You need a solid secrets management strategy (Vault, External Secrets Operator, or pod identity) or it becomes a maintenance burden.</p><p><strong>Kafka minimum replica considerations.</strong> Scaling a Kafka consumer group to zero requires careful handling. Consumer group rebalances can be slow, and scaling from 0 means rejoining the group. Many teams keep minReplicaCount: 1 for Kafka consumers which reduces but does not eliminate savings.</p><p><strong>Metrics API dependency.</strong> KEDA runs its own metrics API server. If this component has issues, HPA can no longer fetch external metrics, which can affect scaling decisions. Running KEDA with high availability (multiple replicas) is important in production.</p><p><strong>Learning curve for custom scalers.</strong> Writing a custom external scaler requires familiarity with gRPC and the KEDA external scaler protocol. It is doable but adds complexity compared to using a built-in scaler.</p><h3>Conclusion</h3><p>KEDA is one of those tools that, once you start using it, makes you wonder how you managed without it. It closes a real gap in Kubernetes: the inability to scale workloads on the actual signals that matter for event-driven systems.</p><p>The zero-to-scale capability alone is worth the adoption cost for most teams. Background workers, batch processors, and non-production environments sitting idle for hours every day are burning money they do not need to. KEDA turns those idle replicas into zero replicas, and zero replicas cost zero compute dollars.</p><p>The setup is straightforward: install via Helm, define a ScaledObject alongside your deployment, point it at your event source, and you are done. The Python and Go examples in this post give you a working foundation for a queue-based worker pattern that you can adapt to your actual workload.</p><p>A few practical recommendations before you ship KEDA to production:</p><ul><li>Use pod identity (IAM roles for service accounts, Workload Identity) instead of static credentials in TriggerAuthentication</li><li>Start with pollingInterval: 15 and tune down if you need faster response</li><li>Set cooldownPeriod based on how bursty your workload is (60-300 seconds is typical)</li><li>For Kafka consumers, lean toward minReplicaCount: 1 unless you can tolerate cold start latency</li><li>Monitor the KEDA metrics API server as a critical component and run it with at least 2 replicas in production</li></ul><p>The KEDA documentation at <a href="https://keda.sh/">keda.sh</a> has excellent scaler-specific examples for every supported event source, and the GitHub issues and discussions are active and responsive.</p><p>Your cloud bill will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42cc40c35415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAP BTP: The Enterprise Cloud Platform Backend Developers Need to Understand]]></title>
            <link>https://medium.com/@mgaurang123/sap-btp-the-enterprise-cloud-platform-backend-developers-need-to-understand-94a702b91111?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/94a702b91111</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[sap]]></category>
            <category><![CDATA[s4-hana]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Fri, 15 May 2026 15:29:25 GMT</pubDate>
            <atom:updated>2026-05-15T15:29:25.275Z</atom:updated>
            <content:encoded><![CDATA[<p>If you work at a company running SAP ERP, S/4HANA, or any SAP backend system, you have almost certainly heard the term “SAP BTP” thrown around in architecture meetings. For many backend engineers outside the SAP ecosystem, BTP can feel like a black box: a cloud platform that does… something SAP-related.</p><p>This post cuts through the noise. We will look at what SAP BTP actually is, why it exists, how it compares to AWS, Azure, and GCP, and when it makes sense to use it. Along the way, we will write real code to interact with BTP services using Python and Go.</p><p>Whether you are evaluating BTP for a new project, extending an existing SAP landscape, or just trying to understand what the enterprise architects at your company keep talking about, this guide is for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUYuC-0xDeSMF2JeLK3IxA.png" /></figure><h3>What is SAP BTP?</h3><p>SAP Business Technology Platform (BTP) is SAP’s unified cloud platform for building, integrating, and extending enterprise applications. Think of it as SAP’s answer to AWS or Azure, but purpose-built for enterprise workloads that live in and around SAP systems.</p><p>BTP is not just one product. It is a collection of services, tools, and runtime environments organized under a single commercial and technical umbrella. The four main pillars are:</p><pre>+----------------------------------------------------------+<br>|                      SAP BTP                             |<br>|                                                          |<br>|  +-------------+  +-------------+  +------------------+ |<br>|  |  Database   |  |  Analytics  |  |   Integration    | |<br>|  |  &amp; Data     |  |  &amp; Planning |  |   (iPaaS)        | |<br>|  |  Management |  |             |  |                  | |<br>|  +-------------+  +-------------+  +------------------+ |<br>|                                                          |<br>|  +-----------------------------------------------------+ |<br>|  |         Application Development &amp; Automation        | |<br>|  |    (Cloud Foundry, Kyma/Kubernetes, ABAP env)        | |<br>|  +-----------------------------------------------------+ |<br>+----------------------------------------------------------+</pre><p><strong>Database and Data Management</strong> covers SAP HANA Cloud, SAP Datasphere (formerly Data Warehouse Cloud), and data lake services.</p><p><strong>Analytics and Planning</strong> includes SAP Analytics Cloud, which provides BI, planning, and predictive capabilities.</p><p><strong>Integration</strong> is SAP Integration Suite, which handles API management, EDI, event mesh, and process integration.</p><p><strong>Application Development and Automation</strong> is where developers spend most of their time. This pillar provides multiple runtime environments: Cloud Foundry, Kyma (Kubernetes-based), and the ABAP environment for traditional SAP developers.</p><h3>Why Was SAP BTP Introduced?</h3><p>SAP’s traditional product portfolio was deeply on-premise. Systems like R/3, ECC, and the classic BW ran in your own data center. Extending these systems meant writing ABAP code that ran inside the same system. That model worked for decades but created significant problems as businesses moved to the cloud.</p><p><strong>The problem SAP needed to solve:</strong></p><p>Organizations running SAP had no clean way to build cloud-native extensions without either hacking directly into the core system (which made upgrades painful) or building completely separate systems that had no native connection to SAP data.</p><p>SAP introduced the “Clean Core” philosophy alongside BTP. The idea is simple: keep your SAP S/4HANA or ECC system clean and unmodified, and push all custom logic, extensions, and integrations out to BTP. This decouples your custom code from SAP upgrades, reduces technical debt, and lets teams use modern development practices.</p><p>BTP also emerged because SAP recognized that enterprise customers needed a single place to connect SAP software with non-SAP systems, hyperscaler services, and custom applications. Rather than asking customers to build those bridges entirely themselves, SAP packaged pre-built connectors, integration flows, and cloud services into BTP.</p><h3>How SAP BTP Differs from AWS, Azure, and GCP</h3><p>This is the question most backend engineers ask first, and the honest answer is: BTP is not trying to compete with AWS, Azure, or GCP in the general-purpose cloud space. It has a very different purpose.</p><h4>The Core Difference</h4><p>AWS, Azure, and GCP are horizontal platforms. They give you raw compute, storage, networking, and managed services that you assemble into whatever you need. They are industry-agnostic.</p><p>SAP BTP is a vertical platform. It is built specifically for enterprise business applications, with deep pre-built integration into SAP’s ecosystem. It assumes you are dealing with business objects like sales orders, materials, financial documents, and business partners.</p><pre>General-Purpose Cloud (AWS/Azure/GCP)<br>+------------------------------------------+<br>|  Raw Infra + Managed Services             |<br>|  You build the business logic             |<br>|  You build SAP connectors yourself        |<br>+------------------------------------------+<br><br>SAP BTP<br>+------------------------------------------+<br>|  Pre-built SAP connectivity &amp; APIs        |<br>|  Business-aware runtime environments      |<br>|  SAP data models baked in                 |<br>|  You focus on business extension logic    |<br>+------------------------------------------+</pre><h4>Development Experience</h4><p>On AWS, you write a Lambda function or an ECS service that connects to SAP via custom RFC or OData clients that you build and maintain yourself.</p><p>On BTP, you write a Cloud Foundry or Kyma service, and the platform’s Destination Service, Connectivity Service, and pre-built SAP connectors handle the secure tunnel to your on-premise SAP system. The boilerplate is already done.</p><h4>Multi-Cloud Position</h4><p>BTP does not run its own global infrastructure to the same scale as AWS or GCP. It runs on top of hyperscalers. Depending on the region, your BTP subaccount may be running on AWS, Azure, or GCP infrastructure underneath. SAP manages the BTP layer on top.</p><p>This means BTP is closer to a managed PaaS offering than a full IaaS. You do not manage virtual machines, VPCs, or bare-metal servers through BTP. You deploy applications, configure services, and consume APIs.</p><h3>What SAP BTP Offers Beyond Other Platforms</h3><p>Here is what BTP genuinely offers that you cannot easily replicate on a generic cloud:</p><h4>1. SAP Business Accelerator Hub and Pre-Built APIs</h4><p>BTP comes with access to SAP’s API Business Hub, which contains thousands of pre-built, documented APIs for SAP S/4HANA, SuccessFactors, Ariba, and other SAP products. You consume these APIs in your extensions without writing custom RFC or BAPI wrappers.</p><h4>2. Event Mesh and SAP Event Broker</h4><p>SAP Event Mesh lets you decouple your BTP extensions from the SAP backend using event-driven architecture. When a sales order is created in S/4HANA, it publishes an event. Your microservice on BTP subscribes to that event. No polling, no tight coupling.</p><h4>3. SAP HANA Cloud</h4><p>HANA Cloud is not just a database. It includes in-memory columnar storage, native geospatial processing, graph processing, and a machine learning integration layer. For applications processing large SAP datasets, having HANA Cloud natively on the same platform is a significant advantage.</p><h4>4. Integration Suite with Pre-Built Content</h4><p>SAP Integration Suite ships with thousands of pre-built integration flows (iFlows) called Integration Content Advisor packages. If you need to integrate SAP with Salesforce, Workday, Microsoft 365, or hundreds of other enterprise systems, there is a pre-built template you can configure rather than build from scratch.</p><h4>5. ABAP Environment</h4><p>BTP has an ABAP runtime environment. This is huge for organizations with decades of ABAP logic. Developers can modernize ABAP code and run it cloud-natively on BTP without rewriting everything in a new language. This is something no other cloud platform offers.</p><h4>6. SAP Build (Low-Code and Process Automation)</h4><p>BTP includes SAP Build, a suite of low-code tools for building apps, automating processes with RPA, and composing workflows. For enterprise environments where non-developers need to build automations, this is built into the platform.</p><h3>BTP Equivalent Services Compared to Other Platforms</h3><pre>| Capability               | AWS                     | Azure                   | GCP                     |<br>|--------------------------|-------------------------|-------------------------|-------------------------|<br>| App Runtime (PaaS)       | Elastic Beanstalk       | App Service             | App Engine              |<br>| Containers / K8s         | EKS                     | AKS                     | GKE                     |<br>| Serverless Functions     | Lambda                  | Azure Functions         | Cloud Functions         |<br>| API Management           | API Gateway             | API Management          | Apigee                  |<br>| Integration / iPaaS      | EventBridge + Step Fns  | Logic Apps + Svc Bus    | Pub/Sub + Workflows     |<br>| Event Streaming          | Kinesis / MSK           | Event Hubs              | Pub/Sub                 |<br>| Relational Database      | RDS                     | Azure SQL               | Cloud SQL               |<br>| Data Warehouse           | Redshift                | Synapse Analytics       | BigQuery                |<br>| Identity &amp; Auth          | IAM + Cognito           | Azure AD + B2C          | IAM + Identity Platform |<br>| CI/CD                    | CodePipeline            | Azure DevOps            | Cloud Build             |<br>| Low-Code App Builder     | Honeycode (disc.)       | Power Apps              | AppSheet                |<br>| Workflow Automation      | Step Functions          | Power Automate          | Workflows               |<br>| Monitoring &amp; Logging     | CloudWatch              | Azure Monitor           | Cloud Logging           |<br>| Secret Management        | Secrets Manager         | Key Vault               | Secret Manager          |<br>| Object Storage           | S3                      | Blob Storage            | Cloud Storage           |</pre><h3>Code Examples</h3><p>Let us look at two practical scenarios: calling a BTP API protected by OAuth2 using Python, and publishing a message to SAP Event Mesh using Go.</p><h4>Prerequisites</h4><p>Before running either example, you need:</p><ul><li>A BTP subaccount with the relevant service instance created</li><li>Service binding credentials (usually a JSON object with client ID, client secret, token URL, and endpoint URL)</li></ul><p>BTP uses OAuth2 client credentials flow for machine-to-machine authentication. Both examples follow this pattern:</p><pre>Your App --&gt; POST /oauth/token --&gt; Get access token<br>Your App --&gt; API call with Bearer token --&gt; BTP Service</pre><h4>Python: Calling a BTP OData API via Destination Service</h4><p>This example fetches business partner data from an S/4HANA system connected through BTP’s Destination Service.</p><pre>import os<br>import requests<br>from typing import Optional<br><br># Service binding credentials injected via environment variables<br># In BTP, these come from the service binding in CF or Kyma secret<br>OAUTH_CLIENT_ID = os.environ[&quot;BTP_CLIENT_ID&quot;]<br>OAUTH_CLIENT_SECRET = os.environ[&quot;BTP_CLIENT_SECRET&quot;]<br>OAUTH_TOKEN_URL = os.environ[&quot;BTP_TOKEN_URL&quot;]<br>DESTINATION_SERVICE_URL = os.environ[&quot;BTP_DESTINATION_URL&quot;]<br><br><br>def get_access_token(client_id: str, client_secret: str, token_url: str) -&gt; str:<br>    &quot;&quot;&quot;Fetch OAuth2 access token using client credentials flow.&quot;&quot;&quot;<br>    response = requests.post(<br>        token_url,<br>        data={<br>            &quot;grant_type&quot;: &quot;client_credentials&quot;,<br>            &quot;client_id&quot;: client_id,<br>            &quot;client_secret&quot;: client_secret,<br>        },<br>        headers={&quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;},<br>        timeout=10,<br>    )<br>    response.raise_for_status()<br>    return response.json()[&quot;access_token&quot;]<br><br><br>def get_destination(token: str, destination_name: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Retrieve destination configuration from BTP Destination Service.<br>    The destination holds the URL and credentials for the backend system (e.g., S/4HANA).<br>    &quot;&quot;&quot;<br>    url = f&quot;{DESTINATION_SERVICE_URL}/destination-configuration/v1/destinations/{destination_name}&quot;<br>    response = requests.get(<br>        url,<br>        headers={&quot;Authorization&quot;: f&quot;Bearer {token}&quot;},<br>        timeout=10,<br>    )<br>    response.raise_for_status()<br>    return response.json()<br><br><br>def fetch_business_partners(<br>    destination: dict,<br>    token: str,<br>    top: int = 10,<br>    filter_str: Optional[str] = None,<br>) -&gt; list[dict]:<br>    &quot;&quot;&quot;<br>    Call SAP S/4HANA Business Partner OData API via BTP Destination.<br>    The destination object contains the backend URL and auth headers.<br>    &quot;&quot;&quot;<br>    backend_url = destination[&quot;destinationConfiguration&quot;][&quot;URL&quot;]<br>    odata_endpoint = f&quot;{backend_url}/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner&quot;<br><br>    params = {<br>        &quot;$top&quot;: top,<br>        &quot;$format&quot;: &quot;json&quot;,<br>        &quot;$select&quot;: &quot;BusinessPartner,BusinessPartnerFullName,BusinessPartnerType&quot;,<br>    }<br><br>    if filter_str:<br>        params[&quot;$filter&quot;] = filter_str<br><br>    # BTP Connectivity Service injects SAP-Connectivity-Authentication header<br>    # when routing through the Cloud Connector for on-premise systems<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {token}&quot;,<br>        &quot;SAP-Connectivity-Authentication&quot;: f&quot;Bearer {token}&quot;,<br>    }<br><br>    response = requests.get(<br>        odata_endpoint,<br>        params=params,<br>        headers=headers,<br>        timeout=30,<br>    )<br>    response.raise_for_status()<br><br>    results = response.json().get(&quot;d&quot;, {}).get(&quot;results&quot;, [])<br>    return results<br><br><br>def main():<br>    print(&quot;Authenticating with SAP BTP...&quot;)<br>    token = get_access_token(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_TOKEN_URL)<br><br>    print(&quot;Fetching destination configuration...&quot;)<br>    destination = get_destination(token, destination_name=&quot;S4HANA_PROD&quot;)<br><br>    print(&quot;Fetching business partners from S/4HANA...&quot;)<br>    partners = fetch_business_partners(<br>        destination=destination,<br>        token=token,<br>        top=5,<br>        filter_str=&quot;BusinessPartnerType eq &#39;1&#39;&quot;,  # Only persons<br>    )<br><br>    print(f&quot;Found {len(partners)} business partners:\n&quot;)<br>    for bp in partners:<br>        print(f&quot;  ID: {bp[&#39;BusinessPartner&#39;]} | Name: {bp[&#39;BusinessPartnerFullName&#39;]}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>What is happening here:</strong></p><ol><li>We authenticate against BTP’s OAuth2 token endpoint using client credentials.</li><li>We call the BTP Destination Service to retrieve the configuration for a named destination (in this case, S4HANA_PROD). A destination in BTP is essentially a named connection profile that stores the backend URL, authentication method, and any proxy settings.</li><li>We call the S/4HANA OData API through the destination URL. The BTP Cloud Connector handles the secure tunnel to your on-premise S/4HANA if needed.</li></ol><h4>Python: Publishing an Event to SAP Event Mesh</h4><pre>import os<br>import json<br>import requests<br>from datetime import datetime, timezone<br>import uuid<br><br>OAUTH_CLIENT_ID = os.environ[&quot;EVENT_MESH_CLIENT_ID&quot;]<br>OAUTH_CLIENT_SECRET = os.environ[&quot;EVENT_MESH_CLIENT_SECRET&quot;]<br>OAUTH_TOKEN_URL = os.environ[&quot;EVENT_MESH_TOKEN_URL&quot;]<br>EVENT_MESH_URL = os.environ[&quot;EVENT_MESH_URL&quot;]  # e.g., https://&lt;namespace&gt;.enterprise-messaging.sap...<br><br><br>def get_access_token(client_id: str, client_secret: str, token_url: str) -&gt; str:<br>    response = requests.post(<br>        token_url,<br>        data={<br>            &quot;grant_type&quot;: &quot;client_credentials&quot;,<br>            &quot;client_id&quot;: client_id,<br>            &quot;client_secret&quot;: client_secret,<br>        },<br>        headers={&quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;},<br>        timeout=10,<br>    )<br>    response.raise_for_status()<br>    return response.json()[&quot;access_token&quot;]<br><br><br>def publish_event(token: str, topic: str, payload: dict) -&gt; None:<br>    &quot;&quot;&quot;<br>    Publish a CloudEvent to SAP Event Mesh.<br>    BTP Event Mesh supports the CloudEvents specification.<br>    &quot;&quot;&quot;<br>    url = f&quot;{EVENT_MESH_URL}/messagingrest/v1/topics/{topic}/messages&quot;<br><br>    # CloudEvents envelope<br>    # SAP Event Mesh follows the CloudEvents 1.0 spec<br>    cloud_event = {<br>        &quot;specversion&quot;: &quot;1.0&quot;,<br>        &quot;type&quot;: &quot;sap.s4.beh.salesorder.v1.SalesOrder.Created.v1&quot;,<br>        &quot;source&quot;: &quot;/btp/custom-extension/order-service&quot;,<br>        &quot;id&quot;: str(uuid.uuid4()),<br>        &quot;time&quot;: datetime.now(timezone.utc).isoformat(),<br>        &quot;datacontenttype&quot;: &quot;application/json&quot;,<br>        &quot;data&quot;: payload,<br>    }<br><br>    response = requests.post(<br>        url,<br>        json=cloud_event,<br>        headers={<br>            &quot;Authorization&quot;: f&quot;Bearer {token}&quot;,<br>            &quot;Content-Type&quot;: &quot;application/cloudevents+json&quot;,<br>            &quot;x-qos&quot;: &quot;1&quot;,  # Quality of service: at least once delivery<br>        },<br>        timeout=15,<br>    )<br>    response.raise_for_status()<br>    print(f&quot;Event published successfully. Status: {response.status_code}&quot;)<br><br><br>def main():<br>    token = get_access_token(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_TOKEN_URL)<br><br>    order_created_payload = {<br>        &quot;SalesOrder&quot;: &quot;0000012345&quot;,<br>        &quot;SoldToParty&quot;: &quot;CUST-001&quot;,<br>        &quot;TotalNetAmount&quot;: &quot;15000.00&quot;,<br>        &quot;TransactionCurrency&quot;: &quot;USD&quot;,<br>        &quot;RequestedDeliveryDate&quot;: &quot;2025-08-15&quot;,<br>    }<br><br>    publish_event(<br>        token=token,<br>        topic=&quot;sap/s4/beh/salesorder/v1/SalesOrder/Created/v1&quot;,<br>        payload=order_created_payload,<br>    )<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Go: Consuming Events from SAP Event Mesh (Long-Poll)</h4><p>SAP Event Mesh supports a REST-based messaging API for consuming messages via long polling. Here is a Go service that polls a queue and processes events.</p><pre>package main<br><br>import (<br> &quot;bytes&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;net/url&quot;<br> &quot;os&quot;<br> &quot;strings&quot;<br> &quot;time&quot;<br>)<br><br>// TokenResponse holds the OAuth2 token response from BTP<br>type TokenResponse struct {<br> AccessToken string `json:&quot;access_token&quot;`<br> ExpiresIn   int    `json:&quot;expires_in&quot;`<br> TokenType   string `json:&quot;token_type&quot;`<br>}<br><br>// CloudEvent represents a CloudEvents 1.0 envelope<br>type CloudEvent struct {<br> SpecVersion     string          `json:&quot;specversion&quot;`<br> Type            string          `json:&quot;type&quot;`<br> Source          string          `json:&quot;source&quot;`<br> ID              string          `json:&quot;id&quot;`<br> Time            string          `json:&quot;time&quot;`<br> DataContentType string          `json:&quot;datacontenttype&quot;`<br> Data            json.RawMessage `json:&quot;data&quot;`<br>}<br><br>// BTPConfig holds all configuration needed to connect to BTP Event Mesh<br>type BTPConfig struct {<br> ClientID     string<br> ClientSecret string<br> TokenURL     string<br> EventMeshURL string<br> QueueName    string<br>}<br><br>func loadConfig() BTPConfig {<br> return BTPConfig{<br>  ClientID:     os.Getenv(&quot;EVENT_MESH_CLIENT_ID&quot;),<br>  ClientSecret: os.Getenv(&quot;EVENT_MESH_CLIENT_SECRET&quot;),<br>  TokenURL:     os.Getenv(&quot;EVENT_MESH_TOKEN_URL&quot;),<br>  EventMeshURL: os.Getenv(&quot;EVENT_MESH_URL&quot;),<br>  QueueName:    os.Getenv(&quot;EVENT_MESH_QUEUE_NAME&quot;),<br> }<br>}<br><br>// getAccessToken fetches an OAuth2 token using client credentials flow<br>func getAccessToken(cfg BTPConfig) (string, error) {<br> formData := url.Values{}<br> formData.Set(&quot;grant_type&quot;, &quot;client_credentials&quot;)<br> formData.Set(&quot;client_id&quot;, cfg.ClientID)<br> formData.Set(&quot;client_secret&quot;, cfg.ClientSecret)<br><br> req, err := http.NewRequest(<br>  http.MethodPost,<br>  cfg.TokenURL,<br>  strings.NewReader(formData.Encode()),<br> )<br> if err != nil {<br>  return &quot;&quot;, fmt.Errorf(&quot;building token request: %w&quot;, err)<br> }<br> req.Header.Set(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;)<br><br> client := &amp;http.Client{Timeout: 10 * time.Second}<br> resp, err := client.Do(req)<br> if err != nil {<br>  return &quot;&quot;, fmt.Errorf(&quot;token request failed: %w&quot;, err)<br> }<br> defer resp.Body.Close()<br><br> if resp.StatusCode != http.StatusOK {<br>  body, _ := io.ReadAll(resp.Body)<br>  return &quot;&quot;, fmt.Errorf(&quot;token endpoint returned %d: %s&quot;, resp.StatusCode, string(body))<br> }<br><br> var tokenResp TokenResponse<br> if err := json.NewDecoder(resp.Body).Decode(&amp;tokenResp); err != nil {<br>  return &quot;&quot;, fmt.Errorf(&quot;decoding token response: %w&quot;, err)<br> }<br><br> return tokenResp.AccessToken, nil<br>}<br><br>// consumeMessage performs a long-poll on the BTP Event Mesh queue<br>// Returns the message body and an acknowledgment token<br>func consumeMessage(cfg BTPConfig, token string) ([]byte, string, error) {<br> queueURL := fmt.Sprintf(<br>  &quot;%s/messagingrest/v1/queues/%s/messages/consumption&quot;,<br>  cfg.EventMeshURL,<br>  url.PathEscape(cfg.QueueName),<br> )<br><br> req, err := http.NewRequest(http.MethodPost, queueURL, nil)<br> if err != nil {<br>  return nil, &quot;&quot;, fmt.Errorf(&quot;building consume request: %w&quot;, err)<br> }<br> req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+token)<br> req.Header.Set(&quot;x-qos&quot;, &quot;1&quot;) // At-least-once: requires explicit acknowledgment<br><br> // Long-poll timeout: wait up to 30 seconds for a message<br> client := &amp;http.Client{Timeout: 35 * time.Second}<br> resp, err := client.Do(req)<br> if err != nil {<br>  return nil, &quot;&quot;, fmt.Errorf(&quot;consume request failed: %w&quot;, err)<br> }<br> defer resp.Body.Close()<br><br> if resp.StatusCode == http.StatusNoContent {<br>  // No messages available<br>  return nil, &quot;&quot;, nil<br> }<br><br> if resp.StatusCode != http.StatusOK {<br>  body, _ := io.ReadAll(resp.Body)<br>  return nil, &quot;&quot;, fmt.Errorf(&quot;consume returned %d: %s&quot;, resp.StatusCode, string(body))<br> }<br><br> body, err := io.ReadAll(resp.Body)<br> if err != nil {<br>  return nil, &quot;&quot;, fmt.Errorf(&quot;reading message body: %w&quot;, err)<br> }<br><br> // BTP Event Mesh returns an acknowledgment token in the response header<br> ackToken := resp.Header.Get(&quot;x-ack-token&quot;)<br> return body, ackToken, nil<br>}<br><br>// acknowledgeMessage confirms successful processing of a message<br>// Without this, the message is redelivered after the visibility timeout<br>func acknowledgeMessage(cfg BTPConfig, token, ackToken string) error {<br> ackURL := fmt.Sprintf(<br>  &quot;%s/messagingrest/v1/queues/%s/messages/acknowledgment&quot;,<br>  cfg.EventMeshURL,<br>  url.PathEscape(cfg.QueueName),<br> )<br><br> ackPayload, _ := json.Marshal(map[string]string{&quot;ackToken&quot;: ackToken})<br><br> req, err := http.NewRequest(http.MethodPost, ackURL, bytes.NewReader(ackPayload))<br> if err != nil {<br>  return fmt.Errorf(&quot;building ack request: %w&quot;, err)<br> }<br> req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+token)<br> req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br> client := &amp;http.Client{Timeout: 10 * time.Second}<br> resp, err := client.Do(req)<br> if err != nil {<br>  return fmt.Errorf(&quot;ack request failed: %w&quot;, err)<br> }<br> defer resp.Body.Close()<br><br> if resp.StatusCode != http.StatusOK &amp;&amp; resp.StatusCode != http.StatusNoContent {<br>  return fmt.Errorf(&quot;ack returned unexpected status: %d&quot;, resp.StatusCode)<br> }<br><br> return nil<br>}<br><br>// processSalesOrderEvent handles a SalesOrder.Created CloudEvent<br>func processSalesOrderEvent(event CloudEvent) error {<br> log.Printf(&quot;Processing event: type=%s id=%s source=%s&quot;, event.Type, event.ID, event.Source)<br><br> var orderData map[string]interface{}<br> if err := json.Unmarshal(event.Data, &amp;orderData); err != nil {<br>  return fmt.Errorf(&quot;unmarshaling order data: %w&quot;, err)<br> }<br><br> // Your business logic here<br> // For example: write to your database, trigger a downstream workflow, etc.<br> log.Printf(&quot;Sales Order created: ID=%v, Customer=%v, Amount=%v %v&quot;,<br>  orderData[&quot;SalesOrder&quot;],<br>  orderData[&quot;SoldToParty&quot;],<br>  orderData[&quot;TotalNetAmount&quot;],<br>  orderData[&quot;TransactionCurrency&quot;],<br> )<br><br> return nil<br>}<br><br>func runConsumer(cfg BTPConfig) {<br> log.Println(&quot;Starting BTP Event Mesh consumer...&quot;)<br><br> // Token refresh: in production, implement token caching with expiry<br> token, err := getAccessToken(cfg)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to get initial token: %v&quot;, err)<br> }<br><br> tokenRefreshedAt := time.Now()<br><br> for {<br>  // Refresh token every 45 minutes (tokens typically expire after 60 min)<br>  if time.Since(tokenRefreshedAt) &gt; 45*time.Minute {<br>   log.Println(&quot;Refreshing access token...&quot;)<br>   token, err = getAccessToken(cfg)<br>   if err != nil {<br>    log.Printf(&quot;Token refresh failed: %v&quot;, err)<br>    time.Sleep(5 * time.Second)<br>    continue<br>   }<br>   tokenRefreshedAt = time.Now()<br>  }<br><br>  messageBody, ackToken, err := consumeMessage(cfg, token)<br>  if err != nil {<br>   log.Printf(&quot;Error consuming message: %v&quot;, err)<br>   time.Sleep(2 * time.Second)<br>   continue<br>  }<br><br>  if messageBody == nil {<br>   // No messages, poll again<br>   continue<br>  }<br><br>  var event CloudEvent<br>  if err := json.Unmarshal(messageBody, &amp;event); err != nil {<br>   log.Printf(&quot;Failed to parse CloudEvent: %v&quot;, err)<br>   // Acknowledge malformed messages to avoid infinite redelivery<br>   _ = acknowledgeMessage(cfg, token, ackToken)<br>   continue<br>  }<br><br>  if err := processSalesOrderEvent(event); err != nil {<br>   log.Printf(&quot;Failed to process event %s: %v&quot;, event.ID, err)<br>   // Do not acknowledge: message will be redelivered<br>   // In production, implement a dead-letter queue strategy<br>   continue<br>  }<br><br>  // Acknowledge successful processing<br>  if err := acknowledgeMessage(cfg, token, ackToken); err != nil {<br>   log.Printf(&quot;Warning: failed to acknowledge message %s: %v&quot;, event.ID, err)<br>  } else {<br>   log.Printf(&quot;Successfully processed and acknowledged event %s&quot;, event.ID)<br>  }<br> }<br>}<br><br>func main() {<br> cfg := loadConfig()<br> runConsumer(cfg)<br>}</pre><p><strong>What this Go consumer does:</strong></p><ol><li>Authenticates with BTP OAuth2 and manages token lifecycle.</li><li>Long-polls the Event Mesh queue for incoming messages.</li><li>Parses the CloudEvents envelope and dispatches to a handler.</li><li>Explicitly acknowledges messages after successful processing. If processing fails, the message is not acknowledged and gets redelivered, giving your service a chance to retry.</li></ol><p>This is the standard pattern for reliable event-driven services on BTP.</p><h3>Pros and Cons of SAP BTP</h3><h4>Pros</h4><p><strong>Deep SAP integration out of the box</strong> If your application needs to read from or write to S/4HANA, SuccessFactors, or Ariba, BTP removes weeks of integration work. The Destination Service, Cloud Connector, and pre-built OData clients handle the heavy lifting.</p><p><strong>Clean Core enablement</strong> BTP makes it practical to follow SAP’s Clean Core guidelines. You can extend SAP without modifying the core, which means your S/4HANA upgrade path stays clear.</p><p><strong>Pre-built integration content</strong> SAP Integration Suite ships with thousands of pre-built integration flows. Connecting SAP to Salesforce or Workday is configuration-heavy but not code-heavy.</p><p><strong>ABAP in the cloud</strong> The ABAP environment lets organizations bring existing ABAP logic to the cloud without a full rewrite. This is unique in the industry.</p><p><strong>Enterprise-grade identity management</strong> SAP Cloud Identity Services provides centralized identity, single sign-on, and user provisioning that integrates natively with all BTP services and SAP applications.</p><p><strong>Commercial simplicity within SAP contracts</strong> If your organization already has SAP licensing, adding BTP services often fits within existing enterprise agreements. Procurement is easier compared to signing separate cloud contracts.</p><h4>Cons</h4><p><strong>Steep learning curve for non-SAP developers</strong> BTP has its own terminology, account hierarchy (global account, subaccount, space, environment), service broker model, and tooling. Developers coming from AWS or Azure need significant ramp-up time.</p><p><strong>Limited compute options</strong> You are working within Cloud Foundry, Kyma, or ABAP runtimes. You do not have the raw EC2/VM flexibility of AWS or Azure. For certain workloads, this is a real constraint.</p><p><strong>Smaller community and ecosystem</strong> AWS and Azure have dramatically larger open-source communities, Stack Overflow answers, and third-party tooling. Finding BTP-specific answers to niche problems can mean reading SAP Notes or filing support tickets.</p><p><strong>Pricing complexity</strong> BTP pricing uses a credit-based model called CPEA (Cloud Platform Enterprise Agreement) or Pay-As-You-Go. Understanding what drives consumption and predicting costs is harder than reading an AWS Cost Explorer breakdown.</p><p><strong>Performance variability</strong> Because BTP runs on hyperscaler infrastructure underneath, performance characteristics can feel less predictable than working directly with AWS or GCP primitives.</p><p><strong>Not a general-purpose platform</strong> If your workload has nothing to do with SAP systems, using BTP instead of AWS or GCP adds overhead without benefit. BTP earns its complexity only in SAP-adjacent use cases.</p><h3>When to Use SAP BTP</h3><p>Use BTP when one or more of these conditions are true:</p><p><strong>Your application reads from or writes to SAP systems</strong> If your service needs SAP data (sales orders, materials, financial documents, HR records), BTP’s native connectivity saves significant integration effort.</p><p><strong>You are building a side-by-side extension to S/4HANA or ECC</strong> This is BTP’s primary use case. You want to add custom logic, a new UI, or a new process that complements the SAP system without modifying it. Examples: custom approval workflows, external-facing portals that read SAP data, AI-powered recommendations based on SAP transactional data.</p><p><strong>You need to integrate multiple SAP products with each other or with third-party systems</strong> SAP Integration Suite on BTP handles SAP-to-SAP and SAP-to-non-SAP integration better than building custom pipelines on a general cloud.</p><p><strong>Your organization has an existing SAP enterprise agreement</strong> If BTP is already licensed or available under your SAP contract, the procurement and commercial path is simpler.</p><p><strong>You are modernizing ABAP workloads</strong> The ABAP Cloud environment on BTP is the right home for ABAP code that needs to move out of the core system.</p><p><strong>Do not use BTP as a primary cloud if:</strong></p><ul><li>Your workload is entirely unrelated to SAP.</li><li>You need fine-grained control over compute, networking, or storage.</li><li>Your team has no SAP background and the project timeline does not allow for ramp-up.</li><li>You need a massive ecosystem of third-party tooling and open-source support.</li></ul><p>In these cases, AWS, Azure, or GCP are better choices. The two are not mutually exclusive either. Many enterprises run SAP BTP for their SAP extensions and a hyperscaler for their general-purpose workloads, connecting them via BTP’s Integration Suite.</p><h3>Conclusion</h3><p>SAP BTP is not a replacement for AWS, Azure, or GCP. It is a purpose-built enterprise platform that solves a specific and real problem: building cloud-native extensions and integrations for SAP landscapes without making the core system brittle.</p><p>For backend engineers working in enterprise environments with heavy SAP footprints, understanding BTP is becoming as important as knowing any major cloud platform. The “Clean Core” movement is pushing more and more custom logic out of S/4HANA and into BTP-hosted microservices.</p><p>The platform has a learning curve, but the fundamentals are familiar: OAuth2 for auth, REST APIs for integration, CloudEvents for event-driven architecture, Kubernetes (Kyma) for container workloads. Once you get past BTP’s terminology and account model, writing services on it feels similar to writing services on any other PaaS.</p><p>If your codebase needs to talk to SAP, BTP is almost always the right place to do it. If it does not, keep using the hyperscaler you know best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94a702b91111" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Connect: The Missing Glue in Your Data Pipeline]]></title>
            <link>https://medium.com/@mgaurang123/kafka-connect-the-missing-glue-in-your-data-pipeline-8bbd66dcd3fe?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bbd66dcd3fe</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 16:12:14 GMT</pubDate>
            <atom:updated>2026-04-25T16:12:14.891Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked with Apache Kafka for any reasonable amount of time, you have probably written code that reads from a database and publishes events to a Kafka topic. Or maybe you wrote a consumer that reads from Kafka and writes rows into Elasticsearch or S3. It works. But then your team needs another source. And another sink. And suddenly you are maintaining a small army of custom ingestion scripts, each with its own retry logic, offset management, schema handling, and deployment story.</p><p>Kafka Connect exists precisely to stop this cycle.</p><p>It is a framework built into the Kafka ecosystem that lets you move data in and out of Kafka without writing custom producer or consumer code. It handles the operational complexity so you can focus on configuration rather than plumbing. This post breaks down what it is, why it was built, and how to use it practically, with real code examples in Python and Go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umJV6Fa6c1kDPq4cgRtr9w.png" /></figure><h3>What Is Kafka Connect?</h3><p>Kafka Connect is a scalable, fault-tolerant framework for streaming data between Apache Kafka and external systems. It ships as part of the Apache Kafka distribution and runs as a separate process (or cluster of processes) alongside your Kafka brokers.</p><p>At its core, it is a runtime that executes <strong>Connectors</strong>. A connector is a plugin that knows how to talk to a specific external system, whether that is PostgreSQL, MongoDB, S3, Elasticsearch, HTTP APIs, or dozens of others.</p><p>Kafka Connect operates in two directions:</p><pre>External System ──► Kafka Connect (Source) ──► Kafka Topic<br>Kafka Topic    ──► Kafka Connect (Sink)   ──► External System</pre><p>A <strong>Source Connector</strong> pulls data from an external system and writes it into one or more Kafka topics.<br> A <strong>Sink Connector</strong> reads from one or more Kafka topics and pushes data into an external system.</p><p>Kafka Connect exposes a REST API for managing connectors, so you can deploy, pause, resume, and monitor connectors without touching your application code.</p><h3>Why Was Kafka Connect Invented?</h3><p>Before Kafka Connect, teams building Kafka-based pipelines had to write custom producers and consumers for every data source and destination. This sounds straightforward until you realize how much boilerplate is involved:</p><ul><li>Offset management (where did I last read from?)</li><li>Exactly-once or at-least-once delivery guarantees</li><li>Parallelism and partitioning</li><li>Schema evolution and serialization</li><li>Error handling, dead-letter queues</li><li>Restarts, rebalancing, and fault recovery</li><li>Monitoring and operational visibility</li></ul><p>Every team was solving the same problems independently. Confluent and the Kafka community recognized this pattern and introduced Kafka Connect in Kafka 0.9 (2015) to standardize and reuse this integration logic.</p><p>The goal was simple: make data integration a <strong>configuration problem</strong>, not a coding problem.</p><h3>What Problem Does It Solve?</h3><p>Let us be concrete. Imagine you are building a system where:</p><ul><li>A PostgreSQL database holds your transactional data</li><li>You want every change (insert, update, delete) to flow into Kafka in real time</li><li>Downstream, you want those events to land in Elasticsearch for search and S3 for archival</li></ul><p>Without Kafka Connect, you are writing:</p><ol><li>A change-data-capture (CDC) producer that polls or uses logical replication to read Postgres WAL</li><li>An Elasticsearch sink consumer with retry logic and bulk indexing</li><li>An S3 sink consumer with partitioning, file rolling, and upload logic</li></ol><p>Each of these needs its own deployment, monitoring, and maintenance.</p><p>With Kafka Connect, you configure three connectors via JSON and the framework handles the rest:</p><pre>PostgreSQL (WAL)<br>      |<br>      v<br>Debezium Source Connector<br>      |<br>      v<br>Kafka Topic: postgres.orders<br>      |<br>      |-----&gt; Elasticsearch Sink Connector<br>      |<br>      |-----&gt; S3 Sink Connector<br>      |<br>      |-----&gt; Another Sink Connector</pre><p>No custom consumer code. No offset tracking in your application. No retry logic to maintain.</p><h3>What Are Connectors?</h3><p>A <strong>connector</strong> in Kafka Connect is a JAR-based plugin that implements either the SourceConnector or SinkConnector interface from the Kafka Connect API.</p><p>Internally, each connector is made up of two components:</p><p><strong>Connector Class</strong>: Determines how many tasks to create and what configuration each task gets. It is the manager.</p><p><strong>Task Class</strong>: Does the actual work of reading from or writing to the external system. Multiple tasks can run in parallel across worker nodes.</p><p>This separation is what gives Kafka Connect its horizontal scalability. If you have a 12-partition Kafka topic and a sink connector configured with tasks.max=6, six tasks will run in parallel, each consuming two partitions.</p><h4>Connector Configuration</h4><p>Every connector is configured through a JSON payload sent to the Kafka Connect REST API. Here is a minimal example:</p><pre>{<br>  &quot;name&quot;: &quot;postgres-source&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>    &quot;database.hostname&quot;: &quot;localhost&quot;,<br>    &quot;database.port&quot;: &quot;5432&quot;,<br>    &quot;database.user&quot;: &quot;replicator&quot;,<br>    &quot;database.password&quot;: &quot;secret&quot;,<br>    &quot;database.dbname&quot;: &quot;orders_db&quot;,<br>    &quot;database.server.name&quot;: &quot;orderservice&quot;,<br>    &quot;table.include.list&quot;: &quot;public.orders&quot;,<br>    &quot;plugin.name&quot;: &quot;pgoutput&quot;<br>  }<br>}</pre><p>You POST this to http://localhost:8083/connectors and the connector starts running.</p><h3>What Connectors Are Available?</h3><p>The Kafka Connect ecosystem has hundreds of connectors. Here are the most commonly used ones grouped by category:</p><pre>Databases and CDC<br>+---------------------------+-----------+-------------------------------------+<br>| Connector                 | Direction | Notes                               |<br>+---------------------------+-----------+-------------------------------------+<br>| Debezium PostgreSQL       | Source    | CDC via WAL logical replication     |<br>| Debezium MySQL            | Source    | CDC via binlog                      |<br>| Debezium MongoDB          | Source    | CDC via oplog                       |<br>| JDBC Source Connector     | Source    | Poll-based, works with any JDBC DB  |<br>| JDBC Sink Connector       | Sink      | Write to any JDBC-compatible DB     |<br>+---------------------------+-----------+-------------------------------------+<br><br>Cloud Storage<br>+----------------------+-----------+--------------------------------+<br>| Connector            | Direction | Notes                          |<br>+----------------------+-----------+--------------------------------+<br>| S3 Sink (Confluent)  | Sink      | Write to AWS S3 with partition |<br>| GCS Sink             | Sink      | Google Cloud Storage           |<br>| Azure Blob Sink      | Sink      | Azure Blob Storage             |<br>+----------------------+-----------+--------------------------------+<br><br>Search and Analytics<br>+--------------------+-----------+--------------------------------+<br>| Connector          | Direction | Notes                          |<br>+--------------------+-----------+--------------------------------+<br>| Elasticsearch Sink | Sink      | Bulk indexing into ES          |<br>| OpenSearch Sink    | Sink      | Fork for OpenSearch compat     |<br>| Splunk Sink        | Sink      | Log forwarding to Splunk       |<br>+--------------------+-----------+--------------------------------+<br><br>Messaging and APIs<br>+---------------------+-----------+----------------------------------------+<br>| Connector           | Direction | Notes                                  |<br>+---------------------+-----------+----------------------------------------+<br>| HTTP Source         | Source    | Poll HTTP endpoints and push to Kafka  |<br>| HTTP Sink           | Sink      | POST Kafka records to HTTP endpoints   |<br>| RabbitMQ Source/Sink| Both      | Bridge between RabbitMQ and Kafka      |<br>+---------------------+-----------+----------------------------------------+<br><br>Data Warehouses<br>+----------------+-----------+--------------------------------+<br>| Connector      | Direction | Notes                          |<br>+----------------+-----------+--------------------------------+<br>| Snowflake Sink | Sink      | Stream records into Snowflake  |<br>| BigQuery Sink  | Sink      | Stream into Google BigQuery    |<br>| Redshift Sink  | Sink      | Write to Amazon Redshift       |<br>+----------------+-----------+--------------------------------+</pre><p>You can find the full catalog at <a href="https://www.confluent.io/hub/">Confluent Hub</a> and the <a href="https://kafka.apache.org/documentation/#connect">Kafka connector documentation</a>.</p><h3>How Kafka Connect Simplifies Implementation</h3><p>Let us look at a real scenario: you want to sync every new order from PostgreSQL into Elasticsearch.</p><h4>The Old Way (Custom Consumer)</h4><p>You would write something like this in Python:</p><pre>from confluent_kafka import Consumer, KafkaError<br>from elasticsearch import Elasticsearch, helpers<br>import json<br><br>consumer = Consumer({<br>    &#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;,<br>    &#39;group.id&#39;: &#39;orders-es-sync&#39;,<br>    &#39;auto.offset.reset&#39;: &#39;earliest&#39;,<br>    &#39;enable.auto.commit&#39;: False<br>})<br><br>es = Elasticsearch(&quot;http://localhost:9200&quot;)<br>consumer.subscribe([&#39;postgres.orders&#39;])<br><br>buffer = []<br><br>while True:<br>    msg = consumer.poll(timeout=1.0)<br>    if msg is None:<br>        continue<br>    if msg.error():<br>        raise KafkaError(msg.error())<br><br>    record = json.loads(msg.value())<br>    buffer.append({<br>        &quot;_index&quot;: &quot;orders&quot;,<br>        &quot;_id&quot;: record[&quot;id&quot;],<br>        &quot;_source&quot;: record<br>    })<br><br>    if len(buffer) &gt;= 100:<br>        helpers.bulk(es, buffer)<br>        consumer.commit()<br>        buffer.clear()</pre><p>This is not terrible, but now you own the offset commit logic, the bulk flush logic, error handling, and the deployment. And this is just one sink.</p><h4>The Kafka Connect Way</h4><p>You run a Kafka Connect worker (standalone or distributed), install the Elasticsearch connector plugin, and POST this configuration:</p><pre>{<br>  &quot;name&quot;: &quot;elasticsearch-orders-sink&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.confluent.connect.elasticsearch.ElasticsearchSinkConnector&quot;,<br>    &quot;tasks.max&quot;: &quot;3&quot;,<br>    &quot;topics&quot;: &quot;postgres.orders&quot;,<br>    &quot;connection.url&quot;: &quot;http://localhost:9200&quot;,<br>    &quot;type.name&quot;: &quot;_doc&quot;,<br>    &quot;key.ignore&quot;: &quot;false&quot;,<br>    &quot;schema.ignore&quot;: &quot;true&quot;,<br>    &quot;behavior.on.malformed.documents&quot;: &quot;warn&quot;<br>  }<br>}</pre><p>That is it. The framework handles batching, retries, offset commits, task parallelism, and restarts. You deleted 60 lines of application code and replaced it with 12 lines of JSON.</p><h3>Code Examples</h3><h4>Python: Managing Kafka Connect via REST API</h4><p>Kafka Connect exposes a REST API on port 8083 by default. You can manage your entire connector lifecycle programmatically from Python.</p><pre>import requests<br>import json<br><br>CONNECT_URL = &quot;http://localhost:8083&quot;<br><br>def list_connectors():<br>    response = requests.get(f&quot;{CONNECT_URL}/connectors&quot;)<br>    response.raise_for_status()<br>    return response.json()<br><br>def create_connector(config: dict):<br>    response = requests.post(<br>        f&quot;{CONNECT_URL}/connectors&quot;,<br>        headers={&quot;Content-Type&quot;: &quot;application/json&quot;},<br>        data=json.dumps(config)<br>    )<br>    response.raise_for_status()<br>    return response.json()<br><br>def get_connector_status(name: str):<br>    response = requests.get(f&quot;{CONNECT_URL}/connectors/{name}/status&quot;)<br>    response.raise_for_status()<br>    return response.json()<br><br>def pause_connector(name: str):<br>    response = requests.put(f&quot;{CONNECT_URL}/connectors/{name}/pause&quot;)<br>    response.raise_for_status()<br>    print(f&quot;Connector &#39;{name}&#39; paused.&quot;)<br><br>def delete_connector(name: str):<br>    response = requests.delete(f&quot;{CONNECT_URL}/connectors/{name}&quot;)<br>    response.raise_for_status()<br>    print(f&quot;Connector &#39;{name}&#39; deleted.&quot;)<br><br>def restart_failed_tasks(name: str):<br>    status = get_connector_status(name)<br>    tasks = status.get(&quot;tasks&quot;, [])<br>    for task in tasks:<br>        if task[&quot;state&quot;] == &quot;FAILED&quot;:<br>            task_id = task[&quot;id&quot;]<br>            response = requests.post(<br>                f&quot;{CONNECT_URL}/connectors/{name}/tasks/{task_id}/restart&quot;<br>            )<br>            response.raise_for_status()<br>            print(f&quot;Restarted failed task {task_id} for connector &#39;{name}&#39;&quot;)<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    # Deploy a Debezium PostgreSQL source connector<br>    pg_connector_config = {<br>        &quot;name&quot;: &quot;debezium-postgres-orders&quot;,<br>        &quot;config&quot;: {<br>            &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>            &quot;tasks.max&quot;: &quot;1&quot;,<br>            &quot;database.hostname&quot;: &quot;postgres&quot;,<br>            &quot;database.port&quot;: &quot;5432&quot;,<br>            &quot;database.user&quot;: &quot;replicator&quot;,<br>            &quot;database.password&quot;: &quot;replicator_pass&quot;,<br>            &quot;database.dbname&quot;: &quot;orders_db&quot;,<br>            &quot;database.server.name&quot;: &quot;orderservice&quot;,<br>            &quot;table.include.list&quot;: &quot;public.orders,public.payments&quot;,<br>            &quot;plugin.name&quot;: &quot;pgoutput&quot;,<br>            &quot;slot.name&quot;: &quot;debezium_slot&quot;,<br>            &quot;publication.name&quot;: &quot;debezium_pub&quot;,<br>            &quot;topic.prefix&quot;: &quot;cdc&quot;<br>        }<br>    }<br><br>    connector = create_connector(pg_connector_config)<br>    print(&quot;Created connector:&quot;, connector[&quot;name&quot;])<br><br>    # Check status<br>    status = get_connector_status(&quot;debezium-postgres-orders&quot;)<br>    print(&quot;Connector state:&quot;, status[&quot;connector&quot;][&quot;state&quot;])<br>    print(&quot;Tasks:&quot;, status[&quot;tasks&quot;])<br><br>    # List all connectors<br>    all_connectors = list_connectors()<br>    print(&quot;All connectors:&quot;, all_connectors)<br><br>    # Auto-heal failed tasks<br>    restart_failed_tasks(&quot;debezium-postgres-orders&quot;)</pre><h4>Python: Custom Source Connector Using the Kafka Connect Python Worker (Standalone Mode Config Generator)</h4><p>While Kafka Connect connectors are JVM plugins, you can generate and manage connector configs dynamically from Python. Here is a utility to generate connector configurations for common patterns:</p><pre>from dataclasses import dataclass, asdict<br>from typing import Optional<br>import json<br><br>@dataclass<br>class S3SinkConnectorConfig:<br>    name: str<br>    topics: str<br>    s3_bucket_name: str<br>    s3_region: str<br>    s3_part_size: int = 67108864  # 64MB<br>    tasks_max: int = 3<br>    flush_size: int = 1000<br>    rotate_interval_ms: int = 60000<br>    storage_class: str = &quot;io.confluent.connect.s3.storage.S3Storage&quot;<br>    format_class: str = &quot;io.confluent.connect.s3.format.json.JsonFormat&quot;<br>    locale: str = &quot;en_US&quot;<br>    timezone: str = &quot;Asia/Kolkata&quot;<br>    timestamp_extractor: str = &quot;Record&quot;<br>    partitioner_class: str = &quot;io.confluent.connect.storage.partitioner.TimeBasedPartitioner&quot;<br>    path_format: str = &quot;&#39;year&#39;=YYYY/&#39;month&#39;=MM/&#39;day&#39;=dd/&#39;hour&#39;=HH&quot;<br>    partition_duration_ms: int = 3600000<br><br>    def to_connect_payload(self) -&gt; dict:<br>        return {<br>            &quot;name&quot;: self.name,<br>            &quot;config&quot;: {<br>                &quot;connector.class&quot;: &quot;io.confluent.connect.s3.S3SinkConnector&quot;,<br>                &quot;tasks.max&quot;: str(self.tasks_max),<br>                &quot;topics&quot;: self.topics,<br>                &quot;s3.region&quot;: self.s3_region,<br>                &quot;s3.bucket.name&quot;: self.s3_bucket_name,<br>                &quot;s3.part.size&quot;: str(self.s3_part_size),<br>                &quot;flush.size&quot;: str(self.flush_size),<br>                &quot;rotate.interval.ms&quot;: str(self.rotate_interval_ms),<br>                &quot;storage.class&quot;: self.storage_class,<br>                &quot;format.class&quot;: self.format_class,<br>                &quot;locale&quot;: self.locale,<br>                &quot;timezone&quot;: self.timezone,<br>                &quot;timestamp.extractor&quot;: self.timestamp_extractor,<br>                &quot;partitioner.class&quot;: self.partitioner_class,<br>                &quot;path.format&quot;: self.path_format,<br>                &quot;partition.duration.ms&quot;: str(self.partition_duration_ms),<br>                &quot;schema.compatibility&quot;: &quot;NONE&quot;<br>            }<br>        }<br><br><br>@dataclass<br>class ElasticsearchSinkConnectorConfig:<br>    name: str<br>    topics: str<br>    connection_url: str<br>    tasks_max: int = 3<br>    key_ignore: bool = False<br>    schema_ignore: bool = True<br>    behavior_on_malformed: str = &quot;warn&quot;<br>    batch_size: int = 2000<br>    linger_ms: int = 1000<br><br>    def to_connect_payload(self) -&gt; dict:<br>        return {<br>            &quot;name&quot;: self.name,<br>            &quot;config&quot;: {<br>                &quot;connector.class&quot;: &quot;io.confluent.connect.elasticsearch.ElasticsearchSinkConnector&quot;,<br>                &quot;tasks.max&quot;: str(self.tasks_max),<br>                &quot;topics&quot;: self.topics,<br>                &quot;connection.url&quot;: self.connection_url,<br>                &quot;key.ignore&quot;: str(self.key_ignore).lower(),<br>                &quot;schema.ignore&quot;: str(self.schema_ignore).lower(),<br>                &quot;behavior.on.malformed.documents&quot;: self.behavior_on_malformed,<br>                &quot;batch.size&quot;: str(self.batch_size),<br>                &quot;linger.ms&quot;: str(self.linger_ms),<br>                &quot;type.name&quot;: &quot;_doc&quot;<br>            }<br>        }<br><br><br># Usage<br>if __name__ == &quot;__main__&quot;:<br>    s3_config = S3SinkConnectorConfig(<br>        name=&quot;orders-s3-sink&quot;,<br>        topics=&quot;cdc.orderservice.public.orders&quot;,<br>        s3_bucket_name=&quot;data-lake-orders&quot;,<br>        s3_region=&quot;ap-south-1&quot;<br>    )<br><br>    es_config = ElasticsearchSinkConnectorConfig(<br>        name=&quot;orders-es-sink&quot;,<br>        topics=&quot;cdc.orderservice.public.orders&quot;,<br>        connection_url=&quot;http://elasticsearch:9200&quot;<br>    )<br><br>    configs = [s3_config.to_connect_payload(), es_config.to_connect_payload()]<br><br>    for cfg in configs:<br>        print(json.dumps(cfg, indent=2))<br>        # You could POST these directly to the Connect REST API here</pre><p>Golang: Kafka Connect REST Client</p><pre>package main<br><br>import (<br> &quot;bytes&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;net/http&quot;<br> &quot;time&quot;<br>)<br><br>const connectBaseURL = &quot;http://localhost:8083&quot;<br><br>type ConnectorConfig struct {<br> Name   string            `json:&quot;name&quot;`<br> Config map[string]string `json:&quot;config&quot;`<br>}<br><br>type ConnectorStatus struct {<br> Name      string `json:&quot;name&quot;`<br> Connector struct {<br>  State    string `json:&quot;state&quot;`<br>  WorkerID string `json:&quot;worker_id&quot;`<br> } `json:&quot;connector&quot;`<br> Tasks []struct {<br>  ID       int    `json:&quot;id&quot;`<br>  State    string `json:&quot;state&quot;`<br>  WorkerID string `json:&quot;worker_id&quot;`<br>  Trace    string `json:&quot;trace,omitempty&quot;`<br> } `json:&quot;tasks&quot;`<br>}<br><br>type ConnectClient struct {<br> baseURL    string<br> httpClient *http.Client<br>}<br><br>func NewConnectClient(baseURL string) *ConnectClient {<br> return &amp;ConnectClient{<br>  baseURL: baseURL,<br>  httpClient: &amp;http.Client{<br>   Timeout: 15 * time.Second,<br>  },<br> }<br>}<br><br>func (c *ConnectClient) doRequest(method, path string, body interface{}) ([]byte, error) {<br> var reqBody io.Reader<br><br> if body != nil {<br>  data, err := json.Marshal(body)<br>  if err != nil {<br>   return nil, fmt.Errorf(&quot;marshaling request body: %w&quot;, err)<br>  }<br>  reqBody = bytes.NewBuffer(data)<br> }<br><br> req, err := http.NewRequest(method, c.baseURL+path, reqBody)<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;creating request: %w&quot;, err)<br> }<br><br> if body != nil {<br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> }<br><br> resp, err := c.httpClient.Do(req)<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;executing request: %w&quot;, err)<br> }<br> defer resp.Body.Close()<br><br> respBody, err := io.ReadAll(resp.Body)<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;reading response body: %w&quot;, err)<br> }<br><br> if resp.StatusCode &gt;= 400 {<br>  return nil, fmt.Errorf(&quot;connect API error %d: %s&quot;, resp.StatusCode, string(respBody))<br> }<br><br> return respBody, nil<br>}<br><br>func (c *ConnectClient) ListConnectors() ([]string, error) {<br> body, err := c.doRequest(http.MethodGet, &quot;/connectors&quot;, nil)<br> if err != nil {<br>  return nil, err<br> }<br><br> var connectors []string<br> if err := json.Unmarshal(body, &amp;connectors); err != nil {<br>  return nil, fmt.Errorf(&quot;unmarshaling connectors list: %w&quot;, err)<br> }<br><br> return connectors, nil<br>}<br><br>func (c *ConnectClient) CreateConnector(config ConnectorConfig) (*ConnectorConfig, error) {<br> body, err := c.doRequest(http.MethodPost, &quot;/connectors&quot;, config)<br> if err != nil {<br>  return nil, err<br> }<br><br> var created ConnectorConfig<br> if err := json.Unmarshal(body, &amp;created); err != nil {<br>  return nil, fmt.Errorf(&quot;unmarshaling created connector: %w&quot;, err)<br> }<br><br> return &amp;created, nil<br>}<br><br>func (c *ConnectClient) GetStatus(name string) (*ConnectorStatus, error) {<br> body, err := c.doRequest(http.MethodGet, &quot;/connectors/&quot;+name+&quot;/status&quot;, nil)<br> if err != nil {<br>  return nil, err<br> }<br><br> var status ConnectorStatus<br> if err := json.Unmarshal(body, &amp;status); err != nil {<br>  return nil, fmt.Errorf(&quot;unmarshaling connector status: %w&quot;, err)<br> }<br><br> return &amp;status, nil<br>}<br><br>func (c *ConnectClient) RestartFailedTasks(name string) error {<br> status, err := c.GetStatus(name)<br> if err != nil {<br>  return err<br> }<br><br> for _, task := range status.Tasks {<br>  if task.State == &quot;FAILED&quot; {<br>   path := fmt.Sprintf(&quot;/connectors/%s/tasks/%d/restart&quot;, name, task.ID)<br>   _, err := c.doRequest(http.MethodPost, path, nil)<br>   if err != nil {<br>    return fmt.Errorf(&quot;restarting task %d: %w&quot;, task.ID, err)<br>   }<br>   fmt.Printf(&quot;Restarted failed task %d for connector %s\n&quot;, task.ID, name)<br>  }<br> }<br><br> return nil<br>}<br><br>func (c *ConnectClient) DeleteConnector(name string) error {<br> _, err := c.doRequest(http.MethodDelete, &quot;/connectors/&quot;+name, nil)<br> return err<br>}<br><br>func (c *ConnectClient) PauseConnector(name string) error {<br> _, err := c.doRequest(http.MethodPut, &quot;/connectors/&quot;+name+&quot;/pause&quot;, nil)<br> return err<br>}<br><br>func (c *ConnectClient) ResumeConnector(name string) error {<br> _, err := c.doRequest(http.MethodPut, &quot;/connectors/&quot;+name+&quot;/resume&quot;, nil)<br> return err<br>}<br><br>func buildJDBCSinkConfig() ConnectorConfig {<br> return ConnectorConfig{<br>  Name: &quot;jdbc-mysql-sink&quot;,<br>  Config: map[string]string{<br>   &quot;connector.class&quot;:    &quot;io.confluent.connect.jdbc.JdbcSinkConnector&quot;,<br>   &quot;tasks.max&quot;:          &quot;4&quot;,<br>   &quot;topics&quot;:             &quot;cdc.orderservice.public.orders&quot;,<br>   &quot;connection.url&quot;:     &quot;jdbc:mysql://mysql:3306/analytics_db&quot;,<br>   &quot;connection.user&quot;:    &quot;analytics_user&quot;,<br>   &quot;connection.password&quot;: &quot;analytics_pass&quot;,<br>   &quot;auto.create&quot;:        &quot;true&quot;,<br>   &quot;auto.evolve&quot;:        &quot;true&quot;,<br>   &quot;insert.mode&quot;:        &quot;upsert&quot;,<br>   &quot;pk.mode&quot;:            &quot;record_key&quot;,<br>   &quot;pk.fields&quot;:          &quot;id&quot;,<br>   &quot;batch.size&quot;:         &quot;3000&quot;,<br>  },<br> }<br>}<br><br>func main() {<br> client := NewConnectClient(connectBaseURL)<br><br> // List existing connectors<br> connectors, err := client.ListConnectors()<br> if err != nil {<br>  fmt.Printf(&quot;Error listing connectors: %v\n&quot;, err)<br>  return<br> }<br> fmt.Println(&quot;Existing connectors:&quot;, connectors)<br><br> // Create a JDBC sink connector<br> config := buildJDBCSinkConfig()<br> created, err := client.CreateConnector(config)<br> if err != nil {<br>  fmt.Printf(&quot;Error creating connector: %v\n&quot;, err)<br>  return<br> }<br> fmt.Printf(&quot;Created connector: %s\n&quot;, created.Name)<br><br> // Poll status until running<br> for i := 0; i &lt; 10; i++ {<br>  time.Sleep(2 * time.Second)<br>  status, err := client.GetStatus(&quot;jdbc-mysql-sink&quot;)<br>  if err != nil {<br>   fmt.Printf(&quot;Error getting status: %v\n&quot;, err)<br>   break<br>  }<br>  fmt.Printf(&quot;State: %s | Tasks: %d\n&quot;, status.Connector.State, len(status.Tasks))<br>  if status.Connector.State == &quot;RUNNING&quot; {<br>   break<br>  }<br> }<br><br> // Auto-heal failed tasks<br> if err := client.RestartFailedTasks(&quot;jdbc-mysql-sink&quot;); err != nil {<br>  fmt.Printf(&quot;Error restarting tasks: %v\n&quot;, err)<br> }<br>}</pre><h4>Golang: Health Monitor for Kafka Connect Cluster</h4><p>A real-world pattern you will need in production is a health monitor that periodically checks all connectors and restarts any failed tasks automatically.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br>)<br><br>type HealthMonitor struct {<br> client   *ConnectClient<br> interval time.Duration<br> stopCh   chan struct{}<br>}<br><br>func NewHealthMonitor(client *ConnectClient, interval time.Duration) *HealthMonitor {<br> return &amp;HealthMonitor{<br>  client:   client,<br>  interval: interval,<br>  stopCh:   make(chan struct{}),<br> }<br>}<br><br>func (m *HealthMonitor) Start() {<br> ticker := time.NewTicker(m.interval)<br> defer ticker.Stop()<br><br> log.Println(&quot;Health monitor started&quot;)<br><br> for {<br>  select {<br>  case &lt;-ticker.C:<br>   m.checkAll()<br>  case &lt;-m.stopCh:<br>   log.Println(&quot;Health monitor stopped&quot;)<br>   return<br>  }<br> }<br>}<br><br>func (m *HealthMonitor) Stop() {<br> close(m.stopCh)<br>}<br><br>func (m *HealthMonitor) checkAll() {<br> connectors, err := m.client.ListConnectors()<br> if err != nil {<br>  log.Printf(&quot;Failed to list connectors: %v&quot;, err)<br>  return<br> }<br><br> for _, name := range connectors {<br>  status, err := m.client.GetStatus(name)<br>  if err != nil {<br>   log.Printf(&quot;Failed to get status for %s: %v&quot;, name, err)<br>   continue<br>  }<br><br>  connectorState := status.Connector.State<br>  failedTasks := 0<br><br>  for _, task := range status.Tasks {<br>   if task.State == &quot;FAILED&quot; {<br>    failedTasks++<br>    log.Printf(&quot;[ALERT] Connector %s: Task %d FAILED. Trace: %s&quot;,<br>     name, task.ID, task.Trace)<br>   }<br>  }<br><br>  if connectorState != &quot;RUNNING&quot; {<br>   log.Printf(&quot;[ALERT] Connector %s is in state: %s&quot;, name, connectorState)<br>  }<br><br>  if failedTasks &gt; 0 {<br>   log.Printf(&quot;Attempting to restart %d failed tasks for %s&quot;, failedTasks, name)<br>   if err := m.client.RestartFailedTasks(name); err != nil {<br>    log.Printf(&quot;Failed to restart tasks for %s: %v&quot;, name, err)<br>   }<br>  } else {<br>   fmt.Printf(&quot;[OK] %s: %s (%d tasks running)\n&quot;,<br>    name, connectorState, len(status.Tasks))<br>  }<br> }<br>}<br><br>// Entry point for the monitor<br>func runMonitor() {<br> client := NewConnectClient(connectBaseURL)<br> monitor := NewHealthMonitor(client, 30*time.Second)<br><br> // Run in background<br> go monitor.Start()<br><br> // Simulate running for 5 minutes<br> time.Sleep(5 * time.Minute)<br> monitor.Stop()<br>}</pre><h3>Deploying Kafka Connect: Standalone vs Distributed Mode</h3><p>Kafka Connect can run in two modes:</p><p><strong>Standalone Mode</strong> is for local development and simple single-machine setups. You run a single worker process with a properties file.</p><pre># connect-standalone.properties<br>bootstrap.servers=localhost:9092<br>key.converter=org.apache.kafka.connect.json.JsonConverter<br>value.converter=org.apache.kafka.connect.json.JsonConverter<br>key.converter.schemas.enable=false<br>value.converter.schemas.enable=false<br>offset.storage.file.filename=/tmp/connect.offsets</pre><p><strong>Distributed Mode</strong> is what you run in production. Multiple workers form a cluster. Connectors and their tasks are distributed across workers automatically. Configuration is stored in Kafka topics, not local files.</p><pre># connect-distributed.properties<br>bootstrap.servers=kafka-1:9092,kafka-2:9092,kafka-3:9092<br>group.id=connect-cluster<br>key.converter=io.confluent.connect.avro.AvroConverter<br>value.converter=io.confluent.connect.avro.AvroConverter<br>key.converter.schema.registry.url=http://schema-registry:8081<br>value.converter.schema.registry.url=http://schema-registry:8081<br>offset.storage.topic=connect-offsets<br>config.storage.topic=connect-configs<br>status.storage.topic=connect-status<br>offset.storage.replication.factor=3<br>config.storage.replication.factor=3<br>status.storage.replication.factor=3<br>rest.port=8083</pre><p>In distributed mode, if one worker goes down, its tasks are redistributed to other workers automatically.</p><h3>Pros and Cons</h3><h4>Pros</h4><p><strong>Dramatically reduces boilerplate code.</strong> You replace hundreds of lines of custom producer/consumer code with JSON configuration. This is a significant reduction in surface area for bugs.</p><p><strong>Battle-tested reliability.</strong> The framework handles offset management, consumer group rebalancing, fault tolerance, and restarts. These are hard problems to solve correctly in custom code.</p><p><strong>Horizontal scalability out of the box.</strong> Increasing tasks.max scales your connector across multiple workers without any code changes.</p><p><strong>Rich ecosystem.</strong> There are hundreds of production-ready connectors on Confluent Hub and GitHub covering almost every data system you are likely to encounter.</p><p><strong>Schema Registry integration.</strong> Kafka Connect pairs naturally with Confluent Schema Registry and Avro/Protobuf schemas, giving you automatic schema evolution management across your pipeline.</p><p><strong>Operational visibility.</strong> The REST API gives you a single interface for monitoring all your integrations. You can build dashboards and alerting directly on top of it.</p><p><strong>Transforms (SMTs).</strong> Single Message Transforms let you apply lightweight transformations to records inline without writing a full Kafka Streams application. Common use cases include field renaming, masking sensitive values, and routing records to different topics based on content.</p><h4>Cons</h4><p><strong>JVM-only plugin model.</strong> Connectors must be written in Java or Kotlin. If you need a custom connector, you are committing to JVM development and build tooling. Your Python or Go teams cannot easily contribute custom connector code.</p><p><strong>Operational overhead.</strong> Running a Kafka Connect cluster is another distributed system to maintain, monitor, and upgrade. For teams just starting with Kafka, this can be one too many moving parts early on.</p><p><strong>Debugging can be painful.</strong> When a connector fails, the error messages are sometimes buried in Java stack traces. Getting to the root cause of a failed task requires knowing where to look in the logs and understanding the connector’s internals.</p><p><strong>Limited transformation logic.</strong> SMTs are intentionally simple. If you need complex stream processing, enrichment from external databases, or join logic, you are looking at Kafka Streams or Apache Flink, not Kafka Connect. Kafka Connect is not a processing framework.</p><p><strong>Configuration management at scale.</strong> Managing dozens of connector configurations without a proper GitOps workflow and tooling can become messy. Connector configs are stored in Kafka internal topics, not in files, which makes version control non-trivial without additional tooling.</p><p><strong>Backpressure handling varies by connector.</strong> Not all connectors handle slow sink systems equally well. Poorly implemented connectors can cause lag to build up on topics or overload a sink system during high-throughput periods.</p><h3>When to Use Kafka Connect vs Custom Code</h3><p>Kafka Connect is the right choice when:</p><ul><li>You are integrating with a system that has an existing, well-maintained connector</li><li>Your transformation needs are minimal (field masking, routing, renaming)</li><li>You want to move fast and not maintain custom ingestion code</li></ul><p>Write custom Kafka producers and consumers when:</p><ul><li>No connector exists for your target system</li><li>You need complex business logic as part of the ingestion</li><li>You need fine-grained control over exactly-once semantics or ordering</li></ul><p>Use Kafka Streams or Flink when:</p><ul><li>You need stateful processing, aggregations, or joins</li><li>You need to enrich data from external lookups during processing</li><li>Connect’s SMTs are not powerful enough for your transformation needs</li></ul><h3>Conclusion</h3><p>Kafka Connect solves a real and recurring problem in data engineering: the constant rebuilding of custom ingestion pipelines for every new data source or destination. By treating data integration as a configuration problem rather than a coding problem, it lets your team move faster and spend more time on business logic rather than plumbing.</p><p>The framework is mature, battle-tested, and has a thriving ecosystem of connectors. For teams running Kafka in production, Kafka Connect should be the default approach for any standard data movement use case.</p><p>That said, it is not magic. You still need to understand your connectors, configure them correctly, monitor their health, and know when a custom solution makes more sense. The REST API gives you the building blocks to automate and operationalize everything, and as the code examples above show, managing a Connect cluster programmatically from Python or Go is straightforward.</p><p>If you have been manually writing Kafka producers and consumers to move data between systems, Kafka Connect is worth evaluating seriously. In most cases, you will come out the other side with less code to maintain and more reliable pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bbd66dcd3fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraformer: Taming Infrastructure Technical Debt Before It Tames You]]></title>
            <link>https://medium.com/@mgaurang123/terraformer-taming-infrastructure-technical-debt-before-it-tames-you-5ebb72eb17c0?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ebb72eb17c0</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 17:38:16 GMT</pubDate>
            <atom:updated>2026-04-11T17:38:16.181Z</atom:updated>
            <content:encoded><![CDATA[<p>You just joined a new team. The first task? Figure out what’s running in production.</p><p>You open the AWS console and see hundreds of EC2 instances, security groups, load balancers, RDS clusters, and S3 buckets. Some have names like prod-api-server-v2-final-FINAL. Others have no tags at all. No one knows who created them, when, or why. The person who set them up left the company two years ago. Terraform? That was supposed to be adopted &quot;at some point.&quot;</p><p>This is infrastructure technical debt in its rawest form, and almost every engineering team hits it eventually.</p><p>Terraformer is a tool that helps you climb out of this hole. It reverse-engineers your existing cloud infrastructure and generates Terraform code from it, giving you a starting point to bring your infrastructure under version control and make sense of what you actually own.</p><p>This post covers what Terraformer is, why it matters, how to use it with practical Python examples, its trade-offs compared to alternatives, and when you should (and should not) reach for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4IzumdgfTwnjKi5mdVRQA.png" /></figure><h3>The Infrastructure Technical Debt Problem</h3><p>Let’s be specific about the pain points, because they are real and they compound over time.</p><h4>Nobody Knows What Owns What</h4><p>Cloud infrastructure created through the console, manual CLI commands, or one-off scripts leaves no paper trail. Three years in, you have a VPC with 12 subnets and no one can tell you which application uses which subnet, or whether that subnet in us-east-1b is even needed anymore.</p><p>This is not a discipline problem. It is a tooling problem. When the path of least resistance is “click through the console and ship,” people do that. Teams move fast and defer the cleanup that never comes.</p><h4>No Audit Trail</h4><p>Terraform and other IaC tools give you git history. Manual infrastructure gives you nothing. When a security group gets a rule opened wide and an incident happens six months later, your post-mortem is a dead end. You cannot answer “who changed this, when, and why” without digging through CloudTrail logs and stitching together a timeline manually.</p><h4>Fear of Change</h4><p>Once infrastructure is undocumented and unmanaged, people become afraid to touch it. “It works, don’t break it.” That fear accumulates interest. Security patches get skipped. Cost optimizations never happen. Old resources that cost money every month stay because nobody is confident enough to delete them.</p><h4>The Drift Problem</h4><p>Even teams that start with Terraform hit drift. An on-call engineer manually fixes a broken security group at 2 AM. A database parameter gets tweaked in the console during a performance incident. These changes are never reflected back in the Terraform code. Over time, your code and your real infrastructure diverge. The next terraform apply is a surprise box.</p><pre>+--------------------+        +--------------------+<br>|  Terraform State   |        |  Actual Cloud      |<br>|  (what you think   | &lt;----- |  Infrastructure    |<br>|   you have)        |  drift |  (what you really  |<br>|                    |        |   have)            |<br>+--------------------+        +--------------------+<br>         ^<br>         |<br>    Terraformer bridges this gap</pre><h3>What Is Terraformer?</h3><p>Terraformer is an open-source CLI tool built by Waze SRE (now maintained by the community). Its core job is simple: connect to your cloud provider, scan the resources you have, and generate Terraform HCL files and state files from them.</p><p>It does not just create configuration. It also imports the Terraform state, which means after running Terraformer you can immediately run terraform plan and, if all goes well, see no diff between what you have and what Terraform now tracks.</p><p>It supports a wide range of providers including AWS, GCP, Azure, Kubernetes, GitHub, Datadog, and more.</p><p>The typical workflow looks like this:</p><pre>+------------------+     +------------------+     +-------------------+<br>|  Cloud Provider  | --&gt; |  Terraformer     | --&gt; |  Generated        |<br>|  (AWS, GCP, etc) |     |  (reads APIs)    |     |  .tf files        |<br>|                  |     |                  |     |  + terraform.tfstate|<br>+------------------+     +------------------+     +-------------------+<br>                                                          |<br>                                                          v<br>                                              +-------------------+<br>                                              |  Git Repository   |<br>                                              |  (version control,|<br>                                              |   code review,    |<br>                                              |   audit trail)    |<br>                                              +-------------------+</pre><h3>How Terraformer Solves the Debt Problem</h3><h4>Step 1: You Get Visibility</h4><p>Running Terraformer against your AWS account gives you, possibly for the first time, a full inventory of everything you have expressed as code. You can search it, grep it, diff it, and store it in git. That alone is valuable even before you manage anything with it.</p><h4>Step 2: You Get a Starting Point for IaC Adoption</h4><p>Teams that want to adopt Terraform but have years of existing manual infrastructure face a bootstrapping problem. Writing Terraform from scratch for hundreds of resources is impractical. Terraformer gives you a generated baseline. It is not perfect code, but it is a working foundation.</p><h4>Step 3: You Can Detect Drift</h4><p>Once your infrastructure is in Terraform state, terraform plan shows you drift. Any manual change made outside of Terraform shows up as a diff. You can then decide to accept it (import it back), revert it, or write it properly.</p><h4>Step 4: Ownership Becomes Trackable</h4><p>Once resources are in Terraform files committed to git, git blame becomes your audit log. Who added this security group? When was this RDS instance created? Why does this IAM role exist? These questions get real answers.</p><h3>Getting Started with Terraformer</h3><p>Install Terraformer:</p><pre># Set the version you want<br>$version = &quot;0.8.24&quot;<br><br># Download the binary<br>Invoke-WebRequest -Uri &quot;https://github.com/GoogleCloudPlatform/terraformer/releases/download/$version/terraformer-all-windows-amd64.exe&quot; -OutFile &quot;terraformer.exe&quot;<br><br># Move it to a folder in your PATH (e.g., C:\terraform)<br>Move-Item -Path &quot;.\terraformer.exe&quot; -Destination &quot;C:\terraform\terraformer.exe&quot;</pre><p>Install Terraformer (macOS example):</p><pre>brew install terraformer</pre><p>Or download a binary directly from the GitHub releases page. You also need the Terraform CLI and provider plugins installed.</p><p>Basic usage for AWS:</p><pre># Import all S3 buckets in us-east-1<br>terraformer import aws --resources=s3 --regions=us-east-1<br><br># Import EC2 instances and security groups<br>terraformer import aws --resources=ec2_instance,sg --regions=us-east-1<br><br># Import everything (use carefully on large accounts)<br>terraformer import aws --resources=&quot;*&quot; --regions=us-east-1</pre><p>Terraformer generates a directory structure like this:</p><pre>generated/<br>  aws/<br>    s3/<br>      main.tf<br>      outputs.tf<br>      provider.tf<br>      terraform.tfstate<br>    ec2_instance/<br>      main.tf<br>      outputs.tf<br>      provider.tf<br>      terraform.tfstate</pre><h3>Practical Code Examples</h3><h4>Python: Automating Terraformer Runs and Organizing Output</h4><p>This script wraps Terraformer to automate imports across multiple AWS accounts and regions, then organizes the output into a structured repository layout.</p><pre>import subprocess<br>import os<br>import shutil<br>import json<br>import logging<br>from pathlib import Path<br>from dataclasses import dataclass<br>from typing import List<br><br>logging.basicConfig(level=logging.INFO, format=&quot;%(asctime)s %(levelname)s %(message)s&quot;)<br>logger = logging.getLogger(__name__)<br><br>@dataclass<br>class TerraformerJob:<br>    account_id: str<br>    region: str<br>    resources: List[str]<br>    output_dir: str<br><br>def run_terraformer(job: TerraformerJob) -&gt; bool:<br>    &quot;&quot;&quot;Run Terraformer for a given job config and return success status.&quot;&quot;&quot;<br>    resources_arg = &quot;,&quot;.join(job.resources)<br>    output_path = Path(job.output_dir) / job.account_id / job.region<br><br>    output_path.mkdir(parents=True, exist_ok=True)<br><br>    cmd = [<br>        &quot;terraformer&quot;,<br>        &quot;import&quot;,<br>        &quot;aws&quot;,<br>        f&quot;--resources={resources_arg}&quot;,<br>        f&quot;--regions={job.region}&quot;,<br>        &quot;--output=hcl&quot;,<br>        f&quot;--path-output={output_path}&quot;,<br>    ]<br><br>    env = os.environ.copy()<br>    # Assumes you&#39;re using AWS_PROFILE or have credentials in env already<br>    # For cross-account: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY per account<br><br>    logger.info(f&quot;Running terraformer for account={job.account_id} region={job.region}&quot;)<br><br>    result = subprocess.run(<br>        cmd,<br>        capture_output=True,<br>        text=True,<br>        env=env,<br>    )<br><br>    if result.returncode != 0:<br>        logger.error(f&quot;Terraformer failed for {job.account_id}/{job.region}&quot;)<br>        logger.error(result.stderr)<br>        return False<br><br>    logger.info(f&quot;Success: {job.account_id}/{job.region}&quot;)<br>    return True<br><br><br>def collect_resource_summary(base_dir: str) -&gt; dict:<br>    &quot;&quot;&quot;Walk generated output and build a summary of what was found.&quot;&quot;&quot;<br>    summary = {}<br>    base_path = Path(base_dir)<br><br>    for tfstate_file in base_path.rglob(&quot;terraform.tfstate&quot;):<br>        with open(tfstate_file) as f:<br>            state = json.load(f)<br><br>        resources = state.get(&quot;resources&quot;, [])<br>        relative_path = str(tfstate_file.relative_to(base_path))<br><br>        summary[relative_path] = {<br>            &quot;resource_count&quot;: len(resources),<br>            &quot;types&quot;: list(set(r[&quot;type&quot;] for r in resources)),<br>        }<br><br>    return summary<br><br><br>def generate_inventory_report(summary: dict, output_file: str):<br>    &quot;&quot;&quot;Write a markdown inventory report from the collected summary.&quot;&quot;&quot;<br>    lines = [&quot;# Infrastructure Inventory Report\n&quot;]<br>    lines.append(&quot;| Path | Resource Count | Types |\n&quot;)<br>    lines.append(&quot;|------|---------------|-------|\n&quot;)<br><br>    for path, info in sorted(summary.items()):<br>        types = &quot;, &quot;.join(sorted(info[&quot;types&quot;]))<br>        lines.append(f&quot;| {path} | {info[&#39;resource_count&#39;]} | {types} |\n&quot;)<br><br>    with open(output_file, &quot;w&quot;) as f:<br>        f.writelines(lines)<br><br>    logger.info(f&quot;Inventory report written to {output_file}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    OUTPUT_DIR = &quot;./generated&quot;<br>    REPORT_FILE = &quot;./inventory.md&quot;<br><br>    jobs = [<br>        TerraformerJob(<br>            account_id=&quot;123456789012&quot;,<br>            region=&quot;us-east-1&quot;,<br>            resources=[&quot;ec2_instance&quot;, &quot;sg&quot;, &quot;s3&quot;, &quot;rds&quot;, &quot;iam&quot;],<br>            output_dir=OUTPUT_DIR,<br>        ),<br>        TerraformerJob(<br>            account_id=&quot;123456789012&quot;,<br>            region=&quot;eu-west-1&quot;,<br>            resources=[&quot;ec2_instance&quot;, &quot;sg&quot;, &quot;s3&quot;],<br>            output_dir=OUTPUT_DIR,<br>        ),<br>    ]<br><br>    results = [run_terraformer(job) for job in jobs]<br>    failures = sum(1 for r in results if not r)<br><br>    if failures &gt; 0:<br>        logger.warning(f&quot;{failures} job(s) failed. Check logs above.&quot;)<br><br>    summary = collect_resource_summary(OUTPUT_DIR)<br>    generate_inventory_report(summary, REPORT_FILE)</pre><p>This gives you automated imports plus a generated markdown table showing everything Terraformer found, which you can commit to your infrastructure repository as a living inventory document.</p><h4>Python: Drift Detection After Import</h4><p>Once you have Terraform state, use this script to run terraform plan across all imported modules and collect any detected drift.</p><pre>import subprocess<br>import os<br>import json<br>from pathlib import Path<br>from typing import Dict, List<br><br>def run_terraform_plan(module_dir: str) -&gt; Dict:<br>    &quot;&quot;&quot;Run terraform plan in a directory and parse the output.&quot;&quot;&quot;<br>    result = subprocess.run(<br>        [&quot;terraform&quot;, &quot;plan&quot;, &quot;-detailed-exitcode&quot;, &quot;-json&quot;, &quot;-out=plan.tfplan&quot;],<br>        cwd=module_dir,<br>        capture_output=True,<br>        text=True,<br>    )<br><br>    # Exit codes: 0 = no diff, 1 = error, 2 = diff exists<br>    has_changes = result.returncode == 2<br>    has_error = result.returncode == 1<br><br>    changes = []<br>    for line in result.stdout.splitlines():<br>        try:<br>            event = json.loads(line)<br>            if event.get(&quot;type&quot;) == &quot;planned_change&quot;:<br>                changes.append({<br>                    &quot;resource&quot;: event[&quot;change&quot;][&quot;resource&quot;][&quot;addr&quot;],<br>                    &quot;action&quot;: event[&quot;change&quot;][&quot;action&quot;],<br>                })<br>        except json.JSONDecodeError:<br>            continue<br><br>    return {<br>        &quot;module&quot;: module_dir,<br>        &quot;has_changes&quot;: has_changes,<br>        &quot;has_error&quot;: has_error,<br>        &quot;changes&quot;: changes,<br>        &quot;stderr&quot;: result.stderr if has_error else &quot;&quot;,<br>    }<br><br><br>def scan_for_drift(base_dir: str) -&gt; List[Dict]:<br>    &quot;&quot;&quot;Scan all Terraformer-generated modules for drift.&quot;&quot;&quot;<br>    drift_report = []<br>    base_path = Path(base_dir)<br><br>    for main_tf in base_path.rglob(&quot;main.tf&quot;):<br>        module_dir = str(main_tf.parent)<br><br>        # Initialize terraform in this module first<br>        subprocess.run(<br>            [&quot;terraform&quot;, &quot;init&quot;, &quot;-backend=false&quot;],<br>            cwd=module_dir,<br>            capture_output=True,<br>        )<br><br>        result = run_terraform_plan(module_dir)<br>        if result[&quot;has_changes&quot;] or result[&quot;has_error&quot;]:<br>            drift_report.append(result)<br><br>    return drift_report<br><br><br>if __name__ == &quot;__main__&quot;:<br>    drift = scan_for_drift(&quot;./generated&quot;)<br><br>    if not drift:<br>        print(&quot;No drift detected. Infrastructure matches Terraform state.&quot;)<br>    else:<br>        print(f&quot;Drift detected in {len(drift)} module(s):\n&quot;)<br>        for item in drift:<br>            print(f&quot;  Module: {item[&#39;module&#39;]}&quot;)<br>            for change in item[&quot;changes&quot;]:<br>                print(f&quot;    [{change[&#39;action&#39;]}] {change[&#39;resource&#39;]}&quot;)<br>            print()</pre><h3>Alternatives to Terraformer</h3><p>Before committing to Terraformer, it is worth knowing what else exists.</p><h4>1. terraform import (Native Terraform)</h4><p>Terraform has a built-in import command that brings an existing resource into state. As of Terraform 1.5, it also supports import blocks in configuration. The limitation is that it only updates state; you still have to write the HCL configuration by hand. For small numbers of resources this is fine. For hundreds of resources it is not practical.</p><p>From Terraform 1.5 onwards:</p><pre>import {<br>  to = aws_instance.my_server<br>  id = &quot;i-0abc1234def56789&quot;<br>}</pre><h4>2. Former2</h4><p>Former2 is a browser-based tool that uses your AWS credentials directly in the browser to scan resources and generate CloudFormation or Terraform output. It requires no installation and is useful for quick one-off exports, but it relies on you manually selecting what to export and does not integrate well into CI pipelines.</p><h4>3. Pulumi Import</h4><p>If your team is using Pulumi instead of Terraform, Pulumi has its own import command (pulumi import) that generates code in your chosen language (Python, Go, TypeScript, etc.) from existing resources. It is comparable to Terraformer but native to the Pulumi ecosystem.</p><h4>4. AWS Cloud Control API and CDK</h4><p>AWS CDK has an experimental feature called cdk migrate that can generate CDK applications from existing CloudFormation stacks. This is limited to resources already managed by CloudFormation and does not help with resources created manually.</p><h4>5. Atlantis + Drift Detection</h4><p>Atlantis is a Terraform automation tool that runs plans and applies on pull requests. It does not generate code but it does surface drift in the plan output during PR workflows. Combined with a baseline generated by Terraformer, it gives you ongoing drift visibility.</p><h3>Pros and Cons of Terraformer</h3><h4>Pros</h4><p><strong>Gets you started fast.</strong> For teams with large amounts of unmanaged infrastructure, Terraformer does in minutes what would take weeks to write by hand.</p><p><strong>Multi-cloud and multi-provider support.</strong> AWS, GCP, Azure, Kubernetes, Datadog, GitHub, and more. You can consolidate infrastructure from multiple providers into a single Terraform monorepo.</p><p><strong>Generates state files too.</strong> Unlike some tools that only generate HCL, Terraformer also generates the state, meaning Terraform immediately recognizes the resources without requiring a separate import step.</p><p><strong>Good starting point for IaC adoption.</strong> Even if you rewrite the generated code over time, having something to start from beats staring at a blank file.</p><p><strong>Open source and free.</strong> No licensing costs, and the community around it is reasonably active.</p><h4>Cons</h4><p><strong>Generated code is not production-quality HCL.</strong> Terraformer generates valid but verbose, unorganized code. Variables are hardcoded, there are no modules, resource names are auto-generated and often ugly. You will need to refactor it.</p><p><strong>Does not handle dependencies well.</strong> The generated files are often split by resource type, not by logical application boundary. References between resources (like an EC2 instance referencing a security group) may not be wired up as Terraform references; they may be hardcoded IDs instead.</p><p><strong>Provider support is uneven.</strong> AWS support is solid. Some other providers are partially supported or lag behind in updates when provider APIs change.</p><p><strong>Can be overwhelming on large accounts.</strong> Running --resources=&quot;*&quot; on a large AWS account generates an enormous amount of code. Without a plan for how to organize and own it, you just trade one kind of mess for another.</p><p><strong>Requires cleanup before it is trustworthy.</strong> Treat Terraformer output as a first draft. Running terraform apply blindly on generated code without reviewing it first is risky.</p><p><strong>State management needs care.</strong> Terraformer generates local state files. Before these are useful in a team context, you need to configure remote state (S3 + DynamoDB for AWS) and migrate the state files.</p><h3>A Practical Adoption Path</h3><p>Here is how a real team would use Terraformer without creating more chaos:</p><p><strong>Phase 1: Inventory Only</strong> Run Terraformer and commit the output to a read-only branch. Do not manage anything yet. The goal is visibility. Grep through it, understand what you have, and write your inventory report.</p><p><strong>Phase 2: Triage by Risk</strong> Group resources into: “safe to manage now” (new, well-understood resources), “needs review” (existing production resources), and “ignore for now” (legacy or soon-to-be-deleted). Only pull phase-one resources into active Terraform management.</p><p><strong>Phase 3: Refactor the Generated Code</strong> Before managing anything, refactor the Terraformer output for that resource group. Extract variables. Reference resources by Terraform identifiers, not hardcoded IDs. Add tags. Move state to a remote backend.</p><p><strong>Phase 4: Apply and Monitor</strong> Run terraform plan. If the diff is clean (it shows no changes), you are in sync. If there is drift, reconcile it. Then set up a CI pipeline to run plan on every PR and alert on unexpected diffs.</p><p><strong>Phase 5: Enforce Going Forward</strong> Once you have the foothold, enforce that all new resources go through Terraform. Make the console read-only for most engineers using IAM policies. Drift becomes an exception you catch quickly instead of a chronic condition.</p><h3>Conclusion</h3><p>Infrastructure technical debt is expensive, not just financially but in cognitive load, in incident response time, and in the confidence your team has to make changes safely.</p><p>Terraformer does not solve all of this on its own, but it removes the biggest blocker: the blank page problem. You do not have to write Terraform from scratch for your existing infrastructure. You start from generated code, clean it up incrementally, and move toward a world where your infrastructure is just code that lives in git, has owners, and gets reviewed.</p><p>The tools in this post, the Python automation scripts for running imports and detecting drift, and the Go utilities for tagging and inventory reporting, give you a practical scaffolding to operationalize Terraformer in a real environment.</p><p>If your team is swimming in unmanaged cloud resources, pick one account, one region, one resource type, and run Terraformer today. The inventory alone is worth it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ebb72eb17c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI Agent That Watches Your Database and Acts on Its Own]]></title>
            <link>https://medium.com/@mgaurang123/i-built-an-ai-agent-that-watches-your-database-and-acts-on-its-own-66a40a0ce4b2?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a40a0ce4b2</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ambient-agents]]></category>
            <category><![CDATA[dapr]]></category>
            <category><![CDATA[drasi]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 06:50:49 GMT</pubDate>
            <atom:updated>2026-04-05T06:50:49.192Z</atom:updated>
            <content:encoded><![CDATA[<p>Most AI demos follow the same script. User types a prompt. Agent responds. Everyone claps.</p><p>That is autocomplete with extra steps.</p><p>The more interesting question is: what happens when no one is typing? What if the agent watches your data continuously and acts the moment something crosses a threshold, without being asked, without a human in the loop, without a scheduled cron job?</p><p>That is the ambient agent pattern. And I built a working implementation of it on Kubernetes.</p><p>Here is everything I learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqi9MU80qc9kNT7fwc9cWg.png" /></figure><h3>The Problem with How Agents Are Usually Built</h3><p>The standard agent architecture looks like this:</p><pre>User types something<br>      |<br>      v<br>LLM reasons about it<br>      |<br>      v<br>Agent calls a tool<br>      |<br>      v<br>Response comes back</pre><p>This works for assistants. It does not work for operational systems.</p><p>Imagine an inventory management system. You do not want a human typing “check stock levels” every few minutes. You want the system to notice when stock drops below a threshold and immediately place a reorder and alert the operations team. On its own. Every time. At 3am if needed.</p><p>The reactive, poll-based alternative most teams reach for looks like this:</p><pre># The naive approach most teams ship<br>while True:<br>    rows = db.query(&quot;SELECT * FROM inventory WHERE stock_level &lt; reorder_threshold&quot;)<br>    for row in rows:<br>        trigger_agent(row)<br>    time.sleep(60)</pre><p>This works until it does not. You are polling on a fixed interval, so you are always trading off latency against database load. You need to track which rows you already processed or you will trigger the agent on the same low-stock item every 60 seconds. You need to handle missed runs, restarts, and crashes. The logic that seems simple on day one becomes a maintenance burden by month three.</p><p>There is a better way.</p><h3>The Ambient Agent Pattern</h3><p>An ambient agent does not wait to be asked. It watches the data continuously and wakes up exactly when something crosses a condition.</p><pre>Always running, doing nothing<br>                               |<br>                    PostgreSQL row changes<br>                               |<br>                    Drasi detects it immediately<br>                               |<br>                    Smart Router routes the event<br>                               |<br>                    Agent wakes up, reasons, acts<br>                               |<br>                    Agent goes back to waiting</pre><p>No polling. No interval. No “did I already process this?” bookkeeping. The agent is event-driven at the data layer.</p><p>I built this for an inventory management system where a PostgreSQL table tracks stock levels. The moment any product’s stock drops below its reorder threshold, the agent places a reorder and alerts the operations team. No human in the loop, no manual trigger.</p><p>Here is what the stack looks like.</p><h3>The Stack</h3><p><strong>Drasi (Microsoft, Open Source)</strong></p><p>Drasi is a reactive continuous query engine. You write a Cypher query. Drasi evaluates it continuously against your database. The moment a row crosses the condition, Drasi fires a ChangeEvent downstream.</p><pre>MATCH (i:inventory)<br>WHERE i.stock_level &lt; i.reorder_threshold<br>RETURN i.product_name AS productName,<br>       i.stock_level  AS stockLevel</pre><p>This is not a cron job. Drasi uses change data capture (CDC) on PostgreSQL to detect row-level changes in real time. The latency is measured in milliseconds, not minutes.</p><p><strong>Dapr (CNCF)</strong></p><p>Dapr handles the distributed plumbing: pub/sub messaging, state store, durable workflow runtime. Without Dapr, I would be hand-writing Redis clients, retry logic, actor registration, and workflow state management. Dapr wraps all of that behind a clean HTTP/gRPC API.</p><p><strong>dapr-agents</strong></p><p>An AI agent framework built on top of Dapr Workflow. The key piece is DurableAgent, which gives you a fully durable LLM reasoning loop. If the pod crashes mid-tool-call, the workflow resumes where it left off when the pod restarts. That durability matters in production.</p><p><strong>Smart Router (Custom Drasi Reaction)</strong></p><p>The bridge between Drasi and Dapr. Drasi knows nothing about Dapr. Dapr knows nothing about Drasi. The Smart Router sits between them: it receives Drasi ChangeEvents, looks up routing rules from Redis, and publishes spec-compliant CloudEvents to the correct Dapr Pub/Sub topic.</p><p>The Smart Router also hosts an embedded MCP (Model Context Protocol) server on port 3001 so agents can discover and manage routing rules dynamically at runtime without redeployment.</p><p><strong>Ollama + llama3.2:3b</strong></p><p>A local LLM running inside the Kubernetes cluster. No API keys. No cloud calls. No per-token billing. The model runs in a pod alongside the agent.</p><h3>Architecture</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                        Data Layer                               │<br>│   PostgreSQL ──► Drasi Source ──► Continuous Query              │<br>│                        │                                        │<br>│                        ▼  ChangeEvent                           │<br>│              ┌─────────────────────┐                            │<br>│              │   Smart Router      │  (Drasi Reaction)          │<br>│              │   (Python)          │◄── MCP Server :3001        │<br>│              └─────────┬───────────┘    subscribe/list queries  │<br>│                        │  CloudEvent (Dapr Pub/Sub)             │<br>│                        ▼                                        │<br>│              ┌─────────────────────┐                            │<br>│              │   Dapr Pub/Sub      │  (Redis)                   │<br>│              │   inventory-alerts  │                            │<br>│              └─────────┬───────────┘                            │<br>│                        │  POST /inventory-alerts                │<br>│                        ▼                                        │<br>│              ┌─────────────────────┐                            │<br>│              │   InventoryAgent    │  (DurableAgent)            │<br>│              │   llama3.2:3b       │──► place_reorder()         │<br>│              │   (Ollama)          │──► send_alert()            │<br>│              └─────────────────────┘                            │<br>└─────────────────────────────────────────────────────────────────┘</pre><h3>The Full Data Flow</h3><p>Step by step, when a row changes in PostgreSQL:</p><ol><li><strong>Drasi</strong> evaluates the low-stock-query Cypher expression continuously against the source. No polling. CDC handles change detection.</li><li>When stock_level &lt; reorder_threshold becomes true for a row, Drasi fires a ChangeEvent to the registered Reaction.</li><li><strong>Smart Router</strong> receives the event, matches it against routing rules stored in Redis, builds a spec-compliant CloudEvent, and publishes it to the inventory-alerts Dapr Pub/Sub topic.</li><li><strong>Dapr</strong> delivers the event to the agent’s /inventory-alerts HTTP endpoint via push subscription.</li><li>The endpoint formats the change as a task string and schedules a DurableAgent workflow.</li><li><strong>llama3.2:3b</strong> via Ollama reads the task, reasons about what to do, and calls PlaceReorder() and SendAlert() tools.</li><li>Agent goes back to waiting.</li></ol><p>Nobody typed anything. A database row changed and within seconds the agent had reasoned and acted.</p><h3>Code Deep Dive</h3><h4>The Smart Router: Bridging Drasi and Dapr</h4><p>The Smart Router is the most novel piece. It is a Python Drasi Reaction that does four things: receives ChangeEvents, applies routing rules, builds CloudEvents, and publishes to Dapr.</p><p>Here is the core routing logic:</p><pre># smart_router/router.py<br><br>import structlog<br>from smart_router.publisher import EventPublisher<br>from smart_router.rules import RoutingRule<br>from smart_router.state import RuleStore<br><br>log = structlog.get_logger()<br><br><br>class SmartRouter:<br>    def __init__(self, publisher: EventPublisher, rule_store: RuleStore):<br>        self.publisher = publisher<br>        self.rule_store = rule_store<br><br>    async def handle_change_event(self, query_id: str, event: dict) -&gt; None:<br>        rules = await self.rule_store.get_rules(query_id)<br><br>        if not rules:<br>            log.info(&quot;smart_router.no_rules&quot;, query_id=query_id)<br>            return<br><br>        matched = [r for r in rules if self._matches(event, r)]<br>        log.info(&quot;smart_router.event_received&quot;,<br>                 query_id=query_id,<br>                 matched_rules=len(matched))<br><br>        for rule in matched:<br>            await self.publisher.publish(<br>                event=event,<br>                topic=rule.target_topic,<br>                pubsub_name=rule.pubsub_name,<br>            )<br><br>    def _matches(self, event: dict, rule: RoutingRule) -&gt; bool:<br>        if not rule.filter:<br>            return True<br>        added = event.get(&quot;addedResults&quot;, [])<br>        return any(<br>            self._check_filter(row, rule.filter)<br>            for row in added<br>        )<br><br>    def _check_filter(self, row: dict, f) -&gt; bool:<br>        value = row.get(f.field)<br>        if f.operator == &quot;lt&quot;:<br>            return float(value) &lt; float(f.value)<br>        if f.operator == &quot;gt&quot;:<br>            return float(value) &gt; float(f.value)<br>        if f.operator == &quot;eq&quot;:<br>            return str(value) == str(f.value)<br>        return False</pre><p>The publisher side builds a proper CloudEvent before publishing to Dapr:</p><pre># smart_router/publisher.py<br><br>import json<br>from datetime import datetime, timezone<br>from cloudevents.http import CloudEvent<br>from cloudevents.conversion import to_structured<br>from dapr.clients import DaprClient<br>import structlog<br><br>log = structlog.get_logger()<br><br><br>def _to_serializable(obj):<br>    &quot;&quot;&quot;Drasi SDK returns RecordUnknown objects that are not JSON serializable.&quot;&quot;&quot;<br>    if isinstance(obj, dict):<br>        return {k: _to_serializable(v) for k, v in obj.items()}<br>    if isinstance(obj, list):<br>        return [_to_serializable(i) for i in obj]<br>    try:<br>        json.dumps(obj)<br>        return obj<br>    except TypeError:<br>        return str(obj)<br><br><br>class EventPublisher:<br>    def __init__(self, dapr_client: DaprClient):<br>        self.client = dapr_client<br><br>    async def publish(self, event: dict, topic: str, pubsub_name: str) -&gt; None:<br>        safe_data = _to_serializable(event)<br><br>        cloud_event = CloudEvent(<br>            attributes={<br>                &quot;type&quot;: &quot;com.drasi.changeevent&quot;,<br>                &quot;source&quot;: &quot;drasi/smart-router&quot;,<br>                &quot;time&quot;: datetime.now(timezone.utc).isoformat(),<br>            },<br>            data=safe_data,<br>        )<br><br>        headers, body = to_structured(cloud_event)<br><br>        self.client.publish_event(<br>            pubsub_name=pubsub_name,<br>            topic_name=topic,<br>            data=body,<br>            data_content_type=&quot;application/cloudevents+json&quot;,<br>        )<br><br>        log.info(&quot;publisher.published&quot;,<br>                 event_id=cloud_event[&quot;id&quot;],<br>                 topic=topic)</pre><h4>The Agent: Durable LLM Reasoning on Real Events</h4><p>The agent receives the CloudEvent from Dapr and runs an LLM reasoning loop to decide which tools to call.</p><pre># demo/agent/agent.py<br><br>import logging<br>from contextlib import asynccontextmanager<br>from fastapi import FastAPI, Request<br>from dapr_agents import DurableAgent, tool<br>from dapr_agents.extensions.drasi import ChangeEvent<br><br>logging.basicConfig(level=logging.INFO)<br>log = logging.getLogger(&quot;inventory-agent&quot;)<br><br><br>@tool<br>def place_reorder(product_id: str, quantity: str) -&gt; str:<br>    &quot;&quot;&quot;Place a reorder for a product that is low on stock.&quot;&quot;&quot;<br>    log.info(f&quot;PlaceReorder: {quantity} units of {product_id}&quot;)<br>    return f&quot;Reorder placed: {quantity} units of {product_id}&quot;<br><br><br>@tool<br>def send_alert(message: str, severity: str) -&gt; str:<br>    &quot;&quot;&quot;Send an alert to the operations team.&quot;&quot;&quot;<br>    log.info(f&quot;SendAlert [{severity}]: {message}&quot;)<br>    return f&quot;Alert sent: {message}&quot;<br><br><br>agent = DurableAgent(<br>    name=&quot;InventoryAgent&quot;,<br>    instructions=(<br>        &quot;You are an inventory management agent. &quot;<br>        &quot;When you receive a low-stock alert, always place a reorder &quot;<br>        &quot;and send an alert to the operations team.&quot;<br>    ),<br>    tools=[place_reorder, send_alert],<br>    message_bus_name=&quot;pubsub&quot;,<br>    state_store_name=&quot;statestore&quot;,<br>    llm_base_url=&quot;http://ollama:11434/v1&quot;,<br>    llm_model=&quot;llama3.2:3b&quot;,<br>)<br><br>runner = None<br><br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    global runner<br>    runner = await agent.start()<br>    yield<br><br><br>app = FastAPI(lifespan=lifespan)<br><br><br>@app.post(&quot;/inventory-alerts&quot;)<br>async def handle_inventory_alert(request: Request):<br>    &quot;&quot;&quot;<br>    Explicit push subscription endpoint.<br>    dapr-agents v1.0.0 bypasses @drasi_trigger decorated handlers for DurableAgent,<br>    so we wire the endpoint manually and call runner.run() directly.<br>    &quot;&quot;&quot;<br>    body = await request.json()<br>    raw_data = body.get(&quot;data&quot;, body)<br>    event = ChangeEvent(**raw_data)<br><br>    if not event.has_additions:<br>        return {&quot;status&quot;: &quot;no low-stock items in event&quot;}<br><br>    items = &quot;\n&quot;.join(<br>        f&quot;  - {r.get(&#39;productName&#39;)}: {r.get(&#39;stockLevel&#39;)} units&quot;<br>        for r in event.addedResults<br>    )<br><br>    task = (<br>        f&quot;Low stock alert:\n{items}\n\n&quot;<br>        f&quot;Place reorders and notify the operations team.&quot;<br>    )<br><br>    await runner.run(agent, {&quot;task&quot;: task})<br>    return {&quot;status&quot;: &quot;workflow scheduled&quot;}</pre><h4>The MCP Server: Dynamic Routing Without Redeployment</h4><p>One of the more interesting pieces is the embedded MCP server inside the Smart Router. Any agent can connect to it and subscribe to new Drasi queries at runtime without redeploying anything.</p><pre># smart_router/mcp_server.py<br><br>from fastmcp import FastMCP<br>from smart_router.rules import RoutingRule, FieldFilter<br>from smart_router.state import RuleStore<br><br>mcp = FastMCP(&quot;SmartRouter&quot;, host=&quot;0.0.0.0&quot;, port=3001)<br>_rule_store: RuleStore = None<br><br><br>def init_mcp(rule_store: RuleStore):<br>    global _rule_store<br>    _rule_store = rule_store<br><br><br>@mcp.tool()<br>async def list_queries() -&gt; dict:<br>    &quot;&quot;&quot;List all active routing rules.&quot;&quot;&quot;<br>    rules = await _rule_store.get_all_rules()<br>    return {&quot;rules&quot;: [r.model_dump() for r in rules]}<br><br><br>@mcp.tool()<br>async def subscribe(<br>    query_id: str,<br>    target_topic: str,<br>    pubsub_name: str = &quot;pubsub&quot;,<br>    filter_field: str = None,<br>    filter_operator: str = None,<br>    filter_value: str = None,<br>) -&gt; dict:<br>    &quot;&quot;&quot;Add a routing rule. Optionally filter on a specific field.&quot;&quot;&quot;<br>    rule = RoutingRule(<br>        query_id=query_id,<br>        target_topic=target_topic,<br>        pubsub_name=pubsub_name,<br>        filter=FieldFilter(<br>            field=filter_field,<br>            operator=filter_operator,<br>            value=filter_value,<br>        ) if filter_field else None,<br>    )<br>    await _rule_store.save_rule(rule)<br>    return {&quot;status&quot;: &quot;subscribed&quot;, &quot;rule&quot;: rule.model_dump()}<br><br><br>@mcp.tool()<br>async def unsubscribe(query_id: str, target_topic: str) -&gt; dict:<br>    &quot;&quot;&quot;Remove a routing rule.&quot;&quot;&quot;<br>    await _rule_store.delete_rule(query_id, target_topic)<br>    return {&quot;status&quot;: &quot;unsubscribed&quot;}</pre><p>An agent that wants to wire itself to a new Drasi query calls the MCP server directly:</p><pre>import httpx<br><br>with httpx.Client(timeout=10) as client:<br>    with client.stream(&quot;GET&quot;, &quot;http://smart-router:3001/sse&quot;) as r:<br>        for line in r.iter_lines():<br>            if line.startswith(&quot;data:&quot;):<br>                endpoint = line.removeprefix(&quot;data:&quot;).strip()<br>                break<br><br>    resp = client.post(<br>        f&quot;http://smart-router:3001{endpoint}&quot;,<br>        json={<br>            &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;id&quot;: 1,<br>            &quot;method&quot;: &quot;tools/call&quot;,<br>            &quot;params&quot;: {<br>                &quot;name&quot;: &quot;subscribe&quot;,<br>                &quot;arguments&quot;: {<br>                    &quot;query_id&quot;: &quot;high-temperature-query&quot;,<br>                    &quot;target_topic&quot;: &quot;temperature-alerts&quot;,<br>                    &quot;pubsub_name&quot;: &quot;pubsub&quot;,<br>                    &quot;filter_field&quot;: &quot;temperature&quot;,<br>                    &quot;filter_operator&quot;: &quot;gt&quot;,<br>                    &quot;filter_value&quot;: &quot;80&quot;,<br>                }<br>            }<br>        }<br>    )<br>    print(resp.json())</pre><p>No redeployment. No config file update. The routing rule is live immediately and persists in Redis across restarts.</p><h4>Scale to Zero with KEDA</h4><p>The agent does nothing when there are no events. Running it at full replicas 24/7 wastes resources. KEDA handles this with a ScaledObject that watches the Redis stream depth.</p><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: inventory-agent-scaler<br>  namespace: default<br>spec:<br>  scaleTargetRef:<br>    name: inventory-agent<br>  minReplicaCount: 0<br>  maxReplicaCount: 5<br>  triggers:<br>    - type: redis-streams<br>      metadata:<br>        address: redis.default.svc.cluster.local:6379<br>        stream: pubsub-inventory-alerts<br>        consumerGroup: inventory-agent<br>        pendingEntriesCount: &quot;1&quot;</pre><p>With minReplicaCount: 0, the agent pod does not exist when there is nothing to process. The moment a ChangeEvent arrives in the Redis stream, KEDA spins up a replica. Once the backlog clears, it scales back to zero. True scale-to-zero for an event-driven AI agent.</p><h3>Real Demo Output</h3><p>Three terminals. One database change.</p><pre>kubectl exec -n default deployment/postgres -- psql -U postgres -d inventory_db \<br>  -c &quot;UPDATE inventory SET stock_level = 2 WHERE product_id = &#39;GADGET-002&#39;;&quot;</pre><p>Smart Router terminal:</p><pre>smart_router.event_received   matched_rules=1   query_id=low-stock-query<br>smart_router.routing          pubsub=pubsub     topic=inventory-alerts<br>publisher.published           event_id=b199a3...<br>POST /low-stock-query  200 OK</pre><p>Agent terminal:</p><pre>POST /inventory-alerts  200 OK<br><br>user:<br>  Low stock alert:<br>    - Super Gadget: 2 units<br>  Place reorders and notify team.<br><br>InventoryAgent(assistant):<br>  Running tool: PlaceReorder { product_id: &quot;Super Gadget&quot;, quantity: &quot;2&quot; }<br>  Running tool: SendAlert { message: &quot;Low stock: Super Gadget at 2 units&quot;, severity: &quot;LOW&quot; }<br><br>PlaceReorder: Reorder placed: 2 units of Super Gadget<br>SendAlert:    Alert sent.</pre><p>No human in the loop. A row changed, Drasi saw it, the Smart Router routed it, the agent reasoned and acted. The whole pipeline ran in under five seconds.</p><h3>Tech Stack</h3><ul><li><strong>Kubernetes (kind)</strong> — container orchestration</li><li><strong>Drasi</strong> — continuous reactive query engine with CDC on PostgreSQL</li><li><strong>Dapr</strong> — distributed runtime for pub/sub, state store, and workflow</li><li><strong>dapr-agents</strong> — durable AI agent framework on Dapr Workflow</li><li><strong>Ollama + llama3.2:3b</strong> — local LLM with tool calling support</li><li><strong>PostgreSQL + Debezium</strong> — source database with change data capture</li><li><strong>Redis</strong> — state store and pub/sub broker</li><li><strong>FastAPI + uvicorn</strong> — agent HTTP server</li><li><strong>KEDA</strong> — scale-to-zero based on Redis stream depth</li><li><strong>FastMCP</strong> — embedded MCP server in the Smart Router</li><li><strong>Python 3.11</strong> — implementation language</li></ul><h3>Where This Pattern Actually Makes Sense</h3><p>Ambient agents are not a demo trick. The pattern is useful anywhere you need automated reasoning and action in response to data changes.</p><p><strong>Compliance monitoring</strong> — agent watches audit logs, flags anomalies, and opens a ticket automatically when a policy is violated.</p><p><strong>Infrastructure operations</strong> — agent monitors pod crash rates, scales affected deployments, or creates a PagerDuty incident when thresholds are crossed.</p><p><strong>Finance</strong> — agent watches transaction patterns in real time and pauses a card when a fraud signal matches defined conditions.</p><p><strong>Healthcare</strong> — agent monitors patient vitals in a database and alerts the care team when thresholds are crossed.</p><p><strong>Supply chain</strong> — exactly what this demo does. Stock drops, reorder fires. No human touchpoint needed for routine operations.</p><p>The common thread: continuous query on structured data, change event to an agent, agent reasons and takes action. The LLM is not answering questions. It is making operational decisions based on live data state.</p><h3>Honest Assessment</h3><p>What works well:</p><ul><li>Drasi’s continuous query approach eliminates polling entirely. The latency between a row change and an agent response is genuinely low.</li><li>Dapr’s Workflow runtime makes the agent durable. A pod crash mid-tool-call means the tool runs again on restart, not that the operation is silently lost.</li><li>The MCP server in the Smart Router is a clean way to manage routing rules without touching config files or redeploying.</li><li>Scale-to-zero with KEDA is real. The agent pod does not exist when there is nothing to process.</li></ul><p>What needs work:</p><ul><li>dapr-agents v1.0.0 has real compatibility bugs with DurableAgent pub/sub handlers. The workaround is not complex, but it should not be necessary.</li><li>Drasi’s dependency on MongoDB for internal state is not obvious from the documentation. The race condition on restart caught me completely off-guard.</li><li>Running llama3.2:3b inside Kubernetes adds significant resource requirements. Not suitable for environments where you cannot provision enough CPU/memory for the model.</li><li>Namespace isolation requirements for Dapr components add operational complexity in multi-namespace deployments.</li></ul><h3>Conclusion</h3><p>The ambient agent pattern is fundamentally different from the prompt-response loop that defines most AI applications. The agent is not answering questions. It is watching your systems, making decisions, and taking action the moment conditions are met.</p><p>Drasi handles the hard part: CDC-based reactive queries with no polling, no interval management, no duplicate detection. Dapr handles the distributed systems plumbing. dapr-agents provides the durable reasoning loop on top. The Smart Router bridges the two worlds together.</p><p>The bugs I hit were real and non-obvious. The solutions were straightforward once I understood what was actually happening under the hood. That is usually how it goes.</p><p>The code is all open source. If you are building anything that needs reactive, event-driven AI agents, this architecture is worth understanding even if you swap out individual components for something that fits your stack better.</p><p><em>Thanks for reading. If you have questions about the architecture, the bugs, or the ambient agent pattern in general, drop them in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a40a0ce4b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dapr: The Runtime That Makes Distributed Systems Actually Manageable]]></title>
            <link>https://medium.com/@mgaurang123/dapr-the-runtime-that-makes-distributed-systems-actually-manageable-e1d4b1fbeb78?source=rss-80c27f6cc0d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d4b1fbeb78</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[dapr]]></category>
            <dc:creator><![CDATA[Gaurang Malvankar]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 08:09:09 GMT</pubDate>
            <atom:updated>2026-03-14T08:09:09.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Building distributed systems is hard. Not “write a tricky algorithm” hard, but “coordinate a dozen moving parts across cloud providers, handle retries, manage state, wire up pub/sub, trace everything, and somehow keep your sanity” hard.</p><p>Every backend team that ships microservices eventually runs into the same wall: the application logic is simple, but the infrastructure glue surrounding it is not. You end up writing the same boilerplate for retries, the same configuration for service discovery, the same SDK wrappers for your message broker, and the same secret-fetching code in every single service.</p><p>Dapr, which stands for <strong>Distributed Application Runtime</strong>, is Microsoft’s answer to that problem. It takes all of that infrastructure plumbing and wraps it into a sidecar process that your application talks to over HTTP or gRPC. Your app stays clean. The sidecar handles the complexity.</p><p>This post covers what Dapr is, why it exists, how it works across cloud environments, what APIs it exposes, how to deploy it on Kubernetes, and where it actually makes sense to use it. Code examples are in Python and Go throughout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HOo1Y8cwln57kTdizKYRQ.png" /></figure><h3>What Is Dapr?</h3><p>Dapr is an open-source, portable runtime for building microservices and distributed applications. It runs as a <strong>sidecar</strong> alongside your service, exposing a set of stable APIs that abstract away the underlying infrastructure.</p><p>The key idea is this: instead of your application directly using an AWS SQS SDK, a Redis client, or a Vault API library, your application calls the Dapr sidecar over a local HTTP/gRPC call. The sidecar figures out which infrastructure component to talk to based on configuration.</p><pre>+-------------------+        HTTP/gRPC        +-------------------+<br>|   Your Service    | &lt;---------------------&gt; |   Dapr Sidecar    |<br>|   (port 8080)     |      (localhost:3500)    |   (port 3500)     |<br>+-------------------+                         +--------+----------+<br>                                                        |<br>                              +-------------------------+-----------+<br>                              |             |           |           |<br>                         +----+----+  +-----+---+ +-----+--+ +-----+----+<br>                         |  Redis  |  |  Kafka  | | Vault  | |  AWS SQS |<br>                         +---------+  +---------+ +--------+ +----------+</pre><h3>Why Use Dapr?</h3><p>Before Dapr, every microservice team solved the same problems independently:</p><ul><li><strong>State management</strong>: Each service integrated its own Redis or database client, with its own retry logic and connection pooling.</li><li><strong>Pub/Sub messaging</strong>: Developers wrote Kafka consumer/producer code directly into services, coupling them to the broker implementation.</li><li><strong>Service invocation</strong>: Service-to-service calls required service discovery, load balancing, and retry logic all wired up manually.</li><li><strong>Secret management</strong>: Fetching secrets from Vault or AWS Secrets Manager meant adding SDK dependencies and writing boilerplate in every service.</li><li><strong>Observability</strong>: Getting distributed traces required instrumenting each service individually.</li></ul><p>Dapr standardizes all of this. The benefits are concrete:</p><p><strong>Portability</strong>: Your application does not care whether it runs on AWS, Azure, GCP, or on-premises. The Dapr component configuration changes; the application code does not.</p><p><strong>Reduced dependencies</strong>: Your service no longer needs a Kafka client library, a Redis client, a Vault SDK, and a service mesh client. It just needs the Dapr SDK or the ability to make HTTP calls.</p><p><strong>Built-in resiliency</strong>: Dapr has built-in retries, timeouts, and circuit breakers configured through YAML. No retry library required in your service code.</p><p><strong>Standardized observability</strong>: Dapr emits OpenTelemetry traces, metrics, and logs out of the box. Plug in Zipkin, Jaeger, or Prometheus without touching your service code.</p><h3>How Dapr Interacts with Multiple Cloud Services and Platforms</h3><p>Dapr’s component model is what makes multi-cloud work. Every capability in Dapr is backed by a <strong>component</strong>, which is a YAML file that describes what infrastructure to use.</p><p>Here is an example state store component using Redis:</p><pre>apiVersion: dapr.io/v1alpha1<br>kind: Component<br>metadata:<br>  name: statestore<br>spec:<br>  type: state.redis<br>  version: v1<br>  metadata:<br>    - name: redisHost<br>      value: &quot;redis:6379&quot;<br>    - name: redisPassword<br>      secretKeyRef:<br>        name: redis-secret<br>        key: password</pre><p>Swap to Azure Cosmos DB by changing type: state.cosmosdb and updating the metadata. Your application code calling http://localhost:3500/v1.0/state/statestore stays exactly the same.</p><p>The same pattern applies across all building blocks:</p><pre>Building Block   | AWS                | Azure           | GCP            | Self-hosted<br>-----------------|--------------------|-----------------|----------------|------------<br>State Store      | DynamoDB           | Cosmos DB       | Firestore      | Redis<br>Pub/Sub          | SQS/SNS            | Service Bus     | Pub/Sub        | Kafka<br>Secret Store     | Secrets Manager    | Key Vault       | Secret Manager | Vault<br>Bindings         | S3, SQS, DynamoDB  | Blob, Event Hub | GCS, Pub/Sub   | MQTT, Kafka</pre><p>Dapr supports over 100 components across state stores, pub/sub brokers, secret stores, bindings, and middleware. The full list lives in the <a href="https://docs.dapr.io/reference/components-reference/">Dapr component registry</a>.</p><h3>Dapr APIs (Building Blocks)</h3><p>Dapr exposes its capabilities through a set of <strong>building block APIs</strong>. Each one is a stable HTTP/gRPC endpoint that abstracts a common distributed systems pattern.</p><h4>1. Service Invocation</h4><p>Reliable service-to-service calls with built-in retries, load balancing, and mTLS.</p><pre>GET http://localhost:3500/v1.0/invoke/{app-id}/method/{method-name}</pre><h4>2. State Management</h4><p>Read and write key-value state backed by any supported state store.</p><pre>POST http://localhost:3500/v1.0/state/{store-name}<br>GET  http://localhost:3500/v1.0/state/{store-name}/{key}</pre><h4>3. Pub/Sub Messaging</h4><p>Publish messages to a topic and subscribe to receive them, decoupled from the broker.</p><pre>POST http://localhost:3500/v1.0/publish/{pubsub-name}/{topic}</pre><p>Subscriptions are declared either programmatically or through a subscriptions YAML file.</p><h4>4. Bindings</h4><p>Trigger your app from external events (a file arriving in S3, a message on a queue) or invoke external systems (send an email, write to a database) without using their SDKs directly.</p><h4>5. Actors</h4><p>Dapr implements the virtual actor pattern, providing single-threaded, stateful objects with built-in timers and reminders. Useful for modeling entities like orders, sessions, or devices.</p><h4>6. Secrets</h4><p>Fetch secrets from any secret store through a single API call.</p><pre>GET http://localhost:3500/v1.0/secrets/{store-name}/{secret-name}</pre><h4>7. Configuration</h4><p>Read and subscribe to configuration values from stores like Redis or Azure App Configuration.</p><h4>8. Distributed Lock</h4><p>Acquire and release distributed locks backed by Redis or Zookeeper without adding SDK dependencies.</p><h4>9. Cryptography (alpha)</h4><p>Perform encrypt/decrypt operations through Dapr without handling keys in your application.</p><h4>10. Jobs (alpha)</h4><p>Schedule and manage background jobs with cron-style scheduling.</p><h3>Code Examples</h3><h4>Python: State Management and Pub/Sub</h4><p>Install the SDK:</p><pre>pip install dapr</pre><p>Saving and reading state:</p><pre>from dapr.clients import DaprClient<br><br>def save_order(order_id: str, order_data: dict):<br>    with DaprClient() as client:<br>        client.save_state(<br>            store_name=&quot;statestore&quot;,<br>            key=order_id,<br>            value=str(order_data),<br>        )<br>        print(f&quot;Saved order {order_id}&quot;)<br><br>def get_order(order_id: str):<br>    with DaprClient() as client:<br>        result = client.get_state(<br>            store_name=&quot;statestore&quot;,<br>            key=order_id,<br>        )<br>        if result.data:<br>            print(f&quot;Order: {result.data.decode(&#39;utf-8&#39;)}&quot;)<br>        else:<br>            print(&quot;Order not found&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    save_order(&quot;order-001&quot;, {&quot;item&quot;: &quot;widget&quot;, &quot;qty&quot;: 10, &quot;status&quot;: &quot;pending&quot;})<br>    get_order(&quot;order-001&quot;)</pre><p>Publishing a message:</p><pre>import json<br>from dapr.clients import DaprClient<br><br>def publish_order_event(order_id: str, status: str):<br>    with DaprClient() as client:<br>        event_data = {<br>            &quot;orderId&quot;: order_id,<br>            &quot;status&quot;: status,<br>        }<br>        client.publish_event(<br>            pubsub_name=&quot;pubsub&quot;,<br>            topic_name=&quot;orders&quot;,<br>            data=json.dumps(event_data),<br>            data_content_type=&quot;application/json&quot;,<br>        )<br>        print(f&quot;Published event for order {order_id}&quot;)<br><br>publish_order_event(&quot;order-001&quot;, &quot;shipped&quot;)</pre><p>Subscribing to messages (Flask-based subscriber):</p><pre>from flask import Flask, request, jsonify<br>import json<br><br>app = Flask(__name__)<br><br>@app.route(&quot;/dapr/subscribe&quot;, methods=[&quot;GET&quot;])<br>def subscribe():<br>    subscriptions = [<br>        {<br>            &quot;pubsubname&quot;: &quot;pubsub&quot;,<br>            &quot;topic&quot;: &quot;orders&quot;,<br>            &quot;route&quot;: &quot;/orders&quot;,<br>        }<br>    ]<br>    return jsonify(subscriptions)<br><br>@app.route(&quot;/orders&quot;, methods=[&quot;POST&quot;])<br>def handle_order():<br>    event = request.get_json()<br>    order_data = json.loads(event.get(&quot;data&quot;, &quot;{}&quot;))<br>    print(f&quot;Received order event: {order_data}&quot;)<br>    # Process the order here<br>    return jsonify({&quot;status&quot;: &quot;SUCCESS&quot;})<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(port=8080)</pre><p>Invoking another service:</p><pre>from dapr.clients import DaprClient<br><br>def get_inventory(item_id: str):<br>    with DaprClient() as client:<br>        response = client.invoke_method(<br>            app_id=&quot;inventory-service&quot;,<br>            method_name=f&quot;items/{item_id}&quot;,<br>            http_verb=&quot;GET&quot;,<br>        )<br>        return response.json()<br><br>item = get_inventory(&quot;widget-42&quot;)<br>print(item)</pre><p>Fetching a secret:</p><pre>from dapr.clients import DaprClient<br><br>def get_db_password():<br>    with DaprClient() as client:<br>        secret = client.get_secret(<br>            store_name=&quot;secretstore&quot;,<br>            key=&quot;db-password&quot;,<br>        )<br>        return secret.secret[&quot;db-password&quot;]<br><br>password = get_db_password()</pre><h4>Go: State Management and Pub/Sub</h4><p>Install the SDK:</p><pre>go get github.com/dapr/go-sdk/client</pre><p>Saving and reading state:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br><br>    dapr &quot;github.com/dapr/go-sdk/client&quot;<br>)<br><br>type Order struct {<br>    OrderID string `json:&quot;orderId&quot;`<br>    Item    string `json:&quot;item&quot;`<br>    Qty     int    `json:&quot;qty&quot;`<br>    Status  string `json:&quot;status&quot;`<br>}<br><br>func main() {<br>    ctx := context.Background()<br><br>    client, err := dapr.NewClient()<br>    if err != nil {<br>        log.Fatalf(&quot;failed to create dapr client: %v&quot;, err)<br>    }<br>    defer client.Close()<br><br>    order := Order{<br>        OrderID: &quot;order-001&quot;,<br>        Item:    &quot;widget&quot;,<br>        Qty:     10,<br>        Status:  &quot;pending&quot;,<br>    }<br><br>    data, _ := json.Marshal(order)<br><br>    // Save state<br>    err = client.SaveState(ctx, &quot;statestore&quot;, order.OrderID, data, nil)<br>    if err != nil {<br>        log.Fatalf(&quot;failed to save state: %v&quot;, err)<br>    }<br>    fmt.Println(&quot;Order saved&quot;)<br><br>    // Get state<br>    item, err := client.GetState(ctx, &quot;statestore&quot;, order.OrderID, nil)<br>    if err != nil {<br>        log.Fatalf(&quot;failed to get state: %v&quot;, err)<br>    }<br><br>    var retrieved Order<br>    json.Unmarshal(item.Value, &amp;retrieved)<br>    fmt.Printf(&quot;Retrieved: %+v\n&quot;, retrieved)<br>}</pre><p>Publishing a message:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br><br>    dapr &quot;github.com/dapr/go-sdk/client&quot;<br>)<br><br>type OrderEvent struct {<br>    OrderID string `json:&quot;orderId&quot;`<br>    Status  string `json:&quot;status&quot;`<br>}<br><br>func main() {<br>    ctx := context.Background()<br><br>    client, err := dapr.NewClient()<br>    if err != nil {<br>        log.Fatalf(&quot;failed to create dapr client: %v&quot;, err)<br>    }<br>    defer client.Close()<br><br>    event := OrderEvent{<br>        OrderID: &quot;order-001&quot;,<br>        Status:  &quot;shipped&quot;,<br>    }<br><br>    data, _ := json.Marshal(event)<br><br>    err = client.PublishEvent(ctx, &quot;pubsub&quot;, &quot;orders&quot;, data)<br>    if err != nil {<br>        log.Fatalf(&quot;failed to publish event: %v&quot;, err)<br>    }<br><br>    fmt.Println(&quot;Event published&quot;)<br>}</pre><p>Subscribing to messages (HTTP server):</p><pre>package main<br><br>import (<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>)<br><br>type DaprSubscription struct {<br>    PubsubName string `json:&quot;pubsubname&quot;`<br>    Topic      string `json:&quot;topic&quot;`<br>    Route      string `json:&quot;route&quot;`<br>}<br><br>type CloudEvent struct {<br>    Data json.RawMessage `json:&quot;data&quot;`<br>}<br><br>type OrderEvent struct {<br>    OrderID string `json:&quot;orderId&quot;`<br>    Status  string `json:&quot;status&quot;`<br>}<br><br>func main() {<br>    // Dapr calls this to discover subscriptions<br>    http.HandleFunc(&quot;/dapr/subscribe&quot;, func(w http.ResponseWriter, r *http.Request) {<br>        subs := []DaprSubscription{<br>            {<br>                PubsubName: &quot;pubsub&quot;,<br>                Topic:      &quot;orders&quot;,<br>                Route:      &quot;/orders&quot;,<br>            },<br>        }<br>        w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>        json.NewEncoder(w).Encode(subs)<br>    })<br><br>    // Dapr delivers messages here<br>    http.HandleFunc(&quot;/orders&quot;, func(w http.ResponseWriter, r *http.Request) {<br>        var event CloudEvent<br>        if err := json.NewDecoder(r.Body).Decode(&amp;event); err != nil {<br>            http.Error(w, &quot;bad request&quot;, http.StatusBadRequest)<br>            return<br>        }<br><br>        var order OrderEvent<br>        json.Unmarshal(event.Data, &amp;order)<br>        fmt.Printf(&quot;Received order: %+v\n&quot;, order)<br><br>        w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>        json.NewEncoder(w).Encode(map[string]string{&quot;status&quot;: &quot;SUCCESS&quot;})<br>    })<br><br>    log.Println(&quot;Starting subscriber on :8080&quot;)<br>    log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))<br>}</pre><p>Invoking another service:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br><br>    dapr &quot;github.com/dapr/go-sdk/client&quot;<br>)<br><br>func main() {<br>    ctx := context.Background()<br><br>    client, err := dapr.NewClient()<br>    if err != nil {<br>        log.Fatalf(&quot;failed to create dapr client: %v&quot;, err)<br>    }<br>    defer client.Close()<br><br>    content := &amp;dapr.DataContent{<br>        ContentType: &quot;application/json&quot;,<br>    }<br><br>    resp, err := client.InvokeMethodWithContent(<br>        ctx,<br>        &quot;inventory-service&quot;,<br>        &quot;items/widget-42&quot;,<br>        &quot;GET&quot;,<br>        content,<br>    )<br>    if err != nil {<br>        log.Fatalf(&quot;failed to invoke service: %v&quot;, err)<br>    }<br><br>    fmt.Printf(&quot;Response: %s\n&quot;, resp)<br>}</pre><h3>Dapr Workflows</h3><p>Dapr Workflows is a building block for authoring long-running, stateful business processes. It uses a durable execution model, similar to Temporal or Azure Durable Functions: workflow state is checkpointed after each step, so if a service crashes mid-workflow, it resumes from where it left off on restart.</p><p>Workflows are written in code (not YAML), which means they are versionable, testable, and familiar to developers.</p><p><strong>Key concepts:</strong></p><ul><li><strong>Workflow</strong>: The orchestrating function that defines the sequence of steps.</li><li><strong>Activity</strong>: A unit of work called by the workflow. Activities are where you put actual logic, like calling an API or writing to a database.</li><li><strong>Sub-workflow</strong>: A workflow that is called by another workflow.</li><li><strong>External events</strong>: Workflows can pause and wait for an external signal, such as a human approval.</li></ul><p>Python workflow example (order fulfillment):</p><pre>import dapr.ext.workflow as wf<br><br>def order_fulfillment_workflow(ctx: wf.DaprWorkflowContext, order_id: str):<br>    # Step 1: Verify inventory<br>    inventory_ok = yield ctx.call_activity(check_inventory, input=order_id)<br>    if not inventory_ok:<br>        yield ctx.call_activity(notify_out_of_stock, input=order_id)<br>        return {&quot;status&quot;: &quot;failed&quot;, &quot;reason&quot;: &quot;out_of_stock&quot;}<br><br>    # Step 2: Charge the customer<br>    payment_ok = yield ctx.call_activity(charge_customer, input=order_id)<br>    if not payment_ok:<br>        yield ctx.call_activity(notify_payment_failed, input=order_id)<br>        return {&quot;status&quot;: &quot;failed&quot;, &quot;reason&quot;: &quot;payment_failed&quot;}<br><br>    # Step 3: Ship the order<br>    tracking = yield ctx.call_activity(ship_order, input=order_id)<br><br>    # Step 4: Wait for delivery confirmation (external event)<br>    delivered = yield ctx.wait_for_external_event(&quot;delivery_confirmed&quot;)<br><br>    return {&quot;status&quot;: &quot;delivered&quot;, &quot;tracking&quot;: tracking}<br><br><br>def check_inventory(ctx: wf.ActivityContext, order_id: str) -&gt; bool:<br>    print(f&quot;Checking inventory for {order_id}&quot;)<br>    return True  # Simplified<br><br>def charge_customer(ctx: wf.ActivityContext, order_id: str) -&gt; bool:<br>    print(f&quot;Charging customer for {order_id}&quot;)<br>    return True  # Simplified<br><br>def ship_order(ctx: wf.ActivityContext, order_id: str) -&gt; str:<br>    print(f&quot;Shipping order {order_id}&quot;)<br>    return &quot;TRACK-12345&quot;<br><br>def notify_out_of_stock(ctx: wf.ActivityContext, order_id: str):<br>    print(f&quot;Notifying customer: {order_id} is out of stock&quot;)<br><br>def notify_payment_failed(ctx: wf.ActivityContext, order_id: str):<br>    print(f&quot;Notifying customer: payment failed for {order_id}&quot;)</pre><p><strong>Why use Dapr Workflows instead of writing orchestration yourself?</strong></p><ul><li>State is durable. A crash does not lose workflow progress.</li><li>Retries are built-in at the activity level.</li><li>Timeouts and compensation logic are first-class features.</li><li>You get visibility into running workflow instances through the Dapr API.</li></ul><h3>Dapr Agents</h3><p>Dapr Agents is an extension (currently in alpha/early access) that brings agentic AI patterns to the Dapr runtime. It provides building blocks for building AI agents that are stateful, event-driven, and resilient.</p><p>The core idea is that Dapr already handles everything an AI agent needs at the infrastructure level: state persistence, event-driven triggers, durable execution, and service invocation. Dapr Agents layers on top of this with abstractions for LLM interactions, tool execution, and multi-agent coordination.</p><p><strong>What Dapr Agents provides:</strong></p><ul><li><strong>Stateful agent memory</strong>: Store conversation history and agent state using Dapr’s state API backed by any supported store.</li><li><strong>Event-driven agents</strong>: Trigger agents in response to pub/sub events (a new order arrives, a user sends a message).</li><li><strong>Durable agent workflows</strong>: Long-running agent tasks that survive restarts, using Dapr Workflows under the hood.</li><li><strong>Multi-agent orchestration</strong>: One agent can invoke another using Dapr’s service invocation API.</li></ul><p>At the time of writing, Dapr Agents is still evolving rapidly. The underlying approach of using Dapr’s existing building blocks as the infrastructure for agentic systems is sound and represents a natural evolution of the platform. Follow the <a href="https://github.com/dapr/dapr-agents">Dapr Agents GitHub repository</a> for the latest status.</p><h3>What Can You Replace With Dapr?</h3><p>Dapr is not trying to replace your entire stack. But there are specific infrastructure components and patterns it can replace or reduce your dependency on:</p><pre>What You Have                                  | What Dapr Replaces It With<br>-----------------------------------------------|-----------------------------<br>Direct Kafka/RabbitMQ SDK in each service      | Dapr pub/sub building block<br>Redis client library in each service           | Dapr state management<br>Vault/AWS Secrets Manager SDK in each service  | Dapr secrets building block<br>Custom retry/timeout logic per service         | Dapr resiliency policies<br>Service mesh (Linkerd, Istio) for mTLS         | Dapr service invocation with mTLS<br>Custom distributed lock implementation        | Dapr distributed lock API<br>Temporal/Conductor for workflow orchestration  | Dapr Workflows<br>Direct database calls for actor state          | Dapr Actors</pre><p><strong>What Dapr does NOT replace:</strong></p><ul><li>Your actual infrastructure (you still need Redis, Kafka, Vault, etc.). Dapr abstracts them, but they still have to run somewhere.</li><li>A service mesh entirely. Dapr and Istio/Linkerd can coexist and complement each other.</li><li>Your API gateway or edge proxy.</li><li>A full observability platform (Prometheus, Grafana, Jaeger). Dapr emits the signals; you still need the platform to collect them.</li></ul><p>A realistic assessment: Dapr is most valuable when you have many microservices and want to standardize how they interact with infrastructure. For a monolith or a small two-service setup, it adds operational overhead without enough benefit.</p><h3>How to Configure Dapr in Your Kubernetes Cluster</h3><h4>Step 1: Install the Dapr CLI</h4><pre># macOS/Linux<br>wget -q https://raw.githubusercontent.com/dapr/cli/master/install/install.sh -O - | /bin/bash<br><br># Windows (PowerShell)<br>powershell -Command &quot;iwr -useb https://raw.githubusercontent.com/dapr/cli/master/install/install.ps1 | iex&quot;<br><br># Verify<br>dapr --version</pre><h4>Step 2: Initialize Dapr on Kubernetes</h4><pre># Install Dapr control plane to your cluster<br>dapr init --kubernetes --wait<br><br># Verify installation<br>dapr status -k</pre><p>This installs the Dapr operator, sidecar injector, placement service (for actors), and dashboard into the dapr-system namespace.</p><h4>Step 3: Define a Component</h4><p>Create a state store component using Redis:</p><pre># components/statestore.yaml<br>apiVersion: dapr.io/v1alpha1<br>kind: Component<br>metadata:<br>  name: statestore<br>  namespace: default<br>spec:<br>  type: state.redis<br>  version: v1<br>  metadata:<br>    - name: redisHost<br>      value: &quot;redis-master.default.svc.cluster.local:6379&quot;<br>    - name: redisPassword<br>      secretKeyRef:<br>        name: redis-secret<br>        key: password</pre><pre>kubectl apply -f components/statestore.yaml</pre><h4>Step 4: Configure a Pub/Sub Component</h4><pre># components/pubsub.yaml<br>apiVersion: dapr.io/v1alpha1<br>kind: Component<br>metadata:<br>  name: pubsub<br>  namespace: default<br>spec:<br>  type: pubsub.kafka<br>  version: v1<br>  metadata:<br>    - name: brokers<br>      value: &quot;kafka-broker.default.svc.cluster.local:9092&quot;<br>    - name: consumerGroup<br>      value: &quot;orders-group&quot;<br>    - name: authType<br>      value: &quot;none&quot;</pre><pre>kubectl apply -f components/pubsub.yaml</pre><h4>Step 5: Configure Resiliency Policies</h4><p>Dapr lets you define retry, timeout, and circuit breaker policies through a Resiliency resource:</p><pre># resiliency.yaml<br>apiVersion: dapr.io/v1alpha1<br>kind: Resiliency<br>metadata:<br>  name: order-resiliency<br>  namespace: default<br>spec:<br>  policies:<br>    retries:<br>      retryForever:<br>        policy: exponential<br>        maxInterval: 15s<br>        maxRetries: 5<br>    circuitBreakers:<br>      simpleCB:<br>        maxRequests: 1<br>        interval: 10s<br>        timeout: 30s<br>        trip: consecutiveFailures &gt;= 3<br>  targets:<br>    apps:<br>      inventory-service:<br>        retry: retryForever<br>        circuitBreaker: simpleCB</pre><pre>kubectl apply -f resiliency.yaml</pre><h4>Step 6: Annotate Your Deployment</h4><p>Add Dapr annotations to your Kubernetes deployment to inject the sidecar:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-service<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: order-service<br>  template:<br>    metadata:<br>      labels:<br>        app: order-service<br>      annotations:<br>        dapr.io/enabled: &quot;true&quot;<br>        dapr.io/app-id: &quot;order-service&quot;<br>        dapr.io/app-port: &quot;8080&quot;<br>        dapr.io/log-level: &quot;info&quot;<br>        dapr.io/enable-api-logging: &quot;true&quot;<br>    spec:<br>      containers:<br>        - name: order-service<br>          image: your-registry/order-service:latest<br>          ports:<br>            - containerPort: 8080</pre><p>The dapr.io/enabled: &quot;true&quot; annotation triggers the sidecar injector. When your pod starts, the Dapr sidecar is automatically injected alongside your container.</p><h4>Step 7: Verify the Sidecar Is Running</h4><pre># Check that your pod has two containers (app + dapr sidecar)<br>kubectl get pods<br><br># Should show 2/2 READY for your pod<br># order-service-7d9f8b-xyz   2/2   Running   0   1m<br><br># Check Dapr sidecar logs<br>kubectl logs order-service-7d9f8b-xyz -c daprd<br><br># List all Dapr-enabled applications<br>dapr list -k</pre><h4>Step 8: Access the Dapr Dashboard</h4><pre>dapr dashboard -k</pre><p>Opens a browser dashboard showing running applications, components, and configuration.</p><h4>Configure mTLS (Optional but Recommended)</h4><p>Dapr enables mTLS between services by default on Kubernetes. You can configure certificate rotation and trust anchor through the Configuration resource:</p><pre>apiVersion: dapr.io/v1alpha1<br>kind: Configuration<br>metadata:<br>  name: default<br>  namespace: default<br>spec:<br>  mtls:<br>    enabled: true<br>    workloadCertTTL: &quot;24h&quot;<br>    allowedClockSkew: &quot;15m&quot;</pre><h3>Use Cases for Dapr</h3><h4>1. Order Processing Pipelines</h4><p>An e-commerce platform with separate services for checkout, inventory, payment, and shipping. Dapr pub/sub decouples these services. Dapr Workflows orchestrates the sequence with durability. If the payment service crashes mid-checkout, the workflow resumes cleanly.</p><h4>2. Multi-Cloud or Cloud Migration</h4><p>A team migrating from AWS to Azure. By using Dapr’s state and pub/sub APIs, they can run both environments simultaneously and flip the component configuration when ready. No application code changes required.</p><h4>3. IoT and Event-Driven Processing</h4><p>Dapr bindings can receive events from MQTT brokers, process them using actors (one actor per device), and write results to a time-series database, all without any broker-specific SDK code in the processing service.</p><h4>4. Background Job Processing</h4><p>Use Dapr bindings or pub/sub to trigger background jobs. Use Dapr Workflows for long-running jobs that need progress tracking and resumability.</p><h4>5. Microservice Standardization</h4><p>An organization with 20 microservices written by different teams, each using different patterns for secrets, state, and messaging. Introduce Dapr as the standard runtime layer. Each team adopts the same building blocks through a consistent API, regardless of language.</p><h4>6. AI Agent Infrastructure</h4><p>Using Dapr Agents (alpha) to build event-driven AI pipelines: a message arrives on a pub/sub topic, triggers an agent that calls an LLM, stores the result in state, and publishes the response back to another topic. The infrastructure resilience is handled by Dapr.</p><h3>Conclusion</h3><p>Dapr solves a real problem in microservices development: the infrastructure glue code that every team ends up writing independently, inconsistently, and incompletely. By moving that plumbing into a sidecar with a stable API, it lets teams focus on business logic and makes their services genuinely portable across cloud providers.</p><p>It is not magic. You still need to run the underlying infrastructure. You still need to understand your message broker and your state store. But Dapr changes the relationship between your application code and that infrastructure from tight coupling to clean abstraction.</p><p>For teams running multiple microservices, operating across cloud environments, or looking to standardize how their services handle state, messaging, and secrets, Dapr is worth serious consideration. Start by adding it to a single, non-critical service. Get comfortable with components and the sidecar model. Then expand from there.</p><p>The Kubernetes integration is mature, the component ecosystem is broad, and the Workflows building block makes long-running process orchestration accessible without running a separate orchestration platform. If you are building distributed systems and tired of writing the same infrastructure boilerplate in every service, Dapr is a good investment of your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d4b1fbeb78" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>