<?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 Hatam Abolghasemi on Medium]]></title>
        <description><![CDATA[Stories by Hatam Abolghasemi on Medium]]></description>
        <link>https://medium.com/@hatamabolghasemi?source=rss-6aa0f7c725f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N4yCReL4Kx1GrvdUswXp-Q.jpeg</url>
            <title>Stories by Hatam Abolghasemi on Medium</title>
            <link>https://medium.com/@hatamabolghasemi?source=rss-6aa0f7c725f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:05:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hatamabolghasemi/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[DaaC: The Lost XaaC Nobody Talks About]]></title>
            <link>https://medium.com/@hatamabolghasemi/daac-the-lost-xaac-nobody-talks-about-5b590838115e?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b590838115e</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[documentation-as-code]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 19:48:50 GMT</pubDate>
            <atom:updated>2026-09-03T19:49:48.584Z</atom:updated>
            <content:encoded><![CDATA[<p>I needed three new VMs. Fine, easy, except I needed to know which IPs in the subnet were actually free first, and the “system of record” for that was, depending on the day, either a NetBox instance nobody had touched since the person who set it up left, or a Google Sheet that three people had “the current version” of. So I did what everyone does when they don’t trust the doc: I started SSHing into random addresses in the range, one at a time, waiting to see who picked up. Got a response, that one’s taken. Connection refused, maybe free, maybe just firewalled, who actually knows. Twenty minutes of digital door-knocking just to provision three boxes that, in a sane world, should have taken thirty seconds.</p><p>That specific flavor of task, the one that requires real, sustained effort but that nobody actually owns, nobody gets credit for, and everybody silently resents, is one I think every infra person has a version of. Maybe yours is your boss asking, out of nowhere, for “a quick report of all the assets we have in the company,” and you realize there is no button for that, there’s just you, three tools, and an afternoon. Maybe it’s opening NetBox to update one VM’s metadata and getting pulled into a small, personal blackhole, because sitting right next to the box you meant to edit are four other entries for VMs that got decommissioned eight months ago and nobody deleted the record. I have something close to OCD about this specific thing, and I mean that mostly seriously, stale entries sitting next to real ones make my skin crawl in a way that’s probably not entirely rational, but also, if a source of truth has ghosts living in it, is it actually a source of truth, or just a haunted spreadsheet with extra steps?</p><p>I’m not telling you this because it’s a dramatic story. None of these are. That’s exactly why they never get fixed, they’re all just annoying enough to eat an afternoon and never quite annoying enough to justify stopping and building something. Until, apparently, one of them was.</p><h3>The spreadsheet was already lying, we just hadn’t caught it yet</h3><p>Here’s the thing about that IP hunt that bugged me for days afterward, not the twenty minutes it cost, but <em>why</em> it cost twenty minutes. We had monitoring. We had Grafana dashboards you could get lost in for an afternoon. We had, God help us, a spreadsheet, tab-separated by cluster, color-coded, someone’s genuine labor of love at some point in the past, plus a NetBox instance that was one part accurate and two parts graveyard. What we didn’t have was one boring, ground-truth answer to “what is actually running on this network, right now, according to the machines themselves.”</p><p>Every source we had was either <em>declared</em> (the spreadsheet, NetBox, someone’s memory) or <em>aggregated after the fact and immediately stale</em> (a monitoring tool that only knows about hosts that already have its agent installed, which is a wonderfully circular way to find out about hosts that don’t). Nothing was actually walking every reachable box and asking it, directly, “what are you, and is anyone using you,” no opinions, no cache, no ghost entries from a VM that got torn down in March.</p><p>So I built that thing. I called it <strong>Auto-Doc</strong>, because I have never once in my life come up with a clever name for anything and I’ve made peace with it.</p><h3>What it actually does, and why the boring parts are the point</h3><p>Auto-Doc is an Ansible playbook. You give it subnets. It scans them, finds every machine that answers, SSHes in with nothing but raw shell commands, cat, grep, df, lsblk, and writes out flat JSON files describing each host&#39;s OS, CPU, memory, storage, network, installed tools with exact versions, and running Docker containers. One command. No inventory file to hand-maintain. No agent to install anywhere, ever.</p><pre>ansible-playbook main.yaml</pre><p>That’s genuinely it. No -i flag. Subnets live in a subnets var at the top of the file, and the very first thing that happens is discovery: scan, find what&#39;s alive, resolve its real identity, then immediately document it, all in the same run.</p><p>We’ve named basically every “as Code” pattern that matters by now. Infrastructure as Code. Configuration as Code. Policy as Code. Pipeline as Code. We turned the entire discipline into a family of acronyms so we’d stop treating each of those things as some special, hand-maintained artifact and start treating them like source, versioned, reviewed, diffable, boring in the best way. And then somehow the one artifact that describes what’s <em>actually running</em>, the thing every incident retro eventually needs, never got the same treatment. It stayed a wiki page. A spreadsheet. Somebody’s memory. The lost XaaC nobody named: <strong>Documentation as Code</strong>, DaaC, if we’re going to commit to the bit. Not documentation generated once and left to rot, documentation that’s re-derived from the machines themselves, every run, committed, diffed, trusted the same way you’d trust a Terraform plan.</p><p>That’s genuinely the whole design philosophy underneath Auto-Doc, once I actually put a name to it. And it turns out that once you actually commit to that philosophy, “just SSH in and read some files” stops being simple almost immediately. Every single component, IP resolution, storage, tools, all of it, has a naive version that breaks on real infrastructure within about a day, and a not-naive version that has to actually earn the right to call itself DaaC. What follows is basically a tour of those fights, one component at a time.</p><h3>Fight one: which IP is actually yours?</h3><p>The naive version of subnet discovery is: ping-sweep, SSH in, ask for the hostname, done. That works until a machine answers on more than one IP, which happens constantly the moment you have anything resembling a floating IP, a secondary NIC, a management interface alongside a service interface. Which IP is the “real” one? The naive answer picks whichever one happened to respond first, which is basically a coin flip dressed up as a decision, and a coin flip is exactly the kind of thing you do not want silently baked into a document people are going to trust.</p><p>So the actual logic goes deeper than that, in three deliberate layers. For every hostname discovered on more than one candidate IP, it checks the box’s own netplan config first, actually reads /etc/netplan/*.yaml on the target and looks for a static IP assignment matching one of the candidates. That&#39;s the strongest possible signal, the box itself has a config file declaring &quot;this is my address.&quot; If exactly one candidate matches, that&#39;s the answer, high confidence, done. If netplan doesn&#39;t resolve it cleanly, either there&#39;s no netplan config, or more than one candidate matches it, it falls back to asking the box which IP it would use to reach the outside world, ip route get 1.1.1.1, and checks if that source address matches one of the candidates. That&#39;s a weaker signal than a declared static config, but it&#39;s still the kernel&#39;s own routing table telling you something real about which interface it actually considers primary. And if <em>that</em> doesn&#39;t resolve it either, it falls back to just picking the numerically lowest candidate IP as a last resort, and, this is the part I actually care about most, it explicitly labels that result as a guess and logs a warning naming the exact host and every IP it saw. Nothing gets silently decided. If the tool had to guess, you know it guessed, and you know exactly what it guessed between.</p><p>Why go to that trouble instead of just always trusting ip route? Because on a box with policy routing, VPN interfaces, or a management network that doesn&#39;t carry default-route traffic, the &quot;IP the kernel would use to reach the internet&quot; and &quot;the IP everyone actually SSHes to and calls this machine by&quot; are sometimes two completely different addresses. Netplan&#39;s static declaration is closer to human intent. The route table is closer to kernel behavior. They usually agree. When they don&#39;t, that disagreement is itself useful information, and burying it behind a silent pick would be exactly the kind of quiet, confident wrongness that got me into this mess in the first place with that spreadsheet.</p><h3>Fight two: storage, or, why df and lsblk both lie a little</h3><p>If you’ve ever tried to write something that reports “what disks does this machine have” in a way that’s actually true across bare metal, VMs, LVM setups, and network mounts all at once, you already know this is a nightmare with about six different flavors of nightmare hiding inside it. This is the densest file in the whole project, and every line in it exists because some earlier, simpler version of it produced a wrong or misleading answer on a real machine.</p><p>Start with the source. /proc/mounts is the ground truth for &quot;what&#39;s actually mounted right now,&quot; but it&#39;s noisy. On any Kubernetes node, every single pod&#39;s emptyDir, secret, and configMap volume shows up in there too, which means a naive scan of a K8s worker returns dozens of irrelevant entries under /var/lib/kubelet/pods for things that aren&#39;t storage in any meaningful sense, they&#39;re ephemeral pod plumbing. So that path gets explicitly excluded, along with /dev/loop* devices, which are almost always squashfs mounts from snap packages, not real storage anyone cares about documenting.</p><p>Then there’s the LVM problem. When a filesystem sits on a logical volume, the device name you get back is something like /dev/mapper/ubuntu--vg-ubuntu--lv, which tells you precisely nothing about the physical disk underneath it. So the script walks /sys/block/&lt;device&gt;/slaves/, the kernel&#39;s own record of which raw block devices back a given logical device, and resolves the mapper name down to the actual disk. Without that step, every LVM-backed host in the fleet would report storage as living on a device that doesn&#39;t correspond to anything you could point to in a datacenter.</p><p>Vendor, model, and transport type all cascade through the same pattern, three separate fallback chains, because no single source reliably has all of it. lsblk gets asked first, since it&#39;s usually right and it&#39;s cheap. When it comes back empty, which happens more often than you&#39;d hope, especially on virtio devices, the script reads straight from /sys/block/*/device/vendor and /sys/block/*/device/model instead, the same files lsblk itself would have read, just accessed directly. And when even that&#39;s empty, it falls back to inference from the device name itself: a scsi_device directory under sysfs means sata or scsi, an nvme*-prefixed name means nvme, a vda*-prefixed name means virtio. None of those individually is bulletproof. Together, stacked in that order, they cover essentially every disk you&#39;ll actually meet in the wild.</p><p>And then two special cases that exist purely because I got burned by them specifically: anything with rbd in its source path gets explicitly labeled Ceph, RADOS Block Device, transport network/rbd, because Ceph&#39;s naming otherwise sails straight through every heuristic above without matching any of them. And anything mounted with an nfs, ceph, or cifs filesystem type gets bucketed generically as network_mount, vendor network_vendor, model remote_share, because a network share genuinely doesn&#39;t have a vendor or model in the way a physical disk does, and reporting unknown for something that&#39;s <em>supposed</em> to be unknown, by nature, felt like the more honest answer than pretending otherwise.</p><h3>Fight three: sixteen tools, sixteen different opinions about what --version means</h3><p>This is the fight that’s the least glamorous and probably the most tedious to have actually had. Every one of the roughly sixteen tools Auto-Doc knows how to check for, Docker, containerd, nginx, Redis, Teleport, Zabbix Agent 2, k3s, kubelet, and so on, formats its own version output slightly differently, and “slightly differently” is doing a lot of work in that sentence.</p><p>Teleport prints its version with a leading v that has to get stripped. k3s prints a v prefix <em>and</em> a trailing +-something build suffix, both of which need stripping before you get a clean semantic version. Zabbix Agent 2&#39;s version string is buried inside parentheses in the middle of a longer line. Each of these got its own small, specific awk/sed extraction rule, because there was no shortcut, no --version --json flag any of these tools consistently support. This is just what happens when you commit to reporting real, exact, comparable version numbers instead of &quot;yes, it&#39;s installed&quot; as a boolean.</p><p>The naming mismatches were their own small hell. Zabbix Agent 2’s binary is zabbix_agent2, underscore, but its systemd service is registered as zabbix-agent2, hyphen. A naive systemctl is-active zabbix_agent2 silently reports &quot;inactive&quot; forever on a host where it&#39;s actually running perfectly fine, because you asked about a service name that doesn&#39;t exist. The check explicitly special-cases this one binary-to-service-name translation, because I hit it in exactly one production host and it was enough to make me paranoid about every other tool on the list too.</p><p>And figuring out <em>how</em> something got installed, apt-managed versus a standalone binary someone dropped in by hand, turned out to have a cleaner answer than I expected: ask dpkg whether it recognizes the file at all, dpkg -S &lt;path&gt;. If dpkg claims ownership of that exact path, it&#39;s apt-managed. If dpkg has never heard of it, it&#39;s standalone. No need to know in advance how each tool is typically installed across sixteen different tools and however many Linux distributions, dpkg already keeps that ledger, you just have to ask it the right question.</p><h3>Fight four: the IP inventory doesn’t assume you only have one subnet</h3><p>I described the IP inventory’s shape as an honest tradeoff before, and it is one, it’s a pivoted table, wide rows keyed by host octet, not a flat list, which does mean anything downstream that expects flat JSON has to reshape it first. But I undersold something about it while I was busy being self-critical: the pivot isn’t hardcoded to a single subnet. It derives its columns dynamically, at run time, from whatever unique subnets actually show up in network.json. Scan one subnet, you get one subnet_&lt;segment&gt;_ip / subnet_&lt;segment&gt;_target_name / subnet_&lt;segment&gt;_target_group triplet of columns. Scan five, you get five triplets, automatically, with zero configuration telling it how many to expect. The jq that builds it reduces over whatever subnet keys it actually finds and generates the column structure from that reduction, rather than a person having to declare, somewhere, &quot;this fleet has N subnets, expect N sets of columns.&quot; It grows with your fleet without you touching it.</p><h3>Fight five: not letting one bad host ruin the whole run</h3><p>This one’s less a clever trick and more a decision I almost got wrong the first time. The obvious way to write a fleet-wide documentation playbook is to just let Ansible do what it does by default: if a host is unreachable or a task fails on it, that host drops out, sometimes loudly, sometimes in a way that eats the rest of the run’s attention. Across forty, fifty, a hundred-plus hosts, on any given run there is <em>always</em> one box that’s mid-reboot, or firewalled differently than the rest, or just having a bad day.</p><p>So the documentation play runs with ignore_unreachable: true at the play level and ignore_errors: true wrapped around the whole block of component tasks. One flaky host gets skipped, quietly, and the other ninety-nine still get fully documented in the same run. And the SSH timeout settings are tuned specifically for this workflow, not a generic default: ConnectTimeout=120, generous, because you&#39;ve likely just discovered this host seconds ago in the same run and its SSH banner might be slow to answer, but ConnectionAttempts=1, because retrying a host that&#39;s genuinely down just burns time you&#39;d rather spend documenting the hosts that are actually up.</p><h3>Fight six: discovery that doesn’t require you to have installed anything first</h3><p>The scan itself tries nmap first, because it&#39;s fast and it&#39;s good at this exact job. But it doesn&#39;t hard-require it. If nmap isn&#39;t on the control node, discovery falls back to a pure Bash port-scan using /dev/tcp, Bash&#39;s built-in ability to open a raw TCP connection without any external tool at all, with a manually implemented concurrency cap using job control, jobs -r | wc -l, so it doesn&#39;t try to open two hundred and fifty simultaneous connections and fall over. It&#39;s slower than nmap. It also means the very first time you ever run this against a fresh control node, before you&#39;ve apt-installed a single thing, it still works.</p><p>And there’s a small side effect of the discovery step I didn’t originally think of as a feature, but I’ve come to appreciate as one: it writes hosts.yaml, a genuinely valid, grouped Ansible inventory file, as a record of what it found, even though the live run never reads that file back in, it works entirely from in-memory add_host calls instead. You get a real, usable static inventory as a byproduct of a run that technically didn&#39;t need one, in case you want to point some other, more targeted playbook at this exact fleet later without re-discovering it from scratch.</p><h3>And the dashboard side doesn’t cache anything either</h3><p>The Grafana half of this is a genuinely tiny Go program, json-exposer, that globs confs/*.json and serves each file over HTTP. The detail worth mentioning: it re-reads every file straight from disk on every single HTTP request. No in-memory cache, no &quot;restart the container to pick up new data.&quot; Run the Ansible playbook again while Grafana&#39;s sitting open in a browser tab, hit refresh, and the new numbers are just there. And its index route, the plain HTML page listing what&#39;s currently being served, is generated from whatever&#39;s actually present in the folder at request time, so adding a ninth component file later means it shows up in that list automatically, no code change required on the exposer side at all.</p><h3>Where this actually sits, next to everything else that sort of does this</h3><p>I’ve said a version of this before in passing, that Auto-Doc is adjacent to a handful of tools rather than competing with any of them, and I want to actually put that in a table instead of just asserting it, because “adjacent” is a claim that should survive being checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTtcqAALCs5ntd3R6v40zg.png" /></figure><p>A few things I want to say plainly about that table instead of letting it sit there implying more than it should.</p><p>Nobody actually owns the full row. That’s the actual point, and it’s the same point from three sections ago, dressed up in table form: phpIPAM knows nothing about what’s running on a host. NetBox knows nothing about what’s actually installed versus what was declared months ago. Wazuh correlates packages against CVEs beautifully but has no concept of IP allocation or physical resource footprint at all. Getting the full picture, “which IP, which specs, which package versions, all keyed to the same hostname, in one place,” otherwise means running four separate stacks and manually joining their outputs yourself. That join is the thing that’s actually missing from the ecosystem, and it’s the thing Auto-Doc does by construction, for free, just by using the same hostname and IP as the join key across every single component file.</p><p>The cost and footprint really aren’t close, either. NetBox is a Django app plus Postgres. phpIPAM is PHP plus MySQL. Wazuh is a manager, an indexer, and a dashboard, three services minimum, plus a persistent agent on every host you want covered, which is a little funny given that keeping agents patched is usually the exact problem you’re trying to get ahead of in the first place. Auto-Doc’s entire footprint is one Ansible run, on-demand or on a cron, static files at the end of it, and, only if you actually want the Grafana view, one ten-megabyte Go container that caches nothing.</p><p>And it’s genuinely more to-the-point because it’s descriptive instead of administrative. NetBox and phpIPAM need someone to declare correct data and then keep it correct by hand, which is a second source of drift sitting right on top of the infrastructure it’s supposedly describing. Auto-Doc just asks the machine what’s true right now. For the tool-version-tracking row specifically, that discovered-truth model is actually a better fit than Wazuh’s CVE-only correlation for one particular kind of problem: version <em>deprecation</em>, not vulnerability. A package can be perfectly CVE-free and still be three major versions past its support window, and that’s a version comparison question, not a vulnerability-feed question. There’s no correlation layer for that in Auto-Doc yet either, to be clear, I’m not going to pretend a shell script grew one overnight. But the discovered, ground-truth data it’s already collecting is the right foundation for building that layer properly, someday, on top of something that’s actually true, instead of on top of a spreadsheet with ghosts in it.</p><h3>Seeing it</h3><p>I built a small Grafana dashboard on top of this, Infinity datasource pointed straight at the JSON files, one tab per component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrGZBTigj2JWfWsHLEsshw.png" /><figcaption><em>(screenshot: Tool inventory — every host, every installed tool, exact version, status, port, all in one table)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZ46LmflDUvYTrkQ0eCb_g.png" /><figcaption><em>(screenshot: IP inventory — the whole subnet, color-coded by which group owns which address, at a glance)</em></figcaption></figure><p>Both of those are running against fake demo data, obviously, forty-five fictional hosts I generated myself, not our real fleet. But the shape of it is exactly what you’d get pointed at your own subnets. docker compose up -d, import the dashboard, and ten minutes after cloning the repo you&#39;re looking at a fully populated view without touching a single real host.</p><h3>Where this actually leaves things</h3><p>The next time I need to spin up a few new VMs, or my boss asks for that “quick asset report,” I want the honest answer to take five seconds and a jq one-liner, not another twenty minutes of digital door-knocking through a subnet, and definitely not another trip through a NetBox instance with ghosts in it. That&#39;s the whole project, really, start to finish. Every fight above exists because the easy version of that fight produced a wrong answer somewhere on a real machine, and a slightly harder version didn&#39;t. We named every other &quot;as Code&quot; that mattered. This one was just waiting for someone to bother.</p><h3>Links</h3><ul><li>Repo: <a href="https://github.com/hatam-abolghasemi/Auto-Doc">github.com/hatam-abolghasemi/Auto-Doc</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b590838115e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why We Monitor Nginx With… Not Nginx: An OpenResty Story]]></title>
            <link>https://medium.com/@hatamabolghasemi/why-we-monitor-nginx-with-not-nginx-an-openresty-story-60e1d2c64527?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/60e1d2c64527</guid>
            <category><![CDATA[openresty]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 15:18:38 GMT</pubDate>
            <atom:updated>2026-08-02T08:31:10.211Z</atom:updated>
            <content:encoded><![CDATA[<p>The whole thing started with one plain, annoying question: how do we get real metrics out of nginx?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqfsCKsC0Xdmb_-Ex2D-sg.png" /><figcaption>sample grafana table visualizing incoming requests in a single scrape</figcaption></figure><p>Nginx sits in front of basically everything we run, terminating connections, proxying requests, doing its job quietly the way nginx always does. And we had almost no idea what it was actually doing at any given moment. Access logs, sure. But access logs are not metrics. You can’t put an access log on a Grafana panel and watch it move. You can grep it after something’s already broken, which is a very different thing from knowing it’s breaking while it happens.</p><h3>Nginx won’t tell you anything</h3><p>Turns out <strong>nginx does not expose real metrics by default.</strong> Stock nginx ships with stub_status, and that&#39;s the entire offering:</p><pre>location = /basic_status {<br>    stub_status;<br>}</pre><p>Four numbers. Active connections, accepts, handled, requests. No per-route latency. No per-status breakdown. Nothing that tells you which endpoint is slow or which one’s throwing 500s at 3am. Want more? Go build a second system that tails and parses the access log, and hope it keeps up with information the proxy already had in memory half a second earlier.</p><h4>And we met OpenResty, by accident, basically</h4><p>We weren’t looking for “an nginx alternative.” We were looking for anything that could get Prometheus metrics out of nginx without reinventing the wheel. That search led us to <a href="https://github.com/knyar/nginx-lua-prometheus">knyar/nginx-lua-prometheus</a>, and that repo is the actual reason OpenResty entered our world at all. The metrics weren’t coming from some log-parsing sidecar. They were coming from Lua embedded directly into the request lifecycle. Which meant the nginx underneath wasn’t stock nginx. It was OpenResty. So the real first question wasn’t “should we build our own exporter.” It was: <strong>can we even run OpenResty instead of our normal nginx?</strong> Same production behavior, same configs, same load, no new class of problem. That doubt was genuine. What settled it:</p><ul><li>Open-source, nothing hidden behind a closed binary</li><li>Tracks upstream nginx releases closely, no frozen fork waiting years on a CVE fix</li><li>A genuinely active community, not a graveyard of five-year-old issues</li><li>Already proven at serious scale at some very large, well-known companies</li></ul><p>Once that doubt cleared, OpenResty stopped being a risky swap and started being a legitimate replacement, and the scope of what we wanted from it kept growing well after that first decision.</p><h4>The first change we made, and why it broke immediately</h4><p>Since the script had no route label at all, that was the first thing I added. Raw path off ngx.var.request_uri, into log_by_lua_block, shipped as a new label. Worked first try. Felt solved for a day. Then I looked at the actual cardinality in Grafana. <strong>“Just add a label” is a sentence that ages badly. </strong>Every unique path was becoming its own permanent time series:</p><pre>/orders/8231<br>/orders/8232<br>/orders/8233<br>...</pre><p>Multiply that by every user ID, every UUID, every hex token some service decided to shove into a URL, and you don’t have a metrics system, You have a cardinality explosion. The route label needed to become “a shape, not an instance.”</p><pre>local function is_param_segment(seg)<br>    if #seg &gt; cfg.sanitize_max_segment_len then<br>        return true<br>    end<br>    if cfg.sanitize_pure_numeric and seg:match(&quot;^%d+$&quot;) then<br>        return true<br>    end<br>    if cfg.sanitize_uuid and seg:match(&quot;^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$&quot;) then<br>        return true<br>    end<br>    if cfg.sanitize_hex and #seg &gt;= 8 and seg:match(&quot;^%x+$&quot;) then<br>        return true<br>    end<br>    if cfg.sanitize_slug_suffix_digit and seg:match(&quot;-%d+$&quot;) then<br>        return true<br>    end<br>    if cfg.sanitize_long_with_digit and #seg &gt; cfg.sanitize_min_len and seg:find(&quot;%d&quot;) then<br>        return true<br>    end<br>    if cfg.sanitize_file_extension and seg:match(&quot;%.%a%a+$&quot;) then<br>        return true<br>    end<br>    return false<br>end</pre><p>Six checks, one job. Too long → data. Pure digits → data. Real UUID shape → data. Hex-looking token → data. Slug with a trailing number → data. File extension → data. Anything else, it stays. Then the route gets rebuilt, collapsing repeats:</p><pre>local segments = {}<br>for seg in path:gmatch(&quot;[^/]+&quot;) do<br>    if is_param_segment(seg) then<br>        if segments[#segments] ~= &quot;$param&quot; then<br>            table.insert(segments, &quot;$param&quot;)<br>        end<br>    else<br>        table.insert(segments, seg)<br>    end<br>end<br><br>local route = &quot;/&quot; .. table.concat(segments, &quot;/&quot;)</pre><p>/orders/8231/items/9f8a3c2e-... becomes /orders/$param/items/$param. Grouped, meaningful, bounded.</p><h4>Same problem, different costume</h4><p>Client IP as a label: same story, one series per client, forever. So the masking depth depends on scope:</p><pre>local function get_client_subnet(addr)<br>    if not addr then return &quot;unknown&quot; end<br>    local ip = addr:match(&quot;^%s*([^,]+)&quot;):match(&quot;^%s*(.-)%s*$&quot;)<br>    local a, b, c, _ = ip:match(&quot;^(%d+)%.(%d+)%.(%d+)%.(%d+)$&quot;)<br>    if not a then return &quot;unknown&quot; end<br>    a, b, c = tonumber(a), tonumber(b), tonumber(c)<br>    -- RFC1918 / pod CIDRs: keep /24 for granularity<br>    if a == 10 or a == 192 or (a == 172 and b &gt;= 16 and b &lt;= 31) then<br>        return a .. &quot;.&quot; .. b .. &quot;.&quot; .. c .. &quot;.0&quot;<br>    end<br>    -- Public IPs: /16 is enough, avoids high cardinality<br>    return a .. &quot;.&quot; .. b .. &quot;.0.0&quot;<br>end</pre><p>Pod CIDRs keep a /24, pods churn constantly, but some locality still beats none. Public IPs get flattened to a /16. More precision there is just noise dressed up as insight.</p><p>Host label had the same trap. Any internal IP landing in a Host header meant a fresh series per pod, per service. So $host gets classified instead of passed through raw:</p><pre>local function classify_host(h)<br>    if not h then return h end<br>    local hostpart = h:match(&quot;^([^:]+):?%d*$&quot;) or h<br>    if hostpart == &quot;127.0.0.1&quot; or hostpart == &quot;localhost&quot; then<br>        return &quot;localhost&quot;<br>    end<br>    if hostpart:match(&quot;^%d+%.%d+%.%d+%.%d+$&quot;) then<br>        if cfg.cluster_ip_prefix and hostpart:sub(1, #cfg.cluster_ip_prefix) == cfg.cluster_ip_prefix then<br>            return &quot;kubernetes&quot;<br>        end<br>        return &quot;$ip&quot;<br>    end<br>    if hostpart:match(&quot;^[%x:]+$&quot;) and hostpart:find(&quot;:&quot;) then<br>        return &quot;$ip&quot;<br>    end<br>    return h<br>end</pre><p>Real domains pass through untouched. Cluster-internal IPs collapse to &quot;kubernetes&quot;. Anything else IP-shaped collapses to &quot;$ip&quot;. Two buckets instead of one series per pod that ever touched a Host header.</p><p>By the third label, the lesson was obvious: <strong>every label is a decision, not a free feature.</strong> Prometheus multiplies label combinations, it doesn’t add them. Every toggle in the config exists because of this:</p><pre>label_method            = true,<br>label_route             = true,<br>label_status            = true,<br>label_client_subnet     = false,<br>label_host              = true,</pre><h4>Why response time as a gauge, not just as a histogram</h4><p>A histogram doesn’t give you a number. It gives you bucket counts, and histogram_quantile() turns those into an estimate, one that&#39;s only as good as the sample size behind it. And here&#39;s the thing: <strong>not every route carries the same weight. </strong>A route hit hundreds of times a second has plenty of samples, a histogram gives you a real, stable p95. A route hit three times in the last five minutes doesn’t. And in real-world per-container sidecar nginx you don’t receive much traffic on a route and if you do, it’s the minority of them all. And the storage cost of those histogram-based metrics explodes your prometheus database for no good reason.</p><p>That’s exactly what the gauge fixes. No estimation. It reports the actual duration of the <strong><em>last</em></strong> request for that exact label combination. For a quiet route, that’s a far more honest answer than any quantile math on three samples. For a busy route, the gauge is noisier, but that’s fine, the histogram’s already doing the real work there. And still for a noisy route i still suggest gauge because if it’s missed in the first interval, it’d be captured on the next scrape or by other pods on the same interval. hmm? Anyway you can run both, and every route gets the representation it actually has the traffic to support.</p><h4>Gauges don’t know when to shut up</h4><p>Counters are self-cleaning, if nothing happens, they don’t move. Gauges aren’t. Set once and never touched again, a gauge just sits there, reporting a stale value with total confidence forever. And given what we just covered, the quiet routes most likely to go stale are exactly the ones we built the gauge for in the first place.</p><pre>local function reset_expired_metrics(premature)<br>    if premature then return end<br>    local now = ngx.now()<br>    for _, key in ipairs(latency_dict:get_keys(cfg.expiry_scan_limit)) do<br>        local entry = latency_dict:get(key)<br>        if not entry then goto continue end<br><br>        local last_update, metric_type = entry:match(&quot;^([^|]+)|(.+)$&quot;)<br>        last_update = tonumber(last_update)<br><br>        if last_update and now - last_update &gt; cfg.expiry_window then<br>            -- ... rebuild labels from the key, zero the matching gauges, delete the key<br>            latency_dict:delete(key)<br>        end<br>        ::continue::<br>    end<br>    ngx.timer.at(5, reset_expired_metrics)<br>end<br>ngx.timer.at(5, reset_expired_metrics)</pre><p>A shared dict, timestamped per label combo, swept every 5 seconds. Anything silent past the window gets zeroed and dropped. expiry_scan_limit bounds the scan on purpose, unbounded under high cardinality would freeze every worker at once.</p><p>And yes, I found a real bug in my own version of this while writing this up. The expiry marker was only written inside one metric’s if block, so if that one metric was off, the others sharing its scope never expired at all, no matter how stale. Fixed: one marker per scope, written once, regardless of which metrics are enabled:</p><pre>if metric_latency or metric_request_size or metric_response_size then<br>    ngx.shared.custom_metrics:set(&quot;req|&quot; .. table.concat(labels, &quot;|&quot;), ngx.now() .. &quot;|req&quot;)<br>end</pre><p>By this point, the original problem was solved. Nginx went from telling us almost nothing to an OpenResty sidecar exposing method, route, status, latency as both gauge and histogram, request size, response size, connection metrics, all labeled, all bounded, all self-cleaning. That was the whole original ask. What comes next isn’t a continuation. It’s a separate story that happened to reuse the same piece of infrastructure.</p><h3>How we ended up watching outgoing traffic too</h3><p>Everything so far only ever looked at requests coming in. Reverse-proxy territory. But our apps also make calls out, to other services, to third-party APIs, and on that side we had nothing. No logs, no metrics, no visibility. If an app started hammering an external API too hard, or a call started silently timing out, we’d find out the way you always find out about things you don’t monitor: after it’s already caused a problem. So the question this time was fresh: how do we get any visibility into traffic leaving our pods, without asking every team to touch their code?</p><p>That’s what pointed us straight back at the sidecar we already had. Already patched, already trusted, already deployed everywhere. A new piece of infrastructure just for egress would’ve meant a second sidecar, a second image, a second thing to reason about per pod. Reusing what was already there meant no new moving part. Just a second job for something that already existed.</p><h4>The cost of doing this</h4><p>Before extending the sidecar, the obvious question was whether it was even worth it, whether we were about to trade one problem for a heavier one. The resource math settled that fast.</p><p>OpenResty sits at somewhere around 10–20MB of RAM and close to zero CPU under real production load, nothing compared to what the actual apps sitting next to it are using. Metric generation happens in log_by_lua_block, which runs after the response has already been sent, so it never blocks or delays a single request waiting on Lua to finish counting things. And since the sidecar lives in the same pod, the extra network hop for outbound traffic is loopback, not a real hop at all, close enough to free to not show up anywhere in latency numbers.</p><p>There’s one more thing this setup gives us almost for free: it isn’t limited to east-west, in-cluster traffic. Since the forward proxy sits directly in the egress path of the pod itself, it sees north-south traffic too, every call actually leaving Kubernetes toward a third-party API or anything else outside the cluster, not just service-to-service hops that stay inside it. If it left the pod, we see it.</p><h4>Making it cost the app team nothing</h4><p>Whatever we built couldn’t turn into a task for every app team. No code changes, no SDK, no “please wrap your HTTP client.” So the fix had to live entirely in infrastructure the app teams already didn’t have to think about: the sidecar. And the mechanism that makes that possible is old and boring in the best way, HTTP_PROXY/HTTPS_PROXY, environment variables every serious HTTP client already respects natively. Point a proxy at those, and the client routes through it automatically. No code change, no library, no per-language anything.</p><h4>What we are talking about right now is actually called a “Forward Proxy”</h4><p>Stock OpenResty doesn’t support HTTP CONNECT out of the box, which is what tunneling HTTPS through a proxy needs. So the image gets patched at build time. Clone the <a href="https://github.com/openresty/docker-openresty/tree/master">docker-openresty</a> project and build the alpine image like this:</p><pre>docker build \<br>  --build-arg RESTY_VERSION=&quot;1.27.1.2&quot; \<br>  --build-arg RESTY_ADD_PACKAGE_BUILDDEPS=&quot;git patch&quot; \<br>  --build-arg RESTY_EVAL_PRE_CONFIGURE=&quot;cd /tmp &amp;&amp; git clone https://github.com/chobits/ngx_http_proxy_connect_module.git&quot; \<br>  --build-arg RESTY_CONFIG_OPTIONS_MORE=&quot;--add-module=/tmp/ngx_http_proxy_connect_module&quot; \<br>  --build-arg RESTY_EVAL_PRE_MAKE=&quot;cd /tmp/openresty-1.27.1.2 &amp;&amp; patch -d build/nginx-1.27.1 -p1 &lt; /tmp/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite_102101.patch&quot; \<br>  -f alpine/Dockerfile \<br>  -t registry.company.com/devops/docker-openresty/openresty:1.27.1.2-egress-0.1 \<br>  .</pre><p>Clones the module, patches it against the exact nginx core bundled in that release, compiles it in. The patch filename has to match the core version, every bump means re-checking the module’s patch/ directory first, a mismatch just fails silently. Then a second server block, bound only to loopback:</p><pre>server {<br>    set                           $request_mode 1;<br>    listen                        127.0.0.1:3128;<br>    resolver                      10.233.0.3 valid=10s;<br>    resolver_timeout              5s;<br><br>    proxy_connect;<br>    proxy_connect_allow           all;<br>    proxy_connect_connect_timeout 10s;<br>    proxy_connect_read_timeout    10s;<br>    proxy_connect_send_timeout    10s;<br><br>    location / {<br>        proxy_pass                $scheme://$http_host$request_uri;<br>        proxy_set_header          Host $http_host;<br>        proxy_http_version        1.1;<br>        proxy_set_header          Connection &quot;&quot;;<br>        access_log                on;<br>    }<br>}</pre><p>Loopback-only, never reachable from outside the pod. proxy_connect_allow 443 keeps CONNECT restricted to HTTPS on purpose, this isn&#39;t meant to tunnel arbitrary TCP. resolver needs the real CoreDNS ClusterIP, fetched per cluster since it&#39;s not portable:</p><pre>sudo kubectl get svc -n kube-system -l k8s-app=kube-dns -o jsonpath=&#39;{.spec.clusterIP}&#39;</pre><p>And validated before it ever ships:</p><pre>sudo docker run --rm -v $(pwd)/egress.conf:/etc/nginx/conf.d/egress.conf:ro \<br>  registry.company.com/devops/docker-openresty/openresty:1.27.1.2-egress-0.1 \<br>  sh -c &quot;openresty -t&quot;</pre><h4>The entire app-side integration</h4><p>This is the part that made the whole thing viable to roll out broadly. The entire integration on the application container is this:</p><pre>env:<br>  - name: HTTP_PROXY<br>    value: &quot;http://127.0.0.1:3128&quot;<br>  - name: HTTPS_PROXY<br>    value: &quot;http://127.0.0.1:3128&quot;<br>  - name: NO_PROXY<br>    value: &quot;localhost,127.0.0.1,.svc.cluster.local,.company.com&quot;</pre><p>That’s it. NO_PROXY matters just as much, without it, purely internal calls route through the proxy unnecessarily. No SDK, no wrapper, no per-language change. Every outbound call now transparently passes through the sidecar, and the app has no idea it happened.</p><h4>Why HTTPS only gets host:port</h4><p>HTTP gets logged in full, method, host, path, status, timing. HTTPS gets logged only as CONNECT host:port, because TLS stays end-to-end encrypted. Real HTTPS visibility would mean terminating and re-establishing TLS ourselves, running our own MITM, which is a far heavier decision around certificate trust and security surface. Not something I&#39;m introducing as a side effect of a metrics project. Stays out of scope, deliberately.</p><h4><strong>Limitations we accepted going in:</strong></h4><ul><li>Route and method are obsolete here, since they live inside the encrypted tunnel; the rest survive</li><li>resolver hard-depends on the CoreDNS ClusterIP, if it changes, outbound proxying breaks silently until the config&#39;s updated, worth its own health check</li><li>The patch is version-pinned, every bump means re-verifying compatibility before rebuilding</li></ul><h4>Telling incoming and outgoing apart</h4><p>One thing was still missing once both directions flowed through the same pipeline: a clean way to tell which direction a data point represented, without relying on someone remembering which panel means what. One more label: mode, set once per server block.</p><pre>server {<br>  listen 80;<br>  location / {<br>    set $request_mode 0;   # reverse-proxy / incoming<br>    fastcgi_pass  127.0.0.1:9000;<br>    fastcgi_param SCRIPT_FILENAME /var/www/html/index.php;<br>    include       fastcgi_params;<br>  }<br>}<br>server {<br>    listen 127.0.0.1:3128;<br>    location / {<br>        set $request_mode 1;   # forward-proxy / outgoing<br>        proxy_pass http://$http_host$request_uri;<br>        proxy_set_header Host $http_host;<br>    }<br>}</pre><pre>local mode = cfg.label_mode and (ngx.var.request_mode or &quot;0&quot;) or nil<br>local labels = build_labels(method, route, status, client_subnet, host, mode)</pre><p>Decided once at the routing level, read once by Lua, no inference needed. Two values, cardinality cost is basically nothing. One Grafana query now splits traffic by direction, instead of two dashboards or someone’s memory doing that job.</p><h3>Somewhere along the way, this quietly stopped being “a fix for one app”</h3><p>Nobody decided to build a company-wide standard. It started as an answer to one narrow question, for one service. But once the sidecar existed in a toggle-driven form, extending it to the next one was almost trivial: copy the ConfigMap, flip a few toggles, done. Shrinking it for a low-traffic service was the same operation in reverse. So it spread. Not through a mandate, just because it was already the easiest answer every time the same question came up. At this point it sits in front of most of what we run, doing both jobs at once.</p><p>Nobody on the team knew Lua before this. It stayed contained, people extend it by copying a block, not by learning the language. That was never the goal. The goal was making the proxy layer legible without turning everyone into an nginx-internals specialist.</p><p>One side effect I didn’t plan for at all: once the metrics were actually good, the access logs stopped earning their keep. We turned them off. We quietly stopped shipping a stream of raw access logs into Elasticsearch, a stream that had been costing real storage and indexing overhead to answer questions already sitting in Prometheus, queryable, labeled, instant.</p><h3>If you want to see the whole thing</h3><p>I keep a working sample and the full script up rather than just describing it, at <a href="https://github.com/hatam-abolghasemi/The-DevOps-Handbook/tree/main/scripts/openresty-exporter">The-DevOps-Handbook/scripts/openresty-exporter</a>. And a sample Grafana dashboard is maintained at <a href="https://github.com/hatam-abolghasemi/The-DevOps-Handbook/blob/main/grafana-dashboards/kubernetes.json">The-DevOps-Handbook/grafana-dashboards/kubernetes.json</a>. It’ll need some adjusting for your own labels and namespaces, but the queries, the gauge-vs-histogram split, the route breakdowns, the mode split, are the real ones, not simplified stand-ins.</p><h3>Where all of this actually leaves us</h3><ul><li>One question, why doesn’t nginx expose real metrics, not a grand redesign</li><li>Discovered OpenResty existed at all through <a href="https://github.com/knyar/nginx-lua-prometheus">knyar/nginx-lua-prometheus</a>, credit where it’s due</li><li>A route label that didn’t exist in the original script, our first change, and our first lesson in cardinality the hard way</li><li>Every metric and label individually toggleable, by design, from day one</li><li>A route sanitizer doing real, layered classification, not a single regex</li><li>Scope-aware IP masking, a host label collapsed into two bounded buckets</li><li>Response time as both gauge and histogram, because not every route carries the same weight</li><li>Gauge expiry that actually covers every gauge, after fixing a real bug where it silently didn’t</li><li>A separate story about outbound traffic, kept apart on purpose, including a service mesh we chose not to bring in</li><li>A forward proxy on the same sidecar, patched module, outbound visibility for the cost of three env vars</li><li>HTTPS staying properly opaque, on purpose</li><li>One small mode label tying both directions together</li><li>A fix for one app that grew into a standard sidecar in front of most of what we run</li><li>Access logs turned off, and an Elasticsearch bill we don’t pay anymore</li><li>The full script, a working sample, and a real dashboard, kept in the open, not just described</li></ul><p>Nginx used to sit there quietly, doing exactly what it’s told and volunteering nothing else. For us that became the whole problem. So we didn’t replace it. We taught it to talk. One label at a time, one bug at a time, until the black box turned into something that just tells us what it’s doing.</p><p>It’s still nginx under all of it. It just finally learned to talk back.</p><h4>Links</h4><ul><li><a href="https://github.com/knyar/nginx-lua-prometheus">knyar/nginx-lua-prometheus</a> — the repo that got us here in the first place</li><li><a href="https://github.com/chobits/ngx_http_proxy_connect_module">chobits/ngx_http_proxy_connect_module</a> — the patch that gives OpenResty CONNECT support</li><li><a href="https://github.com/hatam-abolghasemi/The-DevOps-Handbook/tree/main/scripts/openresty-exporter">Full Lua exporter + sample config</a></li><li><a href="https://github.com/hatam-abolghasemi/The-DevOps-Handbook/blob/main/grafana-dashboards/kubernetes.json">Sample Grafana dashboard</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60e1d2c64527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Expertise Lattice: Why Business Domains Are the Wrong Axis for Infrastructure Teams]]></title>
            <link>https://medium.com/@hatamabolghasemi/the-expertise-lattice-why-business-domains-are-the-wrong-axis-for-infrastructure-teams-502b8d035e06?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/502b8d035e06</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[infrastructure]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 13:30:49 GMT</pubDate>
            <atom:updated>2026-07-13T10:39:03.619Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“We’re a little on edge on our on-call day. We’re a 13-member DevOps team, and honestly we’re not fully aware of what’s changed on production for each function.”</em></p><p><em>“Each function ends up doing its own version of DevOps. RFCs get proposed, approved, and then… just sit there, because some function doesn’t feel like applying them.”</em></p><p><em>“When a failure in one function’s service spills into another function’s service, can we debug it as well as their own dedicated engineer could? Probably not.”</em></p><p>If you’ve worked on a DevOps or platform team of any real size, at least one of those probably sounds familiar.</p><p>Here’s the thing about being a “DevOps engineer”: it’s a generalist role, by definition. One minute you’re fixing a broken CI/CD pipeline. Next minute, a batch of pods just restarted on production, probably disk pressure. Then your Grafana dashboards are quietly running broken queries, and that needs fixing <em>now</em>. You’re expected to context-switch across a pile of unrelated things without your brain short-circuiting.</p><p>On a small team, you can absorb that. But once your infra has 200+ actively-changing repos in a given week, and it’s genuinely pointless to onboard any one person to all of it, you have to ask a harder question: <strong>are we actually using our people well?</strong> Is there someone who can own a piece of this deeply enough to fix it in under a day, instead of everyone dabbling in everything? Is our MTTR as low as it could be? Are we actually in sync, or just sitting next to each other? That’s the question that led me to a structural idea I’ve been calling the <strong>Expertise Lattice</strong>.</p><p><strong>TLDR</strong>: instead of organizing infra teams around business lines (Checkout Team, Search Team), you organize around <em>technical</em> domains, CI/CD, observability, networking, and so on. Each domain gets a small sub-team, but nobody stays locked into just one. People sit on two or three sub-teams at once, and rotate through others every 6–12 months, so knowledge keeps moving instead of pooling in one head. Everyone gets a real voice <em>in their actual domain of depth</em>, no single “chief owner,” but also no more pretending everyone’s vote should weigh the same regardless of experience. And titles get honest: “Observability Engineer” instead of a catch-all “DevOps Engineer.” The payoff is deep expertise <em>and</em> team-wide resilience, at the same time, which the traditional model just isn’t built to give you.</p><h3>The Core Idea</h3><p>Instead of “Checkout Team” or “Search Team,” you get CI/CD, Observability, Networking, Security, Reliability, each with its own small sub-team. The twist: nobody sits on just one.</p><p>Say I’m on Observability and CI/CD at the same time. My colleague Bob is on CI/CD, Security, and Networking. Carol splits her time across Observability, Security, and Reliability. Draw that out and you don’t get neat little boxes, you get a web of overlapping lines. Every domain gets touched by more than one person. Every person touches more than one domain.</p><p><strong>That overlap is the whole point.</strong> It’s how knowledge actually spreads instead of getting stuck in one person’s head. And it shows up hardest during incidents, instead of one isolated expert getting paged as the sole bottleneck for some product team’s problem, there are multiple familiar faces who can step in, because the sub-teams were deliberately woven together in the first place.</p><p>Here’s roughly what that overlap graph looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*1p5eDn8GdgseqjEHIhWh8A.png" /></figure><p>Then there’s the rotation. Every 6–12 months, I move, first half of the year deep in observability, second half in CI/CD, then networking six months after that, eventually cycling back to observability around the two-year mark. It’s a loop, not a ladder. You’re not “graduating” out of a domain, you’re just coming back to it later with fresh eyes. Nobody’s the single point of failure for a whole domain, ever. A simple rotation flow, for one person, might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJKAKBEitLCISvVE9H_tMg.png" /></figure><p>I’d also cap how many domains someone juggles at once , two or three, max, so you don’t trade away depth for breadth. And titles shift to match: “Observability Engineer,” “CI/CD Engineer,” “Network Engineer.” Titles that actually mean something, which, as a nice side effect, also makes hiring and career conversations a lot less vague.</p><h3>Why Domain-Driven Design Doesn’t Actually Fit Here</h3><p>Here’s the real argument underneath all of this: Domain-Driven Design is genuinely great for how we build software. It’s just the wrong tool for organizing the teams that keep that software <em>running</em>.</p><p>DDD earns its keep at the application layer. Bounded contexts, aligning service boundaries with business capability, that all makes sense when your complexity comes from business logic. Checkout really does have different rules and different reasons to change than Search does. Splitting those into separate services, owned by separate teams? Correct call. The mistake is dragging that same logic one layer down, into infrastructure. It doesn’t hold up, and it’s worth being specific about why.</p><p>When a pod gets OOMKilled, or evicted from ephemeral storage pressure, or starts throwing 502s because an ingress controller misbehaved, <strong>the business domain it happens to belong to is almost entirely irrelevant to fixing it.</strong> The real question lives on a totally different axis: is this a memory-limit problem? A kernel-level cgroup thing? A storage-class misconfiguration? None of that cares whether the workload is Checkout, Search, or Loyalty Points. A DiskPressure eviction on a Search pod and one on a Checkout pod are, from a debugging standpoint, <strong>the exact same problem wearing a different business-logic costume.</strong></p><p>This is where organizing infra around business domains actively works against you. If “Checkout DevOps” and “Search DevOps” are two siloed groups, you get two engineers independently rediscovering the same eviction behavior, maybe landing on two different fixes, and neither one building the kind of deep, repeated-exposure expertise you’d get from seeing that failure across the whole fleet. Multiply that across every failure mode, network partitions, cert expiries, DNS errors, noisy-neighbor CPU throttling, and you’ve got an org re-solving the same fires over and over, once per business domain, instead of just getting good at the failure mode itself.</p><p>There’s a subtler issue too. DDD’s bounded contexts work partly because coupling between business domains is something you <em>can</em> minimize, Checkout doesn’t need to know how Search’s ranking algorithm works, and mostly it doesn’t. But infrastructure has a layer of coupling business boundaries can’t see at all: shared node pools, shared network fabric, a shared control plane. A noisy-neighbor problem on a shared node doesn’t respect anyone’s bounded context. It’ll degrade Checkout and Search at the same time, for the exact same reason, while your business-aligned teams each investigate their own slice separately and arrive at the same root cause late, and twice.</p><p>None of this makes DDD wrong. It’s just answering a different question than the one infra teams need answered. A kernel doesn’t know what quarter it is or which product line it’s serving. The lattice takes DDD’s actual instinct, organize around where the complexity really lives, and just points it at the right axis for this layer: technical domains, not business ones.</p><h3>Why the Overlap Matters</h3><p>The overlapping structure isn’t an org-chart quirk. It’s the mechanism that makes the whole thing resilient. When I’m the only person who understands a system, I’m a liability, even if I’m great at my job. The second I go on vacation, get sick, or leave, that knowledge is gone, or at least badly bottlenecked. This is also exactly what fixes that on-call dread from the quotes up top. Being on-call for a 13-person team where nobody’s fully aware of what changed isn’t a staffing problem you solve by hiring more generalists, <strong>it’s a knowledge-distribution problem.</strong> In a lattice, it structurally can’t happen: if I rotate out of CI/CD, the people I overlapped with already have context. Nobody relearns a system from scratch mid-incident, because there’s always more than one familiar face who can step in. It also solves that cross-function debugging complaint directly, the one about a failure spilling from one function into another, and nobody being quite as sharp on it as the “owning” team’s engineer. Business-line groupings don’t help here, because the failure doesn’t respect business boundaries. It respects technical ones. A lattice organizes around exactly those, so whoever understands networking or observability deeply is already embedded across multiple functions, not walled off in just one.</p><p>There’s a term for the failure mode this fixes: the <strong>“human control plane” problem.</strong> Most mature-looking infra orgs quietly have a bus factor of one somewhere, critical knowledge living in a single head, encoded nowhere else. That person goes on vacation, and the “control plane” for that system effectively vanishes with them. The lattice flips this by design: knowledge about any domain is redundantly held by multiple people, and it’s <em>also</em> written down, in the pipelines, runbooks, and docs the sub-team maintains. Losing one engineer slows you down. It doesn’t derail you.</p><h3>The Objections I Actually Hear</h3><p><strong>“Doesn’t this just create new silos?”</strong> I don’t think so, if anything, the opposite. The traditional model creates silos along <em>business</em> lines: the checkout team only knows checkout infra, full stop. The lattice breaks that on purpose, because everyone cross-fertilizes across technical domains. Sub-teams still need to work closely together, CI/CD with Security, say, but that’s managed through clear interfaces, not ad-hoc favors. Practically: time-box “collaboration sprints” for joint work, then switch back to steady “X-as-a-service” mode once it’s done. Keep lightweight SLOs on each sub-team’s services. And hold a regular sync where you literally look at the overlap graph together, so nobody quietly drifts into a permanent silo without anyone noticing.</p><p><strong>“Won’t rotations kill depth, or blow up in-flight work?”</strong> This is the one I take seriously, it’s a real tradeoff, not a strawman. My answer: give people several months to actually ramp in before rotating them out again. Time the rotation around natural project phases, finish the critical piece, <em>then</em> hand off, don’t rotate mid-crisis. Stick to 6–12 months, not weeks. During the handoff window, the outgoing person overlaps briefly with whoever’s coming in, so context doesn’t just evaporate.</p><p><strong>“Isn’t this just a matrix org, i.e., rota hell?”</strong> Fair, this is the first objection I get, every time. What actually prevents matrix-org chaos is clear team APIs plus a disciplined cadence. Each sub-team has a charter, like a product team would, documented interfaces, on-call windows, SLOs. Product engineers consume that through the contract, so day-to-day work doesn’t grind to a halt just because someone’s rotating this quarter. And this is also where the “shared tool nobody owns” problem actually gets solved instead of relabeled: each domain sub-team owns its own tools outright, writes its own usage rules, and the people voting on changes are the ones <em>currently</em> rotating through that domain, not the whole team by default. Whoever leads a sub-team leads it because they currently have the deepest active context, not because they’ve been at the company the longest. Tenure and leadership stop being the same thing by accident.</p><h3>Getting Started</h3><p>If I were setting this up from scratch:</p><ol><li><strong>Map your domains.</strong> CI/CD, observability, networking, security, whatever applies to your stack.</li><li><strong>Draw the overlap graph.</strong> Even a simple wiki page works. Who’s on which sub-team? Where are the gaps?</li><li><strong>Staff for redundancy.</strong> At least three people per domain, ideally four to six. Below that, you’ve just rebuilt the bus-factor-of-one problem you were trying to escape.</li><li><strong>Define team APIs.</strong> Docs, on-call windows, SLOs — whatever it takes for other teams to consume your domain without tribal knowledge. This is also the moment to fix a GitLab structure that grew around business lines instead of technical ones, a flat-first, domain-prefixed layout makes the team APIs something people actually navigate, not just something written down and never opened.</li><li><strong>Plan rotations on a real cadence.</strong> Quarterly or biannual, tuned to what actually works for your org.</li><li><strong>Hire for passion, not just breadth.</strong> Someone excited to go deep in one area first beats a generalist who’s fine at everything and great at nothing.</li></ol><h3>The Bottom Line</h3><p>The old model, one team owns everything for its product, feels simple. But it quietly punishes depth and rewards fragility. The Expertise Lattice flips that: overlapping specialist teams, deliberate rotation, shared ownership. Expertise actually spreads through the org instead of pooling in one person’s head.</p><p>It’s not free, there’s real coordination overhead, and you have to stay disciplined about team APIs and rotation cadence, or it drifts into chaos. But the payoff is real too.</p><p>It borrows from both SRE culture and Team Topologies, and applies it specifically to how roles, rotations, and titles actually work day to day. Done well, it gets an org out of the single-point-of-failure trap without sacrificing the deep technical craft that makes infrastructure work in the first place. And it answers, directly, every frustration in those quotes I opened with: the on-call dread, the out-of-sync functions, and the tool nobody owns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=502b8d035e06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On The Design of an easy-to-maintain, fast, reliable and clean CI/CD Pipeline]]></title>
            <link>https://medium.com/@hatamabolghasemi/on-the-design-of-an-easy-to-maintain-fast-reliable-and-clean-ci-cd-pipeline-0ad7b26b0b0b?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ad7b26b0b0b</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 08:05:44 GMT</pubDate>
            <atom:updated>2026-07-06T14:28:42.807Z</atom:updated>
            <content:encoded><![CDATA[<p>The core mindset is that a CI/CD pipeline is simply the automated version of a manual build and deploy process. It’s something developers already do, and we as DevOps engineers just polish and automate it. There is no new invention, no new creation, and no new art here. Basically, it’s a glorified shell or bash script that performs all of those manual processes automatically. So whenever we’re talking about CI/CD, we’re actually talking about a fancy bash script with modern tooling around it. That’s the core concept.</p><h3>Definitions</h3><p>The two main stages are <strong>build</strong> and <strong>deploy</strong>. I’ll just briefly review the definition of these two stages and we’ll dive deep into them as we proceed.</p><h4>build</h4><p>The build stage is the process that creates a <strong>ready-to-ship</strong> packaged version of an application from scratch. You have the code, and you have a base environment to handle dependencies (a docker base image or a machine with a shell). All you need to do is make sure that every dependency the app needs to run, whether to respond to incoming requests, consume jobs from a queue, or perform other tasks, is prepared at this stage. These dependencies do not include application secrets or configuration files. An application might not be able to start without its configuration files or secrets, unless some defaults are handled properly, but generally these are not build-time concerns. The ready-to-ship packaged version of the application must be as secure as possible. It’s not necessarily supposed to run completely by itself. Configuration files and secrets exist to complete the application, but they are not required for installing dependencies or even compiling in most cases. Some compiled applications might need certain environment variables during compile time, but the majority do not. Even when they do, those variables can be removed afterward and injected again at runtime. The ship-able artifact must not contain any environment variables, secrets, or configuration files hard-coded. Default configurations are allowed and recommended but sensitive data? nope!</p><h4>ready-to-ship is not ready-to-deploy.</h4><p>It’s also important to understand that “ready-to-ship” is not the same thing as “ready-to-deploy”. A ready-to-ship artifact is simply a portable, packaged version of the application that can be distributed safely across environments. It contains the code and its dependencies, but nothing environment-specific. A ready-to-deploy artifact, on the other hand, would already contain configuration files, secrets, runtime parameters, and environment-specific settings. Not differentiating these two from each other is extremely dangerous because it tightly couples the artifact to a specific environment and risks exposing sensitive information. These two concepts must never be confused. The artifact should remain generic and environment-agnostic, while the environment-specific details should always be injected later during runtime. Keeping this separation allows the same artifact to be deployed to multiple environments, staging, UAT or production, without rebuilding it every time. It also keeps secrets out of build systems, logs, and artifact registries, which significantly improves security and maintainability.</p><p>To wrap up, the build stage is where we run commands like pip install, composer install, npm install, or npm build. This is where we install the application’s dependencies, whether they are language-specific extensions or framework-related packages, and perform any compilation or preparation necessary to make the app ready for something like a docker run command. If designed poorly, this stage can become very time-consuming.</p><h4>deploy</h4><p>The deploy stage is where we update the running application with the new version. Ideally, this should be done using a GitOps approach rather than direct commands like kubectl apply, helm upgrade, docker compose restart, or similar operations. This is also where we inject secrets, environment variables, and configuration files into the application at runtime so that it can run in a healthy state.</p><h4>Error Handling: When to Exit vs. When to Log.</h4><p>Most applications rely on external dependencies such as SQL databases, Redis, or other services to process requests more efficiently. These dependencies must not cause the application itself to fail. Requests may fail partially, but the application should remain healthy without memory leaks or CPU spikes caused by connection errors or issues with those dependencies. Such issues should be handled through proper error logging, nothing more. No log spamming, no exit 1, no abrupt termination. The application must continue running.</p><p>The deploy stage is about updating the running version of the application as smoothly as possible, users should feel no change in behavior, and traffic patterns should never be disrupted.</p><p>Regarding configuration files and secrets, there must be a clear framework and cleanup policy for handling them. If something defines how the application is served, then it is runtime configuration, not something to hard code during build. Even if it defines how the application interacts with external dependencies, it is still runtime configuration, no matter how constant it might seem.</p><p>Secrets are self-describing. They include passwords, usernames, addresses, keys, and credentials that must never be pushed to a Git repository or exposed publicly. These are sensitive pieces of information, and we should not treat them the same way we treat ordinary configuration parameters or environment variables. Secrets are usually stored securely and accessed in controlled ways. The sensitivity of the information they carry is what differentiates them from normal configuration values. However, the similarity is that both secrets and configuration should be handled at runtime, not during build or compile. We must keep the build stage as lightweight and as secure as possible. For example, it’s not ideal to write the configuration of something like an fpm www.conf file during the build stage and then override it again at runtime. These settings vary between environments, and developers should not have to worry about them. Developers should focus on development. It’s the DevOps engineer’s responsibility to understand the application and prepare the environment so the application can run properly.</p><h3><strong>Structure of The Proposed Approach</strong></h3><p>Now that we’ve defined what we mean by CI/CD and its two main stages, we need to talk about the design principles. TL;DR: we create a repository called <strong>cicd</strong> (or whatever name you prefer) and structure it like this:</p><pre>.<br>|__&lt;project-name-1&gt;<br>|  |__ pipeline/<br>|  |  |__ build.yml<br>|  |  |__ deploy.yml<br>|  |  |__ healthcheck-response-time.yml (Optional)<br>|  |  |__ secrets.yml (Optional)<br>|  |__ dockerfiles/<br>|  |  |__ main.dockerfile<br>|  |  |__ test.dockerfile<br>|  |__healthcheck/<br>|     |__response-time.json<br>|     |__response-semantic.json<br>|__&lt;project-name-2&gt;<br>   |__ ...</pre><p>Let’s explain this step by step, why it should be centralized, why it should be grouped like this, and why it matters so much to apply such a structure across the entire company.</p><h4>Why externalized and centralized?</h4><p>The first instinct is usually to keep CI/CD files right next to the application code. But that approach increases human error rate. Anyone who has access to the project repository, not just DevOps or SRE people, could potentially affect production either by mistake. On top of that, it adds unnecessary visual noise for developers. They constantly have to ignore things like docker-compose.yml, Dockerfiles, or CI/CD directories sitting at the root of the project. Yes, placing these files in a hidden directory like .cicd/ at the root of the project might partially solve the visual problem. But it still doesn’t solve the security concerns, the scope of responsibility, or the ease of maintenance.</p><p>Another problem that this design solves is CI/CD pipelines debug. Imagine making a “dirty commit” just to test a pipeline feature that triggers based on a commit message. That commit pollutes the repository history for no good reason. If your CI/CD system is modular and call-able from an external repository, you can modify whatever part you need for debugging without touching the application repository’s commit history. We also need to acknowledge something important: DevOps work is not sprint-friendly. Our tasks are mostly reactive and operational. They are often forced by production incidents or infrastructure changes. This kind of work fits Kanban-style workflows, not strict sprint commitments. We cannot realistically promise that a certain operational improvement will be delivered exactly by next weekend if production incidents suddenly appear. Commit message conventions and clean commit history are primarily concerns for developers. DevOps engineers often need to push debugging commits just to investigate pipelines. And honestly, there is no universally accepted commit message convention for DevOps work. At least, I haven’t found one yet.</p><p>One of the main advantages of this modular but centralized CI/CD approach is visibility. You don’t need to jump across multiple application repositories or open several IDEs just to check how a similar application implements its pipeline. Everything is in one place. Every application’s CI/CD materials live in the same repository. At this point, you might ask: “<em>Okay, Hatam. If we centralize CI/CD, why not avoid duplication entirely? Why not write a single </em><em>build.yml for Python/Django and let all 30 backend microservices use it?</em>” That’s a fair question. Yes, you absolutely can do that. In fact, you could even go further and make the build completely language-agnostic with lots of flags, conditions, and abstractions. But the real headache appears during debugging. When something breaks, you won’t clearly know which steps your specific application actually passes through during the build. You end up with extremely abstract Dockerfiles and scripts that try to support everything, and debugging them becomes painful. Also your mistakes propagate much much easily to many applications pipelines. the amount of ease of management we gain in this case isn’t worth the amount of ease of maintenance we lose.</p><h4>Why grouped like this?</h4><p>This structure, project/environment/component, is not limited to CI/CD either. You should ideally apply it to other infrastructure systems as well, your image registry, your secret management system, your Git platform and other operational tools. When everything follows a similar structure, people quickly become familiar with it. Consistency reduces cognitive load across the organization.</p><p>Another benefit of this explicit structure is safe flexibility. You can modify the CI/CD configuration of one application without worrying that your changes will accidentally affect dozens of other services. You also avoid overly complex scripts full of nested conditions. The same reasoning applies to Kubernetes manifests. Personally, I recommend avoiding Helm unless you truly need it. Most companies only have two or three environments, maybe development, staging, and production. Helm becomes truly useful when you have dozens of environments, which is a rare case. Unnecessary abstraction usually creates more maintenance pain than it solves. We should always prefer ease of maintenance over reducing the number of files. This is not a “duplicate files zoo.” It’s about maintaining flexibility and clarity. If you’ve been in a helm hell, you know what I’m talking about.</p><p>You can configure your GitOps tool (like ArgoCD or something similar) to sync directly with this repository. But I generally don’t recommend it, because this structure is designed around CI/CD concerns, not Kubernetes lifecycle management. For Kubernetes maintenance, it’s better to maintain a separate repository that covers clusters, namespaces, and other infrastructure resources. Many of those resources don’t require CI/CD pipelines at all. This repository should mainly store CI/CD-driven GitOps changes for applications. Temporary operational changes can be applied directly in the GitOps synchronization repository instead.</p><h4>Reasons behind this structure</h4><p>At the root level we define &lt;project&gt; because it’s almost always unique across an organization. Application repositories rarely mix multiple languages or unrelated projects. Even for small applications with a tiny backend and a tiny frontend, the two parts are typically kept in separate repositories. On the other hand, <em>environment</em> is not a good candidate for the root level. Different projects may require different environments. By placing environments inside each project directory, we allow projects to define their own environments instead of forcing a global structure. You might also ask <em>why we don’t we structure pipelines around application components, since different components might require different pipelines</em>? The answer is that when you manage the entire pipeline inside the project’s directory, you can still create different build or deploy scripts if needed. However, most applications’ components differ mainly in how they are deployed, not in how they are built. For example, running an application as an API service versus a queue consumer is usually just a matter of changing the runtime command. Both versions can and mostly should share the same codebase and build process. Finally, we usually try to keep everything as code as much as possible. Tests should be automated whenever possible, and that’s the purpose of the tests/ directory. This is where we can store smoke test definitions or other test artifacts related to the project.</p><h4>Some small best practices behind a pipeline stage design</h4><ol><li>One good instinct to have when designing a fast CI/CD pipeline is to keep stages as parallel as possible. If the output of one command does not necessarily depend on another command, then those steps can, and should, be parallelized. For example, fetching secrets from a secret management tool and updating Kubernetes secret objects is not tied to installing application dependencies. Because of that, the build stage and the secrets stage can run in parallel.</li><li>We should also keep an eye on duplicate commands. If different variants of an application only differ at runtime, or maybe in a single Dockerfile layer, then we shouldn’t separate all of their other shared steps unnecessarily. Their packaged images can also be built and pushed to the image registry simultaneously instead of sequentially.</li><li>Another important aspect is deciding which failures should break the pipeline and which ones should not. For instance, we must never allow a broken build to be pushed to the image registry and still mark the job as successful. Similarly, a syntactically invalid Kubernetes manifest must not pass validation, because that could break the GitOps synchronization repository and eventually the cluster itself.</li><li>Logging is another point that is often overlooked. No matter which stage we are in, we usually don’t want a super-verbose runner logging mechanism. Excessive logs quickly turn into a maintenance problem for the GitLab platform. Log cleanup becomes a large operational burden if every pipeline produces thousands of unnecessary lines. A better approach is to control logging manually. Pipelines should report important events using short and clear messages, while errors should be logged as verbosely as necessary for debugging. In some cases, we might want a specific stage to run in verbose mode for debugging purposes. Instead of relying on the runner’s default verbosity, it’s better to control this directly inside the stage script. For example, introducing a flag like CICD_DEBUG=true could enable verbose logging, while the default value should remain false.</li><li>Finally, we can leverage project-level, group-level, and platform-level environment variables in GitLab to control the behavior of our CI/CD pipelines. Keeping these settings inside GitLab is actually beneficial. They are not secrets, but they allow maintainers to change pipeline behavior when needed without modifying the pipeline code itself. For example, something like PACKAGES_CACHE could be controlled via an environment variable. A project maintainer might occasionally want to disable caching and force dependency renewal on a staging environment. Having such controls available at the platform level makes the pipeline more flexible while keeping the configuration clean. Because of this, we should try to keep project environment variables clean, meaningful, and actually useful, instead of letting them become a random collection of unused settings.</li></ol><h3><strong>Externalized Multi-Stage Builds?</strong></h3><p>Now that we understand the general principles of a CI/CD pipeline, we can move into the details of each stage.</p><p>So, once we’ve reviewed what a build is, we can say it’s the process of creating a ready-to-ship version of an application from scratch. By “from scratch,” we mean using different tools and techniques to transform a source code version of an application into a production-ready artifact. Essentially, we think of an application as code written in a specific language, usually within a specific framework. We don’t consider a mix of unrelated languages and bash scripts an application. An application is typically developed within a single language ecosystem, and that assumption helps us reason about the build process more clearly.</p><p>Given that, we can also assume that every application has some form of package manager responsible for installing, upgrading, or removing dependencies. These packages and frameworks are pre-built components that help developers implement their ideas more efficiently, there’s no need to reinvent everything. For example, when calling a REST API, we don’t implement REST from scratch; we rely on existing packages and learn their APIs to get the job done. This approach is conventional and widely accepted. The key point, however, is that in most cases, almost always, developers don’t modify these dependencies. Instead, they update and fix their own code. Roughly speaking, 9 out of 10 commits are about application code, not dependencies. So, if we want to think scientifically about speeding up builds, we need to identify the slow parts and understand their behavior versus our expectations. After all, one of the main reasons we automated builds and deploys via a concept called CICD in the first place was speed, wasn’t it?</p><p>At the beginning, we can introduce checks to decide how a build should behave. Should dependencies be installed from scratch? Has the language version changed? Has composer.json or requirements.txtbeen updated? Has any package even received a patch update? And how long do these checks take, 1 second, 5 seconds? Compare that with skipping all checks and rebuilding everything just to deploy a small bug fix, 2 minutes, 5 minutes, maybe 15. If you’ve seen long, time-consuming builds in your company, you know exactly what I’m talking about. On paper, implementing these checks sounds great. But in practice, there are subtle design challenges that require careful thinking. Where should these checks happen? In a project file? Git tags? Project-level environment variables? However we implement them, we should always remember why we’re doing this in the first place. Don’t over-engineer what doesn’t need over-engineering. Keep it simple, and implement it as simply as possible.</p><p>But here is the more important shift: instead of relying on implicit, local Docker layer caching, we can make each stage of the build explicit, persistent, and shareable. In other words, we externalize the cache. Traditionally, the docker cache is treated as an implementation detail of the local daemon. It works when it works but in the case of shared and distributed runners it’s hard to utilize, and becomes unpredictable and hard to manage. With modern docker BuildKit, we can persist the cache in a registry and intentionally reuse it between builds and treat them as explicit docker images.</p><p>As of writing this, with around 3–4 years of DevOps experience, I’d structure my application builds using a single Dockerfile with three stages:</p><ol><li><strong>Base Stage</strong>: We decide the language version here. It’s supposed to be empty by default and only dictate the pure base image of the final image but in some cases some applications need some extensions or apt/apk-like dependencies which change rate are much much lower than their packages change rate and this stage is where they belong. This stage starts from a minimal runtime image such as debian-slim or alpine and installs components that rarely change like operating system packages, extensions, certificates, and low-level dependencies. These are the slowest and least frequently changing parts of the build, so they should be optimized for long-term reuse. Ideally in this stage we do whatever that is necessary in a single RUN command instead of many and keep it lightweight.</li><li><strong>Packages Stage</strong>: The second stage builds on top of the base image and copies only dependency-related files (package.json, pnpm-lock.yaml, composer.json, requirements.txt, and similar manifests). This stage installs dependencies and intentionally isolates dependency changes from application code changes. That separation becomes surprisingly valuable during debugging. If a deployment suddenly breaks and dependency manifests have not changed, you immediately reduce the scope of investigation. A dependency-related issue and an application-related issue produce different cache invalidation paths. This stage is also where BuildKit shines. Since dependency installation is often the slowest part of application builds, persisting cache externally means even fresh CI runners can immediately reuse previously built layers without depending on local Docker state.</li><li><strong>Code Stage</strong>: Finally, the code stage copies the source code and performs the final build steps, like next build, go build, asset compilation or packaging. Once dependencies are already cached, this part mostly becomes file copying and computation, which makes it significantly faster. Staging environments should be fast and reliable enough that developers trust them more than their local machines. Staging is closer to production; it is where real validation should happen, not localhost.</li></ol><p>The implementation now becomes much simpler operationally. We basically use a single multi-stage build with registry-backed BuildKit cache. As an example:</p><pre>docker buildx build \<br>  -f all.dockerfile \<br>  --cache-from type=registry,ref=registry.company.com/project/stg/cache:latest \<br>  --cache-to type=registry,ref=registry.company.com/project/stg/cache:$CI_COMMIT_SHA,mode=max \<br>  -t registry.company.com/project/stg/app:$CI_COMMIT_SHA \<br>  -t registry.company.com/project/stg/app:latest \<br>  --push .<br><br># retag to CI_COMMIT_SHA so you have no untagged image, <br># so you implement better cache images cleanup policies<br>regctl image copy registry.company.com/project/stg/cache:latest \<br>  registry.company.com/project/stg/cache:$CI_COMMIT_SHA<br><br># stg refers to staging environment in this example</pre><p>Here, cache is no longer tied to a single runner or machine. It becomes portable and reusable across CI workers, environments, and deployments. This solves a common problem in CI/CD pipelines: <em>ephemeral runners</em>. Whether your build runs on a new VM, a Kubernetes executor, or a completely fresh machine, the build can still reuse dependency and intermediate layers pulled directly from the registry. The result is not just faster builds. It is more predictable behavior, easier debugging, and fewer surprises when moving between environments.</p><p>Finally, for debugging purposes, it is useful to log exactly which CI/CD conditions triggered a pipeline and which cache sources were used. Build systems become dramatically easier to reason about when the execution path is visible instead of implicit. Here is a sample build stage:</p><pre>.build:<br>  stage: build<br>  allow_failure: false<br>  interruptible: true<br>  tags:<br>  - docker<br>  image:<br>    name: registry.company.com/devops/runner-build:1.0.2<br>    pull_policy: if-not-present<br>  before_script:<br>  - |<br>    # 🔧 Initialization...<br>    CYAN=&quot;\033[1;36m&quot;; RESET=&quot;\033[0m&quot;<br>    echo -e &quot;${CYAN}=== Build Info ===${RESET}&quot;<br>    for e in \<br>      &quot;ENV=ENV&quot; \<br>      &quot;NEXUS=NEXUS&quot; \<br>      &quot;PROXY=PROXY&quot;<br>    do<br>      label=&quot;${e%%=*}&quot;<br>      var=&quot;${e#*=}&quot;<br>      if [[ &quot;$label&quot; == &quot;APP_VERSION&quot; ]]; then<br>        value=&quot;$var&quot;<br>      else<br>        value=&quot;${!var}&quot;<br>      fi<br>      [ -n &quot;$value&quot; ] &amp;&amp; printf &quot;%b%s:%b %s\n&quot; &quot;$CYAN&quot; &quot;$label&quot; &quot;$RESET&quot; &quot;$value&quot;<br>    done<br>    git clone @git.company.com/devops/cicd.git&quot;&gt;https://${GIT_AUTH}@git.company.com/devops/cicd.git<br>    echo &quot;✅ CICD repository ready for the job.&quot;<br>    docker login -u ${REGISTRY_USERNAME} -p ${REGISTRY_PASSWORD} ${REPO_URL}<br>    echo &quot;🔐 Docker authentication configured successfully.&quot;  <br>    echo &quot;${REGISTRY_PASSWORD}&quot; | regctl registry login ${REPO_URL} -u &quot;${REGISTRY_USERNAME}&quot; --pass-stdin<br>    echo &quot;🔐 regctl authentication configured successfully.&quot;  <br>    echo &quot;$GIT_AUTH_JSON&quot; | base64 -d &gt; auth.json<br>    echo &quot;🔐 Git authentication is configured successfully.&quot;<br>  script:<br>  - |<br>    # 🏗️ Building App Image...<br>    tar cz \<br>      --exclude=.cicd \<br>      --exclude=.archive \<br>      --exclude=.gitlab \<br>      --exclude=.git \<br>      --exclude=.gitlab-ci.yml \<br>      --exclude=. \<br>      --exclude=.. \<br>      --exclude=*.tgz \<br>      -f v${CI_PIPELINE_IID}.tgz `ls -a`<br>    echo &quot;🗜️ Archive created: v${CI_PIPELINE_IID}.tgz&quot;<br>    docker buildx build \<br>      --build-arg ENV=${ENV} \<br>      -f cicd/project/dockerfiles/main.dockerfile \<br>      --cache-from type=registry,ref=registry.company.com/project/stg/cache:latest \<br>      --cache-to type=registry,ref=registry.company.com/project/stg/cache:$CI_COMMIT_SHA,mode=max \<br>      -t registry.company.com/project/stg/app:$CI_COMMIT_SHA \<br>      -t registry.company.com/project/stg/app:latest \<br>      --push .<br>    regctl image copy registry.company.com/project/stg/cache:latest \<br>      registry.company.com/project/stg/cache:$CI_COMMIT_SHA<br>    echo &quot;✅ Building and pushing app image is completed.&quot;<br>    echo &quot;registry.company.com/project/stg/app:$CI_COMMIT_SHA&quot;<br>  after_script:<br>  - rm auth.json<br>build-stg:<br>  extends: .build<br>  variables:<br>    ENV: stg<br>    GIT_DEPTH: 2<br>    GIT_STRATEGY: fetch<br>    GIT_FETCH_EXTRA_FLAGS: &quot;--no-tags&quot;<br>    GIT_SUBMODULE_STRATEGY: none<br>  rules:<br>  - if: &#39;$CI_COMMIT_BRANCH == &quot;develop&quot;&#39;<br>  needs: []</pre><h3>Hydrated Manifests Pattern Deploy?</h3><p>We have the image, the environment is detected, and now we need to ship this ready-to-ship application onto the platform. Let’s keep it simple and clearly define its scope of work. This stage is only responsible for getting a fresh pull from the in-sync repository with ArgoCD, updating the commit SHA of the project’s images, and pushing it right away. That’s it. Changing replica counts of a deployment, updating a ConfigMap, and none of these should be handled at this stage, or in any CI/CD pipeline. Ensuring that the live version of the manifests is healthy is not the responsibility of a project’s CD. It is entirely a manual responsibility of SRE and DevOps teams within a company and has nothing to do with a trigger fired by a developer.</p><p>Another reason this CI/CD repository, or at least this deploy stage, must be modular and included from an external repository is to keep the risk of affecting the platform as far as possible from human error, especially considering the number of contributors in a project. The credentials for pushing to the Kubernetes repository must also be stored out of the project. Security at this stage is extremely important, so the possibility of human error is minimized to near zero.</p><p>The whole responsibility is this to only update the app image and not affecting other objects but to keep the promise of minimized human error we can use the hydrated manifests pattern and define a stable, helm templated version of application at this stage and separate the matter of debug from maintenance. Like this version will override the live (hydrated) version of our manifests. the hydrated version is only in-sync with the argocd and both are version-controlled. by using helm template to define the kubernetes objects of our apps we are minimizing the drift between different environments and are dictating that their differences is only about their values.yaml files. In case we need to debug and test new features on these objects we can use the hydrated repo and after making sure that our changes are needed we can apply to the helm templates so it persists during different pipeline triggers.</p><p>The decision to keep the updated version running, or to detect a failure and trigger a rollback, should be entirely within the scope of another stage, and we’re going to cover that next.</p><h3><strong>Rollback Stage: Healthy Release, Unhealthy Release</strong></h3><p>We can have a small <em>rollback</em> stage that depends on the <em>deploy</em> stage. it’s better to keep it fully manual for prod and only be triggered if the deploy has been finished successfully. In the rollback stage, the only thing that happens is that it uses the image name and tag that was replaced with the new image in the deploy stage to replace with the latest up and running image and then re-commits and push. That’s it.</p><p>All rollback stages, whether manually triggered or initiated by health checks, must be fast. Since the decision is made after deployment, based on either explicit intent or validated health-checks, the rollback should be executed with minimal delay. All desired rollback pods should become available as quickly as possible, and traffic must be shifted entirely to these pods while being drained from those running the unstable version of the application.</p><h4><strong>Health Check Stages</strong></h4><p>Defining whether a release is healthy or unhealthy is highly context-dependent. There’s no single formula that universally determines if a release should be rolled back to the latest stable state or promoted as the new stable version. However, we can introduce a few simple check templates to evaluate different aspects of a release’s health:</p><p><strong>Response Time Check: </strong>Response time is one useful indicator. For example, we can define a JSON configuration with blocks dedicated to route, method pairs, along with their expected inputs, outputs, and evaluation criteria:</p><pre>[<br>  {<br>    &quot;route&quot;: &quot;&quot;,<br>    &quot;method&quot;: &quot;&quot;,<br>    &quot;token-mode&quot;: &quot;&quot;,<br>    &quot;data&quot;: &quot;&quot;,<br>    &quot;content-type&quot;: &quot;&quot;,<br>    &quot;threshold-good&quot;: &quot;&quot;,<br>    &quot;threshold-slow&quot;: &quot;&quot;,<br>    &quot;weight&quot;: &quot;&quot;<br>  }<br>]</pre><p>Based on this configuration, the stage script can read the JSON file and generate customized curl (or similar) requests to measure response times for critical routes. Each entry defines The route and HTTP method, Optional request data, A token-mode (e.g., user token, admin token, or none), Two thresholds (<strong>Good</strong>: response time below this is considered acceptable, <strong>Slow</strong>: response time between good and slow is considered degraded, Above slow is considered unacceptable), Scoring can be defined (Good → +1, Slow → 0, Unacceptable → -1) and at last The weight parameter acts as a multiplier to reflect the importance of each route. By default, it can be 1. The final score (sum or average) determines the overall health of the release from a response-time perspective. Here is a sample healthcheck-response-time stage:</p><pre>.healthcheck-response-time:<br>  stage: healthcheck-response-time<br>  allow_failure: true<br>  tags:<br>  - docker<br>  image:<br>    name: git.company.com/devops/runner-healthcheck:1.0.2<br>  before_script:<br>  - |<br>    # 🔧 Initialization...<br>    git clone @git.company.com/devops/cicd.git&quot;&gt;https://${GIT_AUTH}@git.company.com/devops/cicd.git<br>    echo &quot;✅ CICD repository ready for the job.&quot;<br>    export ADMIN_TOKEN=$(echo -n &quot;$ADMIN_TOKEN_64&quot; | base64 -d)<br>    export NORMAL_TOKEN=$(echo -n &quot;$NORMAL_TOKEN_64&quot; | base64 -d)<br>    echo &quot;✅ bearer tokens are fetched successfully.&quot;<br>  - |<br>    # 🕵️ Pre-Flight Check<br>    echo &quot;Checking environment...&quot;<br>    echo &quot;Looking for JSON_FILE: $JSON_FILE&quot;<br>    if [ ! -f &quot;$JSON_FILE&quot; ]; then<br>      echo &quot;❌ ERROR: JSON file not found at $JSON_FILE&quot;<br>      ls -R .<br>      exit 1<br>    fi<br>    if ! jq -e . &quot;$JSON_FILE&quot; &gt;/dev/null 2&gt;&amp;1; then<br>      echo &quot;❌ ERROR: $JSON_FILE is not valid JSON or is empty.&quot;<br>      exit 1<br>    fi<br>    echo &quot;⏳ Waiting for $ENDPOINT to be reachable...&quot;<br>    MAX_RETRIES=10<br>    RETRY_COUNT=0<br>    HEALTH_CHECK_URL=&quot;$ENDPOINT/actuator/health-check&quot;<br>    until curl -sSf -m 2 &quot;$HEALTH_CHECK_URL&quot; &gt; /dev/null 2&gt;&amp;1; do<br>        RETRY_COUNT=$((RETRY_COUNT + 1))<br>        if [ &quot;$RETRY_COUNT&quot; -ge &quot;$MAX_RETRIES&quot; ]; then<br>            echo -e &quot;\n❌ ERROR: Endpoint [$HEALTH_CHECK_URL] is NOT reachable after $MAX_RETRIES attempts.&quot;<br>            echo &quot;Check if the deployment finished correctly or if the service is crashing.&quot;<br>            exit 1<br>        fi<br>        printf &quot;  (Attempt $RETRY_COUNT/$MAX_RETRIES): Pending... \r&quot;<br>        sleep 1<br>    done<br>    echo &quot;🚀 API is UP. Starting Probes...&quot;<br>  script:<br>  - |<br>    # 🩺 PROBE: RESPONSE TIME HEALTH CHECK STAGE...<br>    echo &quot;---------------------------------------------------------&quot;<br>    echo &quot;Target: $ENDPOINT&quot;<br>    echo &quot;Rounds: $ITERATIONS | Timeout: ${REQUEST_TIMEOUT}s | Wait: ${ITERATION_SLEEP}s&quot;<br>    echo &quot;---------------------------------------------------------&quot;<br>    if ! command -v jq &amp;&gt; /dev/null; then echo &quot;Error: &#39;jq&#39; is required.&quot;; exit 1; fi<br>    RAW_WEIGHT_SUM=$(jq &#39;[.[].weight // 1 | tonumber] | add&#39; &quot;$JSON_FILE&quot;)<br>    MAX_POSSIBLE_SCORE=$(( RAW_WEIGHT_SUM * ITERATIONS ))<br>    for ((i=1; i&lt;=ITERATIONS; i++)); do<br>        echo &quot;▶ ROUND $i OF $ITERATIONS...&quot;<br>        while read -r item; do<br>            ROUTE=$(echo &quot;$item&quot; | jq -r &#39;.route&#39;)<br>            METHOD=$(echo &quot;$item&quot; | jq -r &#39;.method&#39;)<br>            T_MODE=$(echo &quot;$item&quot; | jq -r &#39;.&quot;token-mode&quot;&#39;)<br>            DATA=$(echo &quot;$item&quot; | jq -r &#39;.data&#39;)<br>            CONTENT_TYPE=$(echo &quot;$item&quot; | jq -r &#39;.&quot;content-type&quot;&#39;)<br>            T_GOOD=$(echo &quot;$item&quot; | jq -r &#39;.&quot;threshold-good&quot;&#39;)<br>            T_SLOW=$(echo &quot;$item&quot; | jq -r &#39;.&quot;threshold-slow&quot;&#39;)<br>            WEIGHT=$(echo &quot;$item&quot; | jq -r &#39;.weight // 1&#39;)<br>            AUTH_HEADER=&quot;Authorization: None&quot;<br>            [[ &quot;$T_MODE&quot; == &quot;admin&quot; ]] &amp;&amp; AUTH_HEADER=&quot;Authorization: $ADMIN_TOKEN&quot;<br>            [[ &quot;$T_MODE&quot; == &quot;user&quot; ]] &amp;&amp; AUTH_HEADER=&quot;Authorization: $NORMAL_TOKEN&quot;<br>            TIME_FLOAT=$(curl -s -o /dev/null -m &quot;$REQUEST_TIMEOUT&quot; -w &quot;%{time_total}&quot; \<br>                -X &quot;$METHOD&quot; -H &quot;$AUTH_HEADER&quot; -H &quot;Content-Type: $CONTENT_TYPE&quot; \<br>                -d &quot;$DATA&quot; &quot;$ENDPOINT$ROUTE&quot;)<br>            if (( $(echo &quot;$TIME_FLOAT == 0&quot; | bc -l) )); then<br>                MS=5001; LABEL=&quot;🔴 TIMEOUT&quot;<br>            else<br>                MS=$(echo &quot;$TIME_FLOAT * 1000 / 1&quot; | bc)<br>                if [ &quot;$MS&quot; -le &quot;$T_GOOD&quot; ]; then<br>                    SCORE=1; LABEL=&quot;🟢 GOOD&quot;<br>                elif [ &quot;$MS&quot; -le &quot;$T_SLOW&quot; ]; then<br>                    SCORE=0; LABEL=&quot;🟡 SLOW&quot;<br>                else<br>                    SCORE=-1; LABEL=&quot;🔴 UNACCEPTABLE&quot;<br>                fi<br>            fi<br>            WEIGHTED_SCORE=$((SCORE * WEIGHT))<br>            TOTAL_SCORE=$((TOTAL_SCORE + WEIGHTED_SCORE))<br>            printf &quot;  %-35s | %-6s | %-14s | Score: %d\n&quot; &quot;$ROUTE&quot; &quot;${MS}ms&quot; &quot;$LABEL&quot; &quot;$WEIGHTED_SCORE&quot;<br>        done &lt; &lt;(jq -c &#39;.[]&#39; &quot;$JSON_FILE&quot;)<br>        if [ &quot;$i&quot; -lt &quot;$ITERATIONS&quot; ]; then<br>            echo &quot;   (Waiting ${ITERATION_SLEEP}s for next iteration...)&quot;<br>            sleep &quot;$ITERATION_SLEEP&quot;<br>        fi<br>    done<br>    ACHIEVED_HEALTH_SCORE_RATE=$(echo &quot;scale=2; ($TOTAL_SCORE / $MAX_POSSIBLE_SCORE) * 100&quot; | bc)<br>    echo &quot;---------------------------------------------------------&quot;<br>    echo &quot;📊 STAGE SUMMARY: RESPONSE TIME PROBE&quot;<br>    echo &quot;---------------------------------------------------------&quot;<br>    echo &quot;Raw Score: $TOTAL_SCORE / $MAX_POSSIBLE_SCORE&quot;<br>    echo &quot;Achieved Rate: $ACHIEVED_HEALTH_SCORE_RATE%&quot;<br>    echo &quot;Minimum Required Rate:   $MINIMUM_HEALTH_SCORE_RATE%&quot;<br>    if (( $(echo &quot;$ACHIEVED_HEALTH_SCORE_RATE &gt;= $MINIMUM_HEALTH_SCORE_RATE&quot; | bc -l) )); then<br>        echo &quot;STATUS: [PASS] - Response Time Check Results: RELEASE HEALTHY&quot;<br>        exit 0<br>    else<br>        echo &quot;STATUS: [FAIL] - Response Time Check Results: RELEASE UNHEALTHY&quot;<br>        exit 1<br>    fi<br>healthcheck-response-time-stg:<br>  extends: .healthcheck-response-time<br>  variables:<br>    ENV: stg<br>    ENDPOINT: &quot;https://project-name.company.com&quot;<br>    ITERATIONS: 1<br>    ITERATION_SLEEP: 1<br>    REQUEST_TIMEOUT: 3<br>    JSON_FILE: &quot;cicd/project-name/healthcheck/response-time.json&quot;<br>    ADMIN_TOKEN_64: &quot;$STG_ADMIN_TOKEN&quot;<br>    NORMAL_TOKEN_64: &quot;$STG_NORMAL_TOKEN&quot;<br>    TOTAL_SCORE: 0<br>    MINIMUM_HEALTH_SCORE_RATE: 80<br>  rules:<br>  - if: &#39;$CI_COMMIT_BRANCH == &quot;develop&quot;&#39;<br>  needs:<br>  - job: &quot;healthcheck-response-semantic-stg&quot;<br>    optional: false</pre><p><strong>Response Semantic Check</strong>: Another important aspect is validating the correctness of responses. This follows a similar structure but focuses on semantics:</p><pre>[<br>  {<br>    &quot;route&quot;: &quot;&quot;,<br>    &quot;method&quot;: &quot;&quot;,<br>    &quot;token-mode&quot;: &quot;&quot;,<br>    &quot;data&quot;: &quot;&quot;,<br>    &quot;content-type&quot;: &quot;&quot;,<br>    &quot;desired-status-code&quot;: &quot;&quot;,<br>    &quot;desired-keyphrases&quot;: &quot;&quot;,<br>    &quot;weight&quot;: &quot;&quot;<br>  }<br>]</pre><p>Here, we define Expected HTTP status code (e.g., 200, 222) and a set of expected key phrases in the response body (comma-separated), such as &quot;\”status\”:true,assignedTrips”. The script verifies both the status code and the presence of these key phrases. Scoring can be defined as:</p><pre>| Desired Status Code Match | Keyphrases Found | Score |<br>|---------------------------|------------------|-------|<br>| Yes                       | Yes              | +1    |<br>| No                        | Yes              | 0     |<br>| Yes                       | No               | -1    |<br>| No                        | No               | -1    |</pre><p>The second scenario should ideally be impossible. If it occurs, the key phrase definitions likely need revision. The third scenario clearly indicates an issue, either with the expected key phrases or with the response itself. Here is a sample healthcheck-response-semantic stage:</p><pre>.healthcheck-response-semantic:<br>  stage: healthcheck-response-semantic<br>  allow_failure: true<br>  tags:<br>  - docker<br>  image:<br>    name: registry.company.com/devops/runner-healthcheck:1.0.2<br>  before_script:<br>  - |<br>    # 🔧 Initialization...<br>    git clone @git.company.com/devops/cicd.git&quot;&gt;https://${GIT_AUTH}@git.company.com/devops/cicd.git<br>    echo &quot;✅ CICD repository ready for the job.&quot;<br>    export ADMIN_TOKEN=$(echo -n &quot;$ADMIN_TOKEN_64&quot; | base64 -d)<br>    export NORMAL_TOKEN=$(echo -n &quot;$NORMAL_TOKEN_64&quot; | base64 -d)<br>    echo &quot;✅ bearer tokens are fetched successfully.&quot;<br>  - |<br>    # 🕵️ Pre-Flight Check<br>    echo &quot;Checking environment...&quot;<br>    echo &quot;Looking for JSON_FILE: $JSON_FILE&quot;<br>    if [ ! -f &quot;$JSON_FILE&quot; ]; then<br>      echo &quot;❌ ERROR: JSON file not found at $JSON_FILE&quot;<br>      ls -R .<br>      exit 1<br>    fi<br>    if ! jq -e . &quot;$JSON_FILE&quot; &gt;/dev/null 2&gt;&amp;1; then<br>      echo &quot;❌ ERROR: $JSON_FILE is not valid JSON or is empty.&quot;<br>      exit 1<br>    fi<br>    echo &quot;⏳ Waiting for $ENDPOINT to be reachable...&quot;<br>    MAX_RETRIES=10<br>    RETRY_COUNT=0<br>    HEALTH_CHECK_URL=&quot;$ENDPOINT/actuator/health-check&quot;<br>    until curl -sSf -m 2 &quot;$HEALTH_CHECK_URL&quot; &gt; /dev/null 2&gt;&amp;1; do<br>        RETRY_COUNT=$((RETRY_COUNT + 1))<br>        if [ &quot;$RETRY_COUNT&quot; -ge &quot;$MAX_RETRIES&quot; ]; then<br>            echo -e &quot;\n❌ ERROR: Endpoint [$HEALTH_CHECK_URL] is NOT reachable after $MAX_RETRIES attempts.&quot;<br>            echo &quot;Check if the deployment finished correctly or if the service is crashing.&quot;<br>            exit 1<br>        fi<br>        printf &quot;  (Attempt $RETRY_COUNT/$MAX_RETRIES): Pending... \r&quot;<br>        sleep 1<br>    done<br>    echo &quot;🚀 API is UP. Starting Probes...&quot;<br>  script:<br>  - |<br>    # 🩺 PROBE: RESPONSE SEMANTIC HEALTH CHECK STAGE...<br>    echo &quot;---------------------------------------------------------&quot;<br>    echo &quot;Target: $ENDPOINT&quot;<br>    echo &quot;Rounds: $ITERATIONS | Timeout: ${REQUEST_TIMEOUT}s | Wait: ${ITERATION_SLEEP}s | Verbose: ${VERBOSE}&quot;<br>    echo &quot;---------------------------------------------------------&quot;<br>    if ! command -v jq &amp;&gt; /dev/null; then echo &quot;Error: &#39;jq&#39; is required.&quot;; exit 1; fi<br>    RAW_WEIGHT_SUM=$(jq &#39;[.[].weight // 1 | tonumber] | add&#39; &quot;$JSON_FILE&quot;)<br>    MAX_POSSIBLE_SCORE=$(( RAW_WEIGHT_SUM * ITERATIONS ))<br>    for ((i=1; i&lt;=ITERATIONS; i++)); do<br>        echo &quot;▶ ROUND $i OF $ITERATIONS...&quot;<br>        while read -r item; do<br>            ROUTE=$(echo &quot;$item&quot; | jq -r &#39;.route&#39;)<br>            METHOD=$(echo &quot;$item&quot; | jq -r &#39;.method&#39;)<br>            T_MODE=$(echo &quot;$item&quot; | jq -r &#39;.&quot;token-mode&quot;&#39;)<br>            DATA=$(echo &quot;$item&quot; | jq -r &#39;.data&#39;)<br>            CONTENT_TYPE=$(echo &quot;$item&quot; | jq -r &#39;.&quot;content-type&quot;&#39;)<br>            D_STATUS=$(echo &quot;$item&quot; | jq -r &#39;.&quot;desired-status-code&quot;&#39;)<br>            D_PHRASES=$(echo &quot;$item&quot; | jq -r &#39;.&quot;desired-keyphrases&quot;&#39;)<br>            WEIGHT=$(echo &quot;$item&quot; | jq -r &#39;.weight // 1&#39;)<br>            AUTH_HEADER=&quot;Authorization: None&quot;<br>            [[ &quot;$T_MODE&quot; == &quot;admin&quot; ]] &amp;&amp; AUTH_HEADER=&quot;Authorization: $ADMIN_TOKEN&quot;<br>            [[ &quot;$T_MODE&quot; == &quot;user&quot; ]] &amp;&amp; AUTH_HEADER=&quot;Authorization: $NORMAL_TOKEN&quot;<br>            RESPONSE_FILE=$(mktemp)<br>            HTTP_STATUS=$(curl -s -o &quot;$RESPONSE_FILE&quot; -m &quot;$REQUEST_TIMEOUT&quot; -w &quot;%{http_code}&quot; \<br>                -X &quot;$METHOD&quot; -H &quot;$AUTH_HEADER&quot; -H &quot;Content-Type: $CONTENT_TYPE&quot; \<br>                -d &quot;$DATA&quot; &quot;$ENDPOINT$ROUTE&quot;)<br>            MISSING_PHRASES=&quot;&quot;<br>            PHRASES_FOUND=true<br>            IFS=&#39;,&#39; read -ra ADDR &lt;&lt;&lt; &quot;$D_PHRASES&quot;<br>            for phrase in &quot;${ADDR[@]}&quot;; do<br>                if ! grep -q &quot;$phrase&quot; &quot;$RESPONSE_FILE&quot;; then<br>                    PHRASES_FOUND=false<br>                    MISSING_PHRASES+=&quot;&#39;$phrase&#39; &quot;<br>                fi<br>            done<br>            REASON=&quot;&quot;<br>            if [ &quot;$HTTP_STATUS&quot; -eq &quot;$D_STATUS&quot; ] &amp;&amp; [ &quot;$PHRASES_FOUND&quot; = true ]; then<br>                SCORE=1; LABEL=&quot;🟢 VALID&quot;<br>            elif [ &quot;$HTTP_STATUS&quot; -ne &quot;$D_STATUS&quot; ] &amp;&amp; [ &quot;$PHRASES_FOUND&quot; = true ]; then<br>                SCORE=0; LABEL=&quot;🟡 ANOMALY&quot;<br>                REASON=&quot;Status Code mismatch (Expected: $D_STATUS, Got: $HTTP_STATUS)&quot;<br>            else<br>                SCORE=-1; LABEL=&quot;🔴 FAILED&quot;<br>                if [ &quot;$HTTP_STATUS&quot; -ne &quot;$D_STATUS&quot; ]; then<br>                    REASON=&quot;Status Code mismatch (Expected: $D_STATUS, Got: $HTTP_STATUS). &quot;<br>                fi<br>                if [ &quot;$PHRASES_FOUND&quot; = false ]; then<br>                    REASON+=&quot;Missing keyphrases: [ $MISSING_PHRASES]&quot;<br>                fi<br>            fi<br>            WEIGHTED_SCORE=$((SCORE * WEIGHT))<br>            TOTAL_SCORE=$((TOTAL_SCORE + WEIGHTED_SCORE))<br>            CASE=&quot;$METHOD:$ROUTE&quot;<br>            printf &quot;  %-50s | %-14s | Score: %d\n&quot; &quot;$CASE&quot; &quot;$LABEL&quot; &quot;$WEIGHTED_SCORE&quot;<br>            if [ -n &quot;$REASON&quot; ]; then<br>                echo &quot;     ↳ ⚠️  REASON: $REASON&quot;<br>                if [[ &quot;$VERBOSE&quot; == &quot;true&quot; &amp;&amp; &quot;$LABEL&quot; == &quot;🔴 FAILED&quot; ]]; then<br>                    if jq -e . &gt;/dev/null 2&gt;&amp;1 &lt; &quot;$RESPONSE_FILE&quot;; then<br>                        echo &quot;     ↳ 📄 BODY:&quot;<br>                        echo &quot;$(jq . &quot;$RESPONSE_FILE&quot;)&quot;<br>                    else<br>                        echo &quot;     ↳ 📄 BODY:&quot;<br>                        echo &quot;$(cat &quot;$RESPONSE_FILE&quot;)&quot;<br>                    fi<br>                fi<br>            fi<br>            rm -f &quot;$RESPONSE_FILE&quot;<br>        done &lt; &lt;(jq -c &#39;.[]&#39; &quot;$JSON_FILE&quot;)<br>        if [ &quot;$i&quot; -lt &quot;$ITERATIONS&quot; ]; then<br>            echo &quot;   (Waiting ${ITERATION_SLEEP}s for next iteration...)&quot;<br>            sleep &quot;$ITERATION_SLEEP&quot;<br>        fi<br>    done<br>    ACHIEVED_HEALTH_SCORE_RATE=$(echo &quot;scale=2; ($TOTAL_SCORE / $MAX_POSSIBLE_SCORE) * 100&quot; | bc)<br>    echo &quot;---------------------------------------------------------&quot;<br>    echo &quot;📊 STAGE SUMMARY: RESPONSE SEMANTIC PROBE&quot;<br>    echo &quot;---------------------------------------------------------&quot;<br>    echo &quot;Raw Score: $TOTAL_SCORE / $MAX_POSSIBLE_SCORE&quot;<br>    echo &quot;Achieved Rate: $ACHIEVED_HEALTH_SCORE_RATE%&quot;<br>    echo &quot;Minimum Req:   $MINIMUM_HEALTH_SCORE_RATE%&quot;<br>    if (( $(echo &quot;$ACHIEVED_HEALTH_SCORE_RATE &gt;= $MINIMUM_HEALTH_SCORE_RATE&quot; | bc -l) )); then<br>        echo &quot;STATUS: [PASS] - Response Semantic Check Results: RELEASE HEALTHY&quot;<br>        exit 0<br>    else<br>        echo &quot;STATUS: [FAIL] - Response Semantic Check Results: RELEASE UNHEALTHY&quot;<br>        exit 1<br>    fi<br>healthcheck-response-semantic-stg:<br>  extends: .healthcheck-response-semantic<br>  variables:<br>    ENV: stg<br>    ENDPOINT: &quot;https://project.company.com&quot;<br>    ITERATIONS: 1<br>    ITERATION_SLEEP: 1<br>    REQUEST_TIMEOUT: 5<br>    JSON_FILE: &quot;cicd/project-name/healthcheck/response-semantic.json&quot;<br>    ADMIN_TOKEN_64: &quot;$STG_ADMIN_TOKEN&quot;<br>    NORMAL_TOKEN_64: &quot;$STG_NORMAL_TOKEN&quot;<br>    TOTAL_SCORE: 0<br>    MINIMUM_HEALTH_SCORE_RATE: 80<br>    VERBOSE: &quot;$HEALTHCHECK_VERBOSITY&quot;<br>  rules:<br>  - if: &#39;$CI_COMMIT_BRANCH == &quot;develop&quot;&#39;<br>  needs:<br>  - job: &quot;deploy-app-stg&quot;<br>    optional: false</pre><p>All checks can run in parallel, as their only prerequisite is that the new release is fully deployed and serving traffic (with no old pods still handling requests). Ideally, each check runs in its own isolated environment (e.g., dedicated temporary pods) to minimize external interference. A separate stage should aggregate the results and make the final decision based on the combined scores. As a rule of thumb, requiring something like 80% of the maximum possible score can serve as a threshold for marking a release as healthy. Weights and thresholds can be tuned to reflect the relative importance of each metric.</p><p>Finally, note that this is not meant to replace monitoring. These checks are lightweight, decision-oriented health checks for release validation, not a full observability or long-term monitoring solution.</p><h3>Secrets Stage: Not GitOpsed, Easy to maintain</h3><p>We said that there are always two types of data or configuration parameters required for a ready-to-ship application to run on a platform: one with non-sensitive data that we might inject as ConfigMaps, and one with sensitive data that we inject as Secrets. This stage is responsible for handling the update process of these secrets so that a new release, or even a restart of the same application, can read the updated values. Generally, this process has no dependency on other CI/CD stages and can run in parallel with the build, which is most of the time unnecessary.</p><p>A better approach is to configure the secret management system to trigger this stage, or even directly update Kubernetes secrets without defining a GitLab CI stage at all. Ideally, secrets should be handled as event-driven processes, where the required actions after a modification are explicitly defined. For example, a mapped Kubernetes secret can be updated whenever a value changes in a Vault secret engine, and a rollout restart can be triggered for pods consuming those secrets. The same approach can be applied to ConfigMaps. However, since ConfigMaps can naturally fit into a GitOps workflow, they already follow this event-driven model. Kubernetes Secret objects, on the other hand, are not ideal to store in Git repositories or to be managed by ArgoCD, since base64 encoding is not a secure way to protect sensitive data. You know the rest.</p><p>But anyway, for whatever reason, if you can’t handle this in an event-based manner, you can still define it as a small, fast stage that runs alongside the build and remains independent of commit content and other CI/CD stages. The general flow would be to create a very scoped user in your Vault cluster (or any secret management system), authenticate, retrieve the application-specific values, and apply them directly to Kubernetes. Still, avoiding this approach is highly recommended. If you handle secrets properly elsewhere, you can remove all kubeconfig contents from GitLab and significantly improve the security posture of your Kubernetes cluster.</p><h3>CICD Configuration Management: What To Handle Where, How And Why</h3><p>The conditions that help us decide whether something should be handled through repository files (and a git commit-based flow) or elsewhere are key to understanding what belongs to where and why. A large portion of CI/CD behavior can be configured using GitLab environment variables and traced via simple echo statements in the pipeline, which can radically simplify the overall structure. Deciding what should be handled at which level mostly comes down to manageability. For example: does a variable that affects pipeline behavior need different values per project? Or if it’s defined at the platform level, do we still want the flexibility to override it at the project level? Keep in mind that variables defined at higher levels are inherently more sensitive. It’s also a good practice to clearly distinguish between sensitive and non-sensitive configuration data. And if a value is never going to change, then it’s not really an environment variable. Also, don’t turn everything into a variable, like your registry address. It’s probably not going to change, and even if it does, it won’t be often. Keeping pipeline files modularized in a centralized repository also makes updates much easier with a proper IDE like VSCode or similar. Just be mindful of what you turn into an environment variable, you don’t need to over-engineer this. Yes, you can abstract everything, but you shouldn’t.</p><p><strong><em>GitLab Project-Level Environment Variables</em></strong></p><p>Variables like ENV, NEXUS, and PROXY in the build stage are good examples of project-level configuration. These typically differ per project, affect pipeline behavior, and are non-sensitive. ENV refers to environment and it’s designed so we can have a simple mapping between branches and their according environment like branch: develop → ENV=stg. The NEXUS or PROXY variables are usually boolean flags that can vary between projects and are indicators of using nexus registry and network proxy. Managing them as environment variables is far more practical than hard-coding them into modular pipeline files, especially since developers and maintainers may need to adjust them over time.</p><p><strong><em>GitLab Platform-Level Environment Variables</em></strong></p><p>At the platform level, we typically store the most sensitive data, since access is limited to fewer people. Variables like DOCKER_AUTH_CONFIG, GIT_AUTH_JSONand optionally KUBE_CONF_DEV or KUBE_CONF_PROD fall into this category. These are not meant to be handled at the project, or even group, level due to their sensitivity and scope.</p><p>That’s it. Happy CI/CD!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ad7b26b0b0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes for Stateful Applications: Are We Adding an Abstraction That Stops Paying Rent?]]></title>
            <link>https://medium.com/@hatamabolghasemi/kubernetes-for-stateful-applications-are-we-adding-an-abstraction-that-stops-paying-rent-26ad69e8358b?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/26ad69e8358b</guid>
            <category><![CDATA[stateful-applications]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Sun, 31 May 2026 06:54:00 GMT</pubDate>
            <atom:updated>2026-07-13T10:38:43.610Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a debate that keeps coming up on infra teams, and it usually gets flattened into a slogan: “we should run everything on Kubernetes.” That’s simply wrong, and I want to explain why, using something I actually operate: self-hosted Sentry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UB6jmEEqTr9L1OGAV0M8Q.png" /></figure><p>First, let me be clear about where I’m coming from. I’m not anti-Kubernetes. I run Kubernetes, GitOps, ArgoCD, the whole ecosystem, daily. For a huge chunk of workloads it’s genuinely the right call. What I’ve become skeptical of is the <em>assumption</em> that every complex stateful system automatically benefits from being on Kubernetes, especially things like Sentry, Kafka, ClickHouse, GitLab, Nexus, or any big self-hosted data platform. The question was never whether Kubernetes <em>can</em> run these. Of course it can. The real question is: <strong>at what point do Kubernetes’ abstractions stop paying rent?</strong></p><h4><strong>Where Kubernetes actually shines</strong></h4><p>Picture a company with dozens or hundreds of internally built microservices. Each one scales horizontally, serves traffic independently, tolerates pod restarts, has interchangeable replicas, and leans on service discovery. This is the exact shape of problem Kubernetes was built for. A node dies? The scheduler just moves things. Traffic spikes? Horizontal scaling handles it. A bad deploy? Roll it back declaratively. The abstraction lines up perfectly with the workload, scheduling, reconciliation, Services, declarative desired state, GitOps, one shared observability model across dozens of teams. For internally developed apps, Kubernetes is close to ideal, and that shared operational model is genuinely valuable when you’ve got that many teams shipping software.</p><h4><strong>Then I looked at Sentry</strong></h4><p>Now take something like self-hosted Sentry at real event volume. On paper it looks like “an app.” In practice it’s a distributed data platform wearing an app costume. Under the hood you’re running Kafka, ClickHouse, Redis, Snuba consumers, ingestion pipelines, queue backlogs, retention policies, storage pressure, throughput bottlenecks, the works.</p><p>Here’s the thing that struck me: the day-to-day pain with Sentry was never deployments. It was maintenance. And that distinction actually matters a lot. People defend Kubernetes with deployment ergonomics, “upgrades are easier,” “rollouts are cleaner,” “everything’s declarative.” Sure, fine. But how often do you actually upgrade a system like Sentry? Monthly, maybe quarterly. Now compare that to consumer lag and storage tuning, which you’re dealing with basically every day. If upgrades happen four times a year and maintenance happens constantly, upgrade convenience is a pretty weak argument for your platform choice. <strong>The workload you actually deal with every day should matter more than the rare stuff.</strong></p><p>Sentry’s just the example here, the real question underneath it is whether the benefit is actually worth the cost, or whether we’re just optimizing for the thing that’s easy to point to.</p><h4><strong>The scheduler starts fighting you</strong></h4><p>Kubernetes’ biggest superpower is arguably the scheduler. The whole philosophy is: your app shouldn’t care where it runs. Pods move, nodes fail, the system just converges toward desired state. For stateless workloads that’s incredible. But stateful systems gradually chip away at that flexibility. Kafka brokers want stable identity. Persistent workloads want durable storage tied to a specific place. Clusters need topology awareness. So you start adding node affinity, anti-affinity, persistent volumes, topology spread constraints, carefully ordered startup sequences, and suddenly the scheduler isn’t really deciding anything anymore. It’s just following the very narrow box you built for it.</p><p>At some point you have to ask the uncomfortable question: if I’m this heavily constraining the scheduler, skipping service-level load balancing, and manually hand-placing everything, <strong>how much of Kubernetes am I actually still using?</strong></p><h4><strong>“But uniform operations!”</strong></h4><p>This is usually the strongest counterargument, and honestly, for internally built apps, I agree with it completely. One platform, one deployment model, one observability stack, one debugging playbook, that’s a real win when it’s your own microservices. But I’m a lot less convinced the same logic holds for operationally heavy third-party systems. Do I really need the identical operational model for our own microservices <em>and</em> Sentry <em>and</em> GitLab <em>and</em> a Kafka cluster? Those third-party systems already arrive with their own operational complexity baked in. Sometimes it feels like we’re just stacking a second layer of orchestration complexity on top of a system that was already hard enough to run.</p><h4><strong>To be clear, still not an anti-Kubernetes take</strong></h4><p>This isn’t an argument against Kubernetes. It’s an argument against defaulting to it without checking the math. Kubernetes is exceptional exactly when its abstractions line up with how the workload actually behaves. But an abstraction only earns its keep when it meaningfully cuts operational burden. Sometimes it does. Sometimes it just adds a translation layer on top of complexity that was never actually solved. That doesn’t make Kubernetes wrong, it just makes it a contextual decision. For stateless, internally-built services, it’s often the obvious choice. For operationally demanding stateful systems, it deserves a lot more scrutiny. Maybe Kubernetes still wins. Maybe a managed service is better. Maybe a boring VM is simpler. The real question was never “can Kubernetes run this.” It’s <strong>“are Kubernetes’ abstractions still paying rent for this specific workload?”</strong></p><p>To wrap up: Kubernetes is an orchestration system. Let it orchestrate the things that are actually orchestration-friendly, not reflexively everything you own. With full respect to the people building Operators and CRDs (some of that work is genuinely impressive), I think the real question isn’t whether Kubernetes <em>can</em> run a given system. It’s whether it <em>should</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26ad69e8358b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[For the Sake of Maintainability and MTTR Minimization]]></title>
            <link>https://medium.com/@hatamabolghasemi/for-the-sake-of-maintainability-and-mttr-minimization-5e963b8f2c8d?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e963b8f2c8d</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mttr]]></category>
            <category><![CDATA[reliability]]></category>
            <category><![CDATA[maintainability]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 22:05:45 GMT</pubDate>
            <atom:updated>2026-07-02T20:37:13.829Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re working as a DevOps engineer, probably the only legacy member on your team, and you’re the most responsible person for your company’s infrastructure. All hopes are on you to recover a broken system after some random failure, maybe caused by a bad configuration, or a legacy service that’s been running for over five years and everyone before you just ignored with a “let’s not touch what’s working.”</p><p>The service you set up today with the help of a random LinuxForge or DigitalOcean blog post, and not the official docs, is not guaranteed to be treated with any best practices. You can’t expect backend developers to care about how their app interacts with the MongoDB cluster you just set up. You can’t expect your company’s Sentry integration to stay sane when exception handling slowly turns into an event and transaction logger. You NEED to be careful about what you set up, because you’ll be the one who maintains and saves it in case of future failure. You’re also the one who sets up the monitoring for your Kafka cluster and does all the Kafka admin tasks, not the developers writing consumers and producers.</p><p>Yes, you need to deliver fast. Yes, the business can’t tolerate much downtime for your upgrade tasks. Yes, they won’t get you skilled teammates to speed things up. And yes, you need to be result-oriented, because the DevOps world is endless with R&amp;D, and everything looks necessary to learn before you design a new cluster. But you need to be careful with your R&amp;D time because every useless link that you open looking for a solution costs time. And this time matters more than tools fanciness and need the best practices much more than those tools.</p><p>Whatever your task is, fixing network congestion, setting up alert management, updating a production Kubernetes cluster, you need to consider MTTR minimization before every Ansible playbook or Bash script you write to make things look fancy or easy. And how to keep track of it? Here are my experiences and advice after three years in DevOps:</p><h3>1. Understand the Real Need Before Over-Engineering</h3><p>Don’t jump to apply your “perfect” personal best practices. Sometimes the GitLab pipeline the frontend team wants doesn’t need to be modern or secured. Don’t spin up ArgoCD or Vault cluster just for a simple npm install pipeline. All you need to do is understand their manual steps and automate them. Writing a CI/CD pipeline isn’t about reinventing the wheel. Deploying a microservice isn’t always about containerization or Kubernetes. What you need isn’t perfect, it’s the maintainable and flexible. Products and services come and go, and no company guarantees permanence. Don’t treat your tasks like they’re going to win medals. Listen, and do what’s needed, and do it flexibly. And the flexibility is about mastery of doing simple things and understanding what really is happening in those simple things so you can customize any part of it anytime with no fear of unknown.</p><h3>2. Don’t Add Unnecessary Translations</h3><p>Tools already rename concepts differently. Don’t make it worse by adding your own synonyms. How you can screw up:</p><ul><li>Naming VMs after movie characters nobody knows about.</li><li>Misleading container names (psql for ProxySQL).</li><li>nodeor phpor whatever which are all referring to api container and can be sometimes queue containers.</li><li>Variables for things that will never have more than one value (like victoriametrics-monitoring, you won’t use VictoriaMetrics anywhere else).</li><li>Unnecessary postfix/prefix (grafana-service, you’ll only ever find them with kubectl get svc anyway).</li><li>Proxmox nodes named assrv-01-whatever (everything is a server: nginx, redis, sentry…).</li></ul><p>Just name sanely and enough. Use names that are clear, boring, and searchable. haproxy-dev-1, k8s-master-3. That’s it. The physical location of node, the version it’s using, they are all metadata and annotations. don’t reflect the whole identity card in the full name.</p><h3>3. Stick to Official and Community-Supported Tools</h3><p>If the doc says to install via Helm, do it with Helm. If they ship Docker images, use those. Don’t containerize what isn’t meant to be containerized. Yes, third-party projects may have active communities and big-name clients. But who predicted Bitnami would kill their free images? You get my point. Need Redis? Read the Redis docs. Need Mattermost? Follow its docs. Kafka devs know Kafka better than Strimzi devs. I’m not trashing other projects, just pointing out that these extra “translations” add unnecessary headaches in debugging and are not supposed to be long-term guaranteed. Spend your time learning the actual internals of the tools, not the wrappers and modifiers. As game mods can break your system, modded DevOps tools can break infrastructures too. You don’t need fancy clusters, you need reliable ones and that reliability is only possible by stabilizing your pure knowledge about the workflow of those tools.</p><h3>4. Design for Disasters Before You Create Anything</h3><ul><li>Use LVMs if storage needs are unpredictable.</li><li>Enable memory ballooning if usage isn’t static.</li><li>Create a new repo if its version history must stay separate.</li><li>Define an order and stick to it.</li></ul><p>That “order” becomes the only guide for future engineers when you leave without documentation. Making it rational and easy to follow is the best gift you can leave.</p><h3>5. Document Less, Standardize More</h3><p>Everybody says “document everything,” but here’s the truth: nobody reads outdated docs. What actually saves future-you (or the next engineer) is standards, not novels. If every VM has the same directory layout, if every CI/CD pipeline follows the same structure, if every cluster follows the same naming rules, then you don’t need to document every single thing. Standardization is documentation. Write docs only for the things that truly need human explanation like the “why” behind decisions, the things that aren’t obvious, the risks. For everything else, make the system self-explanatory through order and consistency.</p><h3>6. Automate Only What You Understand</h3><p>Blind automation is a silent disaster. Just because you can wrap something in Ansible or Terraform doesn’t mean you should. If you don’t understand what the script is doing at a low level, you’re just hiding a bomb under a nice YAML file. When it explodes, you’ll be slower to recover. Automation should be the last step, not the first. Learn the manual process first, practice somewhere safe and at once you could recover from scratch without the tool, automate it. Automation exists to reduce MTTR, not to create magical black boxes.</p><h3>7. Never Trust Defaults in Production</h3><p>Defaults are optimized for demos, not for reliability. Default PostgreSQL configs will die under real load. Default Kafka retention settings will eat your storage. Default Docker logging will silently fill your disks. Default Kubernetes resource requests will starve your nodes. If you’re running defaults in prod, you’re just pushing the crash into the future. Always read through configs and adjust for your workload. Learn about the basic features, the ways you can customize each and the side-effects that each change might have. Defaults are a starting point, not a production plan.</p><h3>8. Monitoring Isn’t Just Metrics</h3><p>A Grafana dashboard full of pretty graphs won’t save you if you don’t know what they mean. Monitoring is not about volume, it’s about clarity<strong>. </strong>Alerts should be actionable. If you can’t act on it, it’s probably noise. Metrics should be mapped to real business impact (CPU high? Who cares. API latency spiking? That matters). Logs should be precise and to-the-point, not drown you in lines. Monitoring is there to shorten MTTR, not to impress anyone with dashboards. If your team ignores 90% of the alerts, then your monitoring is just fucked up.</p><h3>9. Backups Are Useless Without Restores</h3><p>Everyone says they “have backups.” Almost nobody tests restores. Until you’ve actually done a restore drill, you don’t have a backup, you have a false sense of security. Schedule restore tests. Automate them if possible. Even if it’s once a month, it’s worth it. When disaster strikes, this alone can turn a 12-hour outage into a 30-minute hiccup. Even fake a disaster and check if they’re not buggy with new updates that you’ve applied to the service and they do consider everything they’re supposed to do.</p><h3>10. Kill Your Pets, Grow Your Cattle</h3><p>If your infrastructure is full of “pets” (that one special VM you treat like royalty because you’re afraid to touch it), you’ve already lost. Every part of your system should be replaceable, reproducible, and disposable. If a server dies and your first thought is “oh no, how do I fix this one,” you’ve built wrong. Your first thought should be “just redeploy it.” Pets increase MTTR and Cattle minimize it.</p><h3>Wrap Up</h3><p>At the end of the day, DevOps isn’t about shiny tools or bragging rights. It’s about being the one who keeps the lights on, who minimizes downtime, who makes the system recoverable. You want 99.9999999% SLAs? Just prioritize standardization and maintainability over automation and security theater and chasing the newest CNCF tools and instead try to build with MTTR minimization in mind. Because when failure comes, and it always comes, you won’t win medals for being clever, You’ll win by being reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e963b8f2c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Reduced PHP-FPM-Based Backend Stack Memory Utilization by Over 80% — Without Changing a Line…]]></title>
            <link>https://medium.com/@hatamabolghasemi/how-i-reduced-php-fpm-based-backend-stack-memory-utilization-by-over-80-without-changing-a-line-a22dd983c6ea?source=rss-6aa0f7c725f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a22dd983c6ea</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[php-fpm]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Hatam Abolghasemi]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 19:57:24 GMT</pubDate>
            <atom:updated>2025-07-29T04:43:31.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I reduced our PHP-FPM-based backend stack memory utilization by over 80% without changing a single line of code</h3><p>So, once upon a time, while i was busy doing a big task “CI/CD Revision” I experienced something strange in the middle of one of its sub-tasks. The sub-task was about increasing the observability as much as possible and since our backend was mostly written in php/laravel, I tried to look for some sort of php-exporter or php-fpm/swoole/whatever-exporter. I found this <a href="https://github.com/hipages/php-fpm_exporter">php-fpm-exporter</a> thing and I added its container to some of our backend pods in Kubernetes cluster and connected its data to our monitoring stack. After setting it up in some 7 to 11 microservices, I thought now I have enough historical traces to see what cool information these metrics are able to give me about our applications behaviours. So I started exploring those 18 metrics exposed by the fpm-exporter per each app at each environment, creating different queries and trying different grafana visualizations.</p><p>As I kept hacking on my ugly Grafana dashboard, one chart in particular caught my attention — I had called it <strong>“process status ratio” </strong>which was running these two queries:</p><pre># active<br>sum(phpfpm_active_processes{target_namespace=~&quot;$namespace&quot;, target_pod=~&quot;$app-app-.*&quot;}) / sum(phpfpm_total_processes{target_namespace=~&quot;$namespace&quot;, target_pod=~&quot;$app-app-.*&quot;})<br><br># idle:<br>sum(phpfpm_idle_processes{target_namespace=~&quot;$namespace&quot;, target_pod=~&quot;$app-app-.*&quot;}) / sum(phpfpm_total_processes{target_namespace=~&quot;$namespace&quot;, target_pod=~&quot;$app-app-.*&quot;})</pre><p>In nearly all the apps I checked, the story was the same:<br> <strong>1 active process and 99 idle ones. </strong>This wasn’t a one-time fluke. I gathered data for several days (more than 7 days) and the numbers almost didn’t change. That struck me as deeply wrong. If you’ve seen an <strong>always-99%-idle</strong> CPU, you know what that means. it’s called <strong>extreme underutilization.</strong> So of course something must have been misconfigured or misworking. Then it hit me: there’s this www.conf config file we use for all PHP-FPM apps across all environments. It looked like this:</p><pre>pm = dynamic<br>pm.max_children = 250<br>pm.start_servers = 100<br>pm.min_spare_servers = 50<br>pm.max_spare_servers = 150<br>pm.max_requests = 1024</pre><p>So why should all apps use the <strong>same</strong> config? They don’t have the same traffic patterns, they don’t serve the same functions, they don’t even run in the same environments. what do these configs even <strong>mean</strong>, really?</p><p>So I began reading and taking notes. As I always document my learning at my Notion workspace, I created a page for <a href="https://hatam.notion.site/www-conf-21a7827e85968065bfc4cfd8ee46f11a">www.conf</a>. Eventually, I understood the implications. pm.start_servers = 100 means the app must spin 100 PHP-FPM worker processes at the startup and if 99 of them are idle at all times… you’ve just reserved memory for no reason!!! The “idle” processes I was seeing? That’s literally the result of over-provisioning. Now scale the big-aha to all environments and most of the backend stack.</p><p>But then came the bigger question: “<strong>Okay, we’ve been using the wrong defaults, but what should we use instead?” </strong>That default config is actually great but only for a very specific use case. It’s made for high-traffic, high-concurrency PHP-FPM servers that need to handle big loads reliably without scaling out. But our setup is nothing like that. We are managing load via Kubernetes and <strong>horizontal pod scaling.</strong> That means we <strong>don’t want superhero FPM or whatever pods</strong> with super high resource limits. We want just-enough capacity per pod, and let Kubernetes scale them out as needed.</p><p>I dug into each setting, what metrics affect it, how traffic patterns play a role and I built a small bash script called <strong>php-fpm-advisor.sh</strong> that reads from an input.json file. This small automation helped me at the math/logic part of the fixing process. Here’s the script: <a href="https://hatam.notion.site/php-fpm-advisor-sh-2367827e859680d4b5a8e8a270386066">php-fpm-advisor.sh</a>. I do not recommend using it without reading and understanding how and based on what formulas those numbers are being generated. Also the JSON is better to be populated with data from at least a 7-day window. the longer, the more accurate.</p><p>Just as a proof it’s one small application’s result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QR36jMRkD0LFpV0SDcPKbA.png" /></figure><p>I constantly tracked requests behavior and latency after the changes, asking myself: <strong>“Are we sure that we are not paying a performance cost for this?” </strong>Answer: no. The only thing we “sacrificed” was blindly copied boilerplate. That’s it. You don’t need to buy new servers to handle more traffic. You don’t need to switch on golang or rust or whatever else. Just stop blindly copying defaults. It will show its effect on the scale of applications that are working with more than like 20 pods or more.</p><p>To wrap-up:</p><ul><li>Add <a href="https://github.com/hipages/php-fpm_exporter">fpm-exporter</a> container to your PHP-FPM pods.</li><li>Connect the metrics to Victoriametrics.</li><li>Develop a Grafana Dashboard or use <a href="https://hatam.notion.site/Grafana-Dashboard-2367827e85968077b977cfac6655e72f">my Grafana dashboard</a>.</li><li>Monitor your apps for at least a week or a month.</li><li>Feed the results to php-fpm-advisor.sh.</li><li>Apply the recommendations (probably as configmaps).</li><li>Restart your pods. That’s it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a22dd983c6ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>