<?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 Udayraj Dhavande on Medium]]></title>
        <description><![CDATA[Stories by Udayraj Dhavande on Medium]]></description>
        <link>https://medium.com/@udayrajdhavande8?source=rss-d0dbda6e7e0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Udayraj Dhavande on Medium</title>
            <link>https://medium.com/@udayrajdhavande8?source=rss-d0dbda6e7e0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:43:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@udayrajdhavande8/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[Building a Two-Site Ceph DR Lab on a 16 GB Laptop: Setup, Every Bug I Hit, and a Live PR→DR…]]></title>
            <link>https://medium.com/@udayrajdhavande8/building-a-two-site-ceph-dr-lab-on-a-16-gb-laptop-setup-every-bug-i-hit-and-a-live-pr-dr-0f9e4a5a2300?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f9e4a5a2300</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[data-storage]]></category>
            <category><![CDATA[ceph]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 21:11:36 GMT</pubDate>
            <atom:updated>2026-09-21T21:11:36.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3-_8YwabhQGzavJi8k9Yw.png" /></figure><h3>Building a Two-Site Ceph DR Lab on a 16 GB Laptop: Setup, Every Bug I Hit, and a Live PR→DR Failover</h3><p><em>Why Ceph exists, what to decide before you build, what you can never change afterwards, and the full build log, in the order things actually broke.</em></p><h3>The goal of the lab</h3><p>The purpose of this lab was to turn Ceph storage and disaster-recovery concepts into a hands-on environment that could be built, tested, broken, and recovered on real hardware.</p><p>The lab was designed to demonstrate the full lifecycle of a Ceph-backed virtualization and DR setup, including storage provisioning, RBD access, asynchronous replication, failover, and failback.So one weekend, on a Lenovo Yoga with 16 GB of RAM and more optimism than sense, I built:</p><ul><li>a 3-node Ceph cluster (the <strong>PR</strong>, primary site),</li><li>a separate, independent Ceph cluster (the <strong>DR</strong> site),</li><li>and two Kubernetes VMs whose data disks live on Ceph.</li></ul><p>Then I failed those VMs over from PR to DR, on purpose, just to see whether I understood the thing</p><p>I did, eventually. This post covers:</p><ol><li><strong>Why Ceph</strong>: what it is, what it provides, where it shines and where it’s a bad idea</li><li><strong>What to decide before you build</strong>: the planning that saves you weeks</li><li><strong>What is set in stone and what you can change later</strong></li><li><strong>The full build</strong>: hosts, PR cluster, DR cluster, pools, RBD, libvirt, RBD mirroring, failover and failback, with commands and every bug in order</li><li><strong>A checklist</strong> you can steal</li></ol><p>The Kubernetes side of this lab is covered in a separate Part 2. This post is the storage and DR foundation.</p><h3>Part 1: Why Ceph?</h3><h3>The problem with “normal” infrastructure</h3><p>Most infrastructure grows the same way. You buy servers, give each one local disks (or a RAID card), run VMs on them, and it works fine until:</p><ul><li><strong>A host dies</strong>, and you’re restoring VMs from backup instead of just restarting them elsewhere, because the data lived only on that host.</li><li><strong>You need to patch a hypervisor</strong>, and every VM on it must first move somewhere else, which means copying its entire disk over the network to another host’s local storage.</li><li><strong>Your DR story is “we have last night’s backup”</strong> instead of “we have a live copy seconds behind.”</li></ul><p>That isn’t a personal failing. It’s what happens when compute and storage are welded together.</p><h3>What Ceph is</h3><p><strong>Ceph is a distributed, software-defined storage system.</strong> Instead of one server owning “the disk,” Ceph spreads data across many disks on many machines, keeps multiple copies automatically, and presents the whole pool to the outside world as if it were one big, always-available storage system, even while individual disks or entire servers are failing underneath it.</p><p>The core idea: <strong>stop tying compute to specific disks.</strong> Storage becomes its own network-reachable layer. Any hypervisor can reach it. It heals itself when hardware dies. It can replicate itself to a second site continuously.</p><h3>What Ceph provides</h3><p>One cluster, three ways to consume it:</p><ul><li><strong>RBD (block)</strong>: virtual hard disks for VMs and Kubernetes persistent volumes. This is what this lab uses.</li><li><strong>CephFS (file)</strong>: a POSIX shared filesystem.</li><li><strong>RGW (object)</strong>: an S3-compatible object store.</li></ul><p>And the features that come with it:</p><ul><li><strong>Scale-out</strong>: add hosts and disks, and capacity and performance grow. No forklift upgrade.</li><li><strong>Self-healing</strong>: lose a disk or a node and Ceph re-creates the missing copies on its own.</li><li><strong>No single point of failure</strong>: there’s no central lookup table (more on CRUSH below).</li><li><strong>Replication or erasure coding</strong>: pay for redundancy with 3× raw space, or with less overhead plus more CPU.</li><li><strong>Thin provisioning, snapshots, clones</strong>: the things you’d expect from a modern storage layer.</li><li><strong>Multi-site replication</strong>: RBD mirroring for block, multisite for object, mirroring for CephFS.</li></ul><h3>Where Ceph fits</h3><ul><li><strong>Private clouds and virtualization</strong>: OpenStack, Proxmox, KVM/libvirt fleets. Live migration becomes trivial because the disk never moves.</li><li><strong>Kubernetes persistent storage</strong>: through Rook or ceph-csi.</li><li><strong>S3-compatible object storage</strong> for backups, artifacts, and data lakes.</li><li><strong>Long-lived infrastructure</strong> with real capacity planning, where “this needs to survive hardware churn for years” is something someone says in a planning meeting.</li></ul><h3>Where Ceph is the wrong answer</h3><p>Ceph is <strong>not a small-scale tool</strong>. If you have three VMs and a NAS, Ceph is a hilarious answer to a question nobody asked. You’ll spend more time babysitting monitors and OSDs than you ever would have worrying about a single RAID card.</p><p>Be honest about the trade-offs too:</p><ul><li><strong>Latency</strong>: every write crosses the network and waits for replicas. A local NVMe will always win a single-stream latency contest.</li><li><strong>Raw-capacity overhead</strong>: 3-way replication means <strong>1 TiB of data costs 3 TiB of disk.</strong></li><li><strong>Operational depth</strong>: you need people who understand it, or a vendor who does (Red Hat/IBM, Canonical, and others sell supported Ceph).</li></ul><h3>The cast of characters</h3><p>Here’s each component, with the Kubernetes analogy that made it click for me.</p><ul><li><strong>RADOS</strong> is the distributed object store underneath everything. RBD, CephFS, and RGW are all just clients of it.</li><li><strong>Monitors (mons)</strong> hold the cluster map (who’s alive, what’s where, what the rules are) and form a <strong>quorum</strong>. You need a majority up to make decisions, exactly like etcd. That’s why real deployments run 3 or 5 mons across separate failure domains.</li><li><strong>Managers (mgrs)</strong> run the orchestrator (cephadm), the dashboard, and modules. They don&#39;t hold the source of truth; they <em>act</em> on it, much like a control plane&#39;s controllers.</li><li><strong>OSDs (Object Storage Daemons)</strong>: one per disk, and where data actually lives. Lose an OSD or a whole host and Ceph notices the missing copies, finds spare capacity elsewhere, and re-replicates. That’s the same self-healing instinct as a Deployment replacing a dead pod, except the “pod” is a copy of your data.</li><li><strong>CRUSH</strong> is the algorithm that decides which OSDs hold which data, computed from a rule plus a map of your physical topology (OSD → host → rack → room). Any client can calculate where an object lives itself, with no central directory. It works like pod anti-affinity, but per object and deterministic.</li><li><strong>Pools</strong> are named containers with their own replication factor, CRUSH rule, and enabled applications (RBD, RGW, CephFS).</li><li><strong>RBD</strong> turns part of a pool into a virtual block device that QEMU/KVM can boot from directly.</li><li><strong>rbd-mirror</strong> is a daemon that ships changes asynchronously to a second, independent cluster. It’s the DR engine.</li></ul><p><strong>A concrete example.</strong> You have 6 OSDs across 3 hosts, replication factor 3. You write a 4 MB object. Ceph maps it to a placement group, and CRUSH picks 3 OSDs, one per host. Pull the power cord on a host. Ceph marks those OSDs down, and once it decides they’re not coming back soon, it creates fresh third copies of every affected PG on the surviving hosts. Nobody touched anything.</p><h3>Part 2: What to decide before you build</h3><p>The most expensive lesson of this whole project was that I didn’t plan the storage layer up front. Ceph’s defaults encode strong opinions, and several of them are painful to retrofit once pools exist.</p><h3>The one fact that drives everything</h3><p>Ceph’s default replication factor is <strong>3</strong>, and the default CRUSH rule spreads those copies across three different <strong>hosts</strong>. So:</p><ul><li>You need <strong>at least 3 hosts</strong> contributing storage before a replicated pool can be healthy.</li><li>You can add fifty OSDs to a single host and Ceph will <em>still</em> refuse to place PGs across three hosts that don’t exist. That isn’t a bug. Ceph is refusing to lie to you about redundancy you don’t have.</li></ul><h3>Before cephadm bootstrap, someone must have answered these</h3><ul><li><strong>Failure domains.</strong> Are you protecting against a disk, a host, a rack, a room, a site? The number of <em>real</em> failure domains you have determines your realistic replication factor, not the other way around.</li><li><strong>Host sizing.</strong> CPU and RAM per OSD (Ceph wants real headroom per daemon; the default memory target is around 4 GiB per OSD). Decide NVMe versus spinning disk. Give OSD replication traffic a <strong>separate cluster network</strong> so it doesn’t fight client traffic.</li><li><strong>Monitor count and placement.</strong> Odd numbers (3 or 5), spread across failure domains.</li><li><strong>Release and lifecycle.</strong> Pin a Ceph release, know its end-of-life date, and decide who owns upgrades. I hit this mid-lab: a download URL 404&#39;d because the release I targeted had already been archived.</li><li><strong>Support model.</strong> Community Ceph or a vendor with an SLA for when quorum breaks at 3 AM?</li><li><strong>DR design.</strong> Async mirroring (non-zero RPO) or something else? Which pools get mirrored? <strong>Pool names must be identical on both sites</strong>, so decide them on day one.</li><li><strong>Network and time.</strong> Reliable DNS or hosts entries, time sync everywhere (monitors are picky about clock skew), and firewall ports open between nodes: monitors on 3300 and 6789, and OSDs/managers on 6800–7300.</li><li><strong>A RAM budget you treat as load-bearing.</strong> More on that in a moment.</li></ul><p>Get this right on day one and Ceph mostly just works, quietly, in the background. Get it wrong and every fix is a retrofit against live data.</p><h3>Part 3: What is set in stone, and what you can change later</h3><p>This is the section I wish I’d had at the start. Ceph is flexible, but a handful of decisions are effectively permanent.</p><h3>Effectively set in stone (changing means rebuild or migrate)</h3><ul><li><strong>The cluster FSID.</strong> It’s minted at bootstrap and is the cluster’s identity. It’s also why a DR site must be a <em>separate</em> cluster rather than extra nodes joined to the primary.</li><li><strong>Pool type: replicated versus erasure-coded.</strong> You can’t convert a pool in place. You create a new pool and migrate data.</li><li><strong>An erasure-code profile (k+m) on an existing pool.</strong> The same story: new pool, migrate.</li><li><strong>RBD image object size and striping.</strong> These are chosen at image creation. Changing them means a new image and a migration.</li><li><strong>The </strong><strong>deep-flatten image feature.</strong> You can disable it on an existing image but not enable it later.</li><li><strong>OSD identity and backend.</strong> OSD IDs are permanent, and BlueStore parameters like the allocation unit are baked in when the OSD is created. Changing them means destroying and redeploying the OSD.</li><li><strong>Upgrades are one-way.</strong> You upgrade forward through supported paths; you don’t downgrade a cluster.</li><li><strong>Quorum math.</strong> Mons need a strict majority. That’s physics, not a setting.</li><li><strong>Mirroring’s naming rule.</strong> For the RBD mirroring setup used here, the pool must have the <strong>same name on both clusters</strong>.</li></ul><h3>Changeable, but it costs you (data movement, risk, or breakage)</h3><ul><li><strong>Replication </strong><strong>size / </strong><strong>min_size.</strong> This can be changed live, but it triggers backfill, and lowering min_size trades safety for availability.</li><li><strong>CRUSH rule and failure domain.</strong> You can point a pool at a different rule live, but data reshuffles across the cluster.</li><li><strong>pg_num.</strong> It can be raised <em>and</em> lowered on modern releases (the autoscaler does this for you), but PG changes cause data movement.</li><li><strong>Pool name.</strong> ceph osd pool rename is clean and moves no data, but everything referencing the old name <em>by string</em> breaks: cephx caps, libvirt XML, automation, and mirroring (rename both sites).</li><li><strong>Monitor IPs and hostnames.</strong> These are technically changeable but painful. cephadm registers hosts by FQDN, and changing mon addresses means editing the monmap. Treat them as permanent.</li><li><strong>Mirroring mode (journal ↔ snapshot).</strong> You disable and re-enable, and the image resyncs.</li><li><strong>Public and cluster networks.</strong> They’re changeable, and disruptive.</li></ul><h3>Freely changeable (live, low drama)</h3><ul><li>Add or remove OSDs and hosts (Ceph rebalances)</li><li>Add or remove monitors and managers via orchestrator placement</li><li>Grow an RBD image (rbd resize); shrinking needs --allow-shrink <em>and</em> the guest filesystem shrunk first</li><li>Enable or disable most image features (journaling, object-map, fast-diff)</li><li>Snapshots and clones</li><li>Runtime configuration (ceph config set …)</li><li>On the hypervisor side: libvirt monitor endpoints and secrets (with the VM shut off) and the guest’s /etc/fstab</li></ul><blockquote><strong><em>Rule of thumb:</em></strong><em> identity, pool type, and on-disk layout are permanent. Placement, counts, and policies are adjustable at the cost of data movement.</em></blockquote><h3>Part 4: The lab</h3><p>Everything ran as KVM/libvirt VMs on one physical box:</p><pre>Host:  Lenovo Yoga 6 13ARE05<br>OS:    Debian GNU/Linux 12<br>CPU:   AMD Ryzen 7 4700U (8 threads)<br>RAM:   ~15 GiB usable</pre><pre>                   Lenovo KVM host<br>                         |<br>        +----------------+-----------------+<br>        |                                  |<br>   PR Ceph cluster                   DR Ceph cluster<br> ceph1  ceph2  ceph3                       dr1<br> (3 mons, mgr, OSDs)              (1 node, own fsid)<br>        |                                  |<br>        +---- journal-based RBD mirror ----+<br>                    |<br>           libvirt-swift-pool<br>             |             |<br>          k8s-master-data  k8s-worker-data<br>             |             |<br>          k8s-master VM  k8s-worker VM  (vdb → /data)</pre><p>The PR and DR clusters are <strong>two independent Ceph clusters</strong>, each with its own fsid, mons, and OSDs. A Ceph cluster gives you availability <em>inside</em> a site. RBD mirroring gives you replication <em>between</em> sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*77So7PA5_HC1gvCLrrZUYw.png" /><figcaption>vms running on host</figcaption></figure><h3>Why VMs on one laptop? The honest limitation</h3><p>Two reasons, no spin:</p><ol><li><strong>One machine can’t be three failure domains.</strong> Surviving a host dying requires multiple hosts. Running each Ceph node as its own VM was the only way to get independent hostnames, IPs, and boot lifecycles, and so to exercise host-based CRUSH rules, quorum loss, and maintenance drills on one box.</li><li><strong>It reuses the exact KVM/libvirt tooling my real job runs on</strong>: virsh, domain XML, live-migration primitives.</li></ol><p>The cost: everything is resource-starved, and I hit bugs (CPU model quirks, contention-triggered boot hangs) that real hardware would never produce. <strong>In production you would never do this.</strong> Ceph nodes are physical (or properly resourced VMs on separate physical hosts) so one hardware failure can’t take out several “independent” nodes. This is a learning compromise, not a design pattern.</p><h3>The heart-attack moment: RAM math</h3><p>At the worst point I had ceph1/2/3 (3+ 2.5 + 2.5 GiB), the DR node (3 GiB), and both Kubernetes VMs (up to 4GiB combined) running at once. That’s <strong>six VMs and well over 15GiB committed on a ~15 GiB laptop</strong>. free -h showed <strong>150 MB</strong> genuinely free. Megabytes, not gigabytes.</p><p>Nothing crashed. Overcommit and reclaimable page cache absorbed it. But in a real environment this is how the OOM killer picks a monitor or OSD to sacrifice, and you explain in a postmortem why storage quorum broke. It “worked” because nothing peaked at the same time, and that’s luck, not a plan.</p><blockquote><strong><em>Plan your RAM budget like it’s load-bearing, because it is.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPYCMIt5ZGMhhUQxvZRNvQ.png" /></figure><h3>Part 5: Building the node VMs</h3><p>Each node started from one <strong>golden Rocky Linux 9</strong> image (RHEL-family, so dnf patching drills transfer to real enterprise habits), cloned with qcow2 backing files so three near-empty OS disks were created in seconds. Cloud-init handled first boot: hostname, SSH key, and the packages cephadm requires (podman, lvm2, chrony, python3).</p><h3>Gotcha 1: the SSH key that never landed</h3><p>Nodes booted with IPs and refused every SSH login. Root’s authorized_keys existed but was empty. Nesting ssh_authorized_keys under users: - name: root doesn&#39;t reliably write the key on this image.</p><p><strong>Fix:</strong> use the top-level directive in user-data:</p><pre>#cloud-config<br>disable_root: false<br>ssh_authorized_keys:<br>  - ssh-ed25519 AAAA... you@host</pre><p>After changing the seed, rebuild the ISO <strong>and</strong> tell cloud-init to reprocess it, because it won’t rerun on its own:</p><pre>cloud-init clean --logs &amp;&amp; reboot</pre><h3>Gotcha 2: duplicate graphics devices bricking VM starts</h3><p>Debian’s libvirt creates VMs with --graphics none. Retrying a failed --add-device --graphics left <strong>two</strong> VNC devices defined, and libvirt refuses to start a domain with duplicates.</p><p><strong>Fix:</strong> always remove-then-add.</p><pre>virt-xml &lt;domain&gt; --remove-device --graphics all<br>virt-xml &lt;domain&gt; --add-device --graphics vnc</pre><h3>Gotcha 3: the boot hang that looked like three separate bugs</h3><p>Two of three nodes intermittently hung forever at SeaBIOS’s <strong>“Probing EDD”</strong>. One node always booted fine. Cold-starting all three at once overwhelmed the 8 threads, and the timing-sensitive firmware routine hung on whichever VMs weren’t scheduled first.</p><p><strong>Fix:</strong> never cold-start multiple nodes together. Stagger boots by ~30 seconds.</p><pre>for vm in ceph1 ceph2 ceph3; do sudo virsh start $vm; sleep 30; done</pre><h3>Gotcha 4: one node quietly missing packages</h3><p>After the hard restarts, ceph2’s cloud-init packages: step had been interrupted, leaving it without podman and lvm2, both hard requirements for cephadm.</p><p><strong>Fix:</strong> don’t assume provisioning finished just because the VM is up. Verify on <strong>every</strong> node:</p><pre>rpm -q podman lvm2 chrony python3<br>systemctl is-active chronyd</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auobuGuaV3UFgbi8vDxLMA.png" /></figure><p>PR: ceph1 , ceph2 and ceph3 IP: 192.168.122.231/118/24</p><p>DR: cephdr IP: 192.168.122.39</p><h3>Part 6: Bootstrapping the primary cluster</h3><h3>Gotcha 5: the old cephadm install method is dead</h3><p>The classic curl of a cephadm script from Ceph&#39;s GitHub reef branch returned a 404. Reef had been archived, and current releases ship cephadm as a <strong>compiled binary</strong> rather than a script you pull from git. (Check the release status page at docs.ceph.com before you pin a version. This changes.)</p><p><strong>Fix:</strong> target a currently supported release (I used <strong>Tentacle, 20.2.x</strong>) and get the binary from Ceph’s download server:</p><pre>curl -sL https://download.ceph.com/rpm-tentacle/el9/noarch/cephadm -o /usr/sbin/cephadm<br>chmod +x /usr/sbin/cephadm<br>cephadm add-repo --release tentacle<br>cephadm install<br>cephadm install ceph-common<br>cephadm version     # confirm the real version before trusting anything else</pre><h3>Bootstrap ceph1</h3><pre>cephadm bootstrap --mon-ip 192.168.122.231 --skip-monitoring-stack</pre><p>--skip-monitoring-stack skips Prometheus, Grafana, and Alertmanager, which is worth it when RAM is tight.</p><h3>Add ceph2 and ceph3</h3><p>cephadm needs its SSH public key on each new host, then you register them:</p><pre>ssh-copy-id -f -i /etc/ceph/ceph.pub root@ceph2<br>ssh-copy-id -f -i /etc/ceph/ceph.pub root@ceph3</pre><pre>cephadm shell -- ceph orch host add ceph2 192.168.122.118<br>cephadm shell -- ceph orch host add ceph3 192.168.122.24<br>cephadm shell -- ceph orch host ls</pre><h3>Gotcha 6: cephadm wants the FQDN</h3><p>Later, ceph orch apply rbd-mirror --placement=&quot;ceph1&quot; failed with <strong>&quot;Unknown hosts&quot;</strong>. cephadm registers hosts by the name you gave host add, which in my case was the FQDN (ceph1.lab.local). It&#39;s a small thing that costs ten minutes every time you forget. Pick one naming convention at bootstrap and stick to it everywhere.</p><h3>Add the OSDs</h3><pre>cephadm shell -- ceph orch device ls<br>cephadm shell -- ceph orch apply osd --all-available-devices<br># or explicitly, one at a time:<br>cephadm shell -- ceph orch daemon add osd ceph1:/dev/vdb</pre><p>--all-available-devices is convenient for a lab, but it&#39;s a <em>standing</em> instruction: any new clean disk you attach later gets consumed automatically. If you don&#39;t want that, run ceph orch apply osd --all-available-devices --unmanaged=true afterwards. In production, write explicit OSD specs so placement is intentional.</p><p>Then verify:</p><pre>cephadm shell -- ceph -s<br>cephadm shell -- ceph osd tree</pre><blockquote><em>📸 </em><strong><em>Screenshot 5:</em></strong><em> </em><em>ceph -s showing </em><em>HEALTH_OK, 3 mons in quorum, mgr active/standby, and all OSDs up. 📸 </em><strong><em>Screenshot 6:</em></strong><em> </em><em>ceph orch host ls and </em><em>ceph osd tree, showing hosts and their OSDs.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze33JOwcQLO3DB2UWYHc9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEnjujv1WRhUf-ro9Uo0RQ.png" /><figcaption>PR Ceph cluster host inventory showing registered Ceph hosts, host status, and available daemon/service placement using ceph orch host ls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxrqEf9SlCAJZyH22xMwww.png" /></figure><h3>Part 7: The DR cluster, and the lesson that cost the most time</h3><p>The DR site is a <strong>separate cluster</strong>: its own fsid, mon, mgr, and OSDs. Hardware reality meant it got <strong>one node</strong>.</p><pre># on dr1<br>cephadm bootstrap --mon-ip 192.168.122.39 --skip-monitoring-stack</pre><h3>Gotcha 7: one host can never satisfy the default rule</h3><p>Fresh bootstrap, one node, one OSD: HEALTH_WARN … OSD count 1 &lt; osd_pool_default_size 3. I added more OSDs, which didn&#39;t help, because the default rule wants three <strong>hosts</strong>, and there was exactly one. Ceph was correctly refusing to pretend it had redundancy it didn&#39;t.</p><p>I had to shut the VM down, hand-craft extra virtual disks, and re-attach them. Then I wrote a <strong>custom CRUSH rule with </strong><strong>osd as the failure domain</strong>:</p><pre>ceph osd crush rule create-replicated replicated_osd default osd<br>ceph osd pool set .mgr crush_rule replicated_osd   # the auto-created .mgr pool uses the host rule too</pre><p>This is an honest, weaker guarantee (“no two copies on the same disk”) that fits a single-host lab. It would be unacceptable in production.</p><p><strong>The retrofit tax:</strong> every step here would have taken minutes if decided before the first pool existed. Done afterwards, it meant redoing OSD layout and rules against a cluster that was already live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLVmNu8ifoxeIIuTPWi2gA.png" /><figcaption>Ceph cluster overall status showing cluster health, MON quorum, MGR status, OSD availability, pool/PG status, and storage utilization using ceph -s.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDRz9UwRztz91-DseLiGdQ.png" /><figcaption>DR Ceph custom replicated_osd CRUSH rule showing OSD-level replica placement and the rule configuration used for the single-host DR lab.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*runteozqC4IFQXzs2GMKgA.png" /><figcaption>Ceph OSD hierarchy showing hosts, OSDs, weights, and their placement within the CRUSH hierarchy using ceph osd tree.</figcaption></figure><h3>Part 8: The pool and the RBD images</h3><p>Create the pool on <strong>both</strong> clusters with the <strong>same name</strong>:</p><pre># PR (3 hosts: the default host-level rule is fine)<br>ceph osd pool create libvirt-ud-pool 32<br># DR (single host: use the OSD-level rule)<br>ceph osd pool create libvirt-ud-pool 32 32 replicated_osd</pre><pre># both sites<br>ceph osd pool set libvirt-ud-pool size 3<br>ceph osd pool set libvirt-ud-pool min_size 2<br>ceph osd pool application enable libvirt-ud-pool rbd<br>rbd pool init libvirt-ud-pool</pre><p><strong>A note on renames.</strong> My pool didn’t start life with this name. ceph osd pool rename &lt;old&gt; &lt;new&gt; works cleanly and moves no data, but everything referencing the old name <em>by string</em> (cephx caps, libvirt XML, scripts) must be updated by hand. The pool doesn&#39;t care what it&#39;s called. Everything pointing at it does.</p><p>Create the images on PR. They’re 10 GiB each and back /data on the two Kubernetes VMs:</p><pre>rbd create libvirt-ud-pool/k8s-master-data --size 10G<br>rbd create libvirt-ud-pool/k8s-worker-data --size 10G<br>rbd ls -l libvirt-ud-pool<br>rbd info libvirt-ud-pool/k8s-master-data</pre><p>Create a dedicated cephx user for libvirt instead of using client.admin:</p><pre>ceph auth get-or-create client.libvirt \<br>  mon &#39;profile rbd&#39; \<br>  osd &#39;profile rbd pool=libvirt-ud-pool&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpDk4m_F08lJaF0gmM_mSg.png" /><figcaption>PR: Detailed OSD pool configuration and replication settings using ceph osd pool ls detail.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xpk89LdXS-iwwStiu0khew.png" /><figcaption>Pool and OSD Capacity Utilization (ceph df)on PR</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkAOWUUdDsqD5DlyLyeSQw.png" /><figcaption>DR: Detailed OSD pool configuration and replication settings using ceph osd pool ls detail.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmCGgzZ29tYhD0GiYMiV8Q.png" /><figcaption>DR Ceph cluster storage capacity, raw/usable space, and pool utilization displayed using ceph df.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d13UtnIj8Ql3aEqFmE85Bw.png" /><figcaption>DR Ceph RBD image inventory and k8s-master-data image metadata using rbd ls -l and rbd info.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Eqt2blzPE6SuuluuVa00g.png" /><figcaption>PR Ceph RBD image inventory and k8s-master-data image metadata using rbd ls -l and rbd info.</figcaption></figure><h3>Part 9: Getting a VM to boot from Ceph</h3><p>This is the part that proves you built something real: a VM whose disk lives entirely on the cluster, reached over the network.</p><h3>Gotcha 8: client and cluster versions must match</h3><p>My laptop’s stock ceph-common (Debian 12 ships a Pacific-era 16.2.x) choked on a Tentacle-generated keyring with Malformed input. Client tools have to match, or at least be compatible with, the cluster.</p><p><strong>Fix:</strong> add the matching upstream repo on the hypervisor:</p><pre>wget -q -O- https://download.ceph.com/keys/release.asc | sudo gpg --dearmor -o /etc/apt/keyrings/ceph.gpg<br>echo &quot;deb [signed-by=/etc/apt/keyrings/ceph.gpg] https://download.ceph.com/debian-tentacle/ $(lsb_release -sc) main&quot; | sudo tee /etc/apt/sources.list.d/ceph.list<br>sudo apt update &amp;&amp; sudo apt install -y ceph-common<br>ceph --version</pre><h3>Gotcha 9: libvirt’s RBD storage-pool driver clashes with a newer Ceph</h3><p>The documented path, a libvirt &lt;pool type=&#39;rbd&#39;&gt;, failed with failed to set RADOS option: auth_supported. Debian&#39;s older libvirt (9.0) tried to set a legacy option that Tentacle&#39;s stricter librados rejects. This is a known old-libvirt/new-Ceph clash, not a config mistake.</p><p><strong>Fix:</strong> skip the storage-pool layer and attach the RBD image as a <strong>direct network disk</strong> in the domain XML. This is what libvirt does underneath anyway, and it’s a perfectly production-valid pattern.</p><p>First, give libvirt the cephx key as a secret:</p><pre>cat &gt; secret-pr.xml &lt;&lt;&#39;EOF&#39;<br>&lt;secret ephemeral=&#39;no&#39; private=&#39;no&#39;&gt;<br>  &lt;uuid&gt;PUT-A-UUID-HERE&lt;/uuid&gt;<br>  &lt;usage type=&#39;ceph&#39;&gt;&lt;name&gt;client.libvirt (PR)&lt;/name&gt;&lt;/usage&gt;<br>&lt;/secret&gt;<br>EOF<br>sudo virsh secret-define secret-pr.xml<br>sudo virsh secret-set-value --secret PUT-A-UUID-HERE \<br>  --base64 &quot;$(ssh root@ceph1 &#39;cephadm shell -- ceph auth get-key client.libvirt&#39; | tr -d &#39;\r\n&#39;)&quot;</pre><p>Then the disk definition:</p><pre>&lt;disk type=&#39;network&#39; device=&#39;disk&#39;&gt;<br>  &lt;driver name=&#39;qemu&#39; type=&#39;raw&#39;/&gt;<br>  &lt;auth username=&#39;libvirt&#39;&gt;<br>    &lt;secret type=&#39;ceph&#39; uuid=&#39;PUT-A-UUID-HERE&#39;/&gt;<br>  &lt;/auth&gt;<br>  &lt;source protocol=&#39;rbd&#39; name=&#39;libvirt-usd-pool/k8s-master-data&#39;&gt;<br>    &lt;host name=&#39;192.168.122.231&#39; port=&#39;6789&#39;/&gt;<br>    &lt;host name=&#39;192.168.122.118&#39; port=&#39;6789&#39;/&gt;<br>    &lt;host name=&#39;192.168.122.24&#39;  port=&#39;6789&#39;/&gt;<br>  &lt;/source&gt;<br>  &lt;target dev=&#39;vdb&#39; bus=&#39;virtio&#39;/&gt;<br>&lt;/disk&gt;</pre><h3>Gotcha 10: the CPU model that ate an evening</h3><p>With the RBD disk wired up, the VM hung at “Probing EDD” <em>again</em>. Same symptom, but this time isolating it from contention didn’t help. The cause: my hand-written domain XML had no &lt;cpu&gt; element, so QEMU silently fell back to the minimal qemu64 model. A bare-bones CPU plus a network-backed disk (higher latency than local qcow2) tripped the same SeaBIOS weakness.</p><p><strong>Fix:</strong></p><pre>&lt;cpu mode=&#39;host-passthrough&#39;/&gt;</pre><p>It booted clean on the first try. localhost login: on a VM whose data disk lives on a 3-node Ceph cluster.</p><p>Inside the guest, format and mount the RBD-backed disk (and <strong>put it in </strong><strong>/etc/fstab</strong>. Remember this line, because it comes back later):</p><pre>mkfs.ext4 /dev/vdb<br>mkdir -p /data<br>blkid /dev/vdb                      # note the UUID<br>echo &#39;UUID=&lt;uuid-from-blkid&gt;  /data  ext4  defaults,nofail  0 2&#39; &gt;&gt; /etc/fstab<br>mount -a &amp;&amp; df -h /data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJL9vRVaLIHOMmEP9YqLcA.png" /><figcaption>k8s-master and k8s-worker vm libvirt domain XML showing the Ceph RBD-backed vdb disk, including the RBD pool/image, Ceph monitor endpoints, authentication secret, and VirtIO disk configuration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cV7gvY4ZhW1bZy6dMO_FxA.png" /><figcaption>nside k8s-master, lsblk -f and df -h /data showing the Ceph-backed vdb disk, its filesystem, and the mounted /data filesystem.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnTi7QljFs_JZ-2mp4j3cQ.png" /><figcaption>nside k8s-worker, lsblk -f and df -h /data showing the Ceph-backed vdb disk, its filesystem, and the mounted /data filesystem.</figcaption></figure><h3>Part 10: RBD mirroring, the DR engine</h3><h3>What we’re using</h3><p><strong>Journal-based mirroring</strong>: writes are recorded in an RBD journal and replayed asynchronously at the remote site, giving crash-consistent replication. It requires the exclusive-lock feature, and journaling is enabled automatically when you turn on per-image journal mirroring. Because it&#39;s asynchronous, your RPO is small but <strong>not zero</strong>.</p><h3>Step 1: enable mirroring on the pool (both clusters)</h3><pre>rbd mirror pool enable libvirt-usd-pool image</pre><p>image mode means you choose which images are mirrored, which is right when a pool holds other things too.</p><h3>Step 2: deploy rbd-mirror on both sides</h3><p>Two-way replication needs the daemon on both clusters, and it’s what makes failback possible. Use the <strong>FQDN</strong> (Gotcha 6):</p><pre># PR<br>ceph orch apply rbd-mirror --placement=&quot;ceph1.lab.local&quot;<br># DR<br>ceph orch apply rbd-mirror --placement=&quot;dr1.lab.local&quot;<br>ceph orch ps --daemon-type rbd-mirror</pre><h3>Step 3: peer the clusters with a bootstrap token</h3><pre># on PR<br>rbd mirror pool peer bootstrap create --site-name pr libvirt-usd-pool &gt; /tmp/token</pre><pre># copy /tmp/token to the DR node, then on DR<br>rbd mirror pool peer bootstrap import --site-name dr --direction rx-tx libvirt-usd-pool /tmp/token</pre><p>--direction rx-tx on the import makes it two-way. Without it the peering is one-way (PR → DR only).</p><h3>Gotcha 11: “No such file or directory” that isn’t about files</h3><p>bootstrap import kept failing with a maddeningly generic (2) No such file or directory. Running with --debug-rbd=20 buried the real message in the trace: <strong>remote pool does not exist</strong>. I&#39;d named the DR pool libvirt-usd-pool-dr, one suffix off from the primary. rbd-mirror requires the <strong>exact same pool name on both sites</strong>. I renamed it and peering succeeded immediately.</p><blockquote><em>When a Ceph error looks unrelated to what you did, turn up debug (</em><em>--debug-rbd=20) and read the trace.</em></blockquote><h3>Step 4: enable mirroring per image</h3><pre>rbd mirror image enable libvirt-swift-pool/k8s-master-data journal<br>rbd mirror image enable libvirt-swift-pool/k8s-worker-data journal<br>rbd info libvirt-swift-pool/k8s-master-data</pre><p>rbd info should now show journaling among the features, plus mirroring state: enabled and mirroring mode: journal.</p><h3>Step 5: prove replication before you trust it</h3><pre>rbd mirror pool status libvirt-swift-pool --verbose<br>rbd mirror image status libvirt-swift-pool/k8s-master-data</pre><p>On the DR side you want to see up+replaying with live byte/sec stats, and entries_behind_primary: 0 means nothing is waiting to be replayed. I used exactly that as a gate in my automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5wE1D1PAP-Um9Hr_L1f4w.png" /><figcaption>BD mirroring configuration and verbose pool replication status on both PR and DR Ceph clusters, confirming the peer relationship and active replication for the mirrored pool.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJQIMxNRhRnLYR_oF7Djsg.png" /><figcaption>BD mirroring configuration and verbose pool replication status on both PR and DR Ceph clusters, confirming the peer relationship and active replication for the mirrored pool.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3a_pO1glWWqH6u7glRtClw.png" /><figcaption>BD mirroring configuration and verbose pool replication status on both PR and DR Ceph clusters, confirming the peer relationship and active replication for the mirrored pool.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROAVktT5gTz_Rkoz1W7J1Q.png" /><figcaption>BD mirroring configuration and verbose pool replication status on both PR and DR Ceph clusters, confirming the peer relationship and active replication for the mirrored pool.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-inefwlDgN5jmrHAbp2_kg.png" /><figcaption>RBD mirror status for k8s-master-data showing up+replaying state with replication lag at 0, confirming that both images are synchronized between PR and DR.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Glo3u6wBQI1ST4e0dpsRMw.png" /><figcaption>RBD mirror status for k8s-master-data showing up+replaying state with replication lag at 0, confirming that both images are synchronized between PR and DR.</figcaption></figure><h3>Important: mirroring is not backup</h3><p>Journal mirroring faithfully replicates <strong>everything</strong>, including accidental deletions and corruption. DR protects you from losing a site. It does not protect you from rm -rf. Keep snapshots or backups too.</p><h3>Part 11: The failover, state machine and all</h3><p>A site switch is <strong>not</strong> promote DR; start VM. Four independent layers must agree:</p><pre>Ceph replication → RBD image ownership → libvirt storage config → guest OS/app</pre><p>The workflow, with a gate at every stage:</p><pre>Stop K8s VMs → verify &quot;shut off&quot; → verify replication is current<br>   → demote PR images → wait for propagation → promote DR images<br>   → verify DR = PRIMARY → rewrite libvirt XML (monitor + secret)<br>   → start VMs → final validation</pre><p>The design choice that kept it clean: I <strong>never detached or reattached the disk</strong>. With the VM shut off, I edited its <em>persistent</em> libvirt XML so vdb points at the DR monitor and DR secret, while keeping the same target (vdb) and image name.</p><p>Both changes matter. The PR and DR clusters have different authentication, so switching only the monitor endpoint isn’t enough. The secret UUID has to switch too.</p><h3>The XML rewrite</h3><pre># switch_site.py &lt;dumped-xml&gt; &lt;mon-ip&gt; &lt;secret-uuid&gt;<br>import sys, xml.etree.ElementTree as ET<br>path, mon_ip, secret_uuid = sys.argv[1:4]<br>tree = ET.parse(path); root = tree.getroot()<br>for disk in root.findall(&quot;./devices/disk&quot;):<br>    src = disk.find(&quot;source&quot;)<br>    if src is not None and src.get(&quot;protocol&quot;) == &quot;rbd&quot;:<br>        for h in src.findall(&quot;host&quot;):<br>            src.remove(h)<br>        ET.SubElement(src, &quot;host&quot;, name=mon_ip, port=&quot;6789&quot;)<br>        disk.find(&quot;auth/secret&quot;).set(&quot;uuid&quot;, secret_uuid)<br>tree.write(path)</pre><pre>sudo virsh dumpxml --inactive k8s-master &gt; /tmp/k8s-master.xml<br>python3 switch_site.py /tmp/k8s-master.xml 192.168.122.39 &lt;DR-SECRET-UUID&gt;<br>sudo virsh define /tmp/k8s-master.xml</pre><p>(The OS disk stays a local qcow2 and is skipped by the protocol == &quot;rbd&quot; check. In this lab only the <strong>data disk</strong> fails over. A real DR design also needs a plan for the OS disk: boot from mirrored RBD, or rebuild from IaC/images.)</p><h3>The automation, and the six problems it taught me</h3><p>My first attempts were a wall of small failures. Each one is a lesson.</p><p><strong>1. </strong><strong>virsh permissions.</strong> The script ran as a normal user; the libvirt connection needed elevated privileges, so virsh domstate returned nothing and the script saw UNKNOWN. <strong>Lesson:</strong> use the same privilege level that owns the libvirt connection, via a wrapper (sudo virsh &quot;$@&quot;).</p><p><strong>2. </strong><strong>cephadm wasn&#39;t on the host.</strong> The script ran on the laptop, but cephadm lived on the Ceph nodes. The laptop is an <em>orchestrator</em>, not a Ceph admin host. <strong>Lesson:</strong> the controller orchestrates; Ceph nodes do Ceph work, over SSH.</p><p><strong>3. </strong><strong>|| true hid the real error.</strong> get_status() { ceph_pr &quot;$1&quot; 2&gt;/dev/null || true; } looked defensive, but a failed command became an empty string, and empty output is indistinguishable from &quot;not primary.&quot; <strong>Lesson:</strong> safety automation must fail loudly with the real reason.</p><p><strong>4. </strong><strong>sudo -n is not a universal test.</strong> sudo -n virsh … could work while sudo -n true prompted for a password. <strong>Lesson:</strong> don&#39;t assume one blanket privilege check represents every command you&#39;ll run.</p><p><strong>5. Interrupted failover state.</strong> My run died after demoting the source, leaving <strong>both</strong> images non-primary, which is neither normal operation nor a completed failover. <strong>Lesson:</strong> a failover script must understand <em>states</em>. “Source already non-primary” and “target already primary” are valid, resumable states, not errors. A script that can’t survive being re-run after a partial failure isn’t a failover script, it’s a liability.</p><p><strong>6. Demotion propagation.</strong> Promoting DR immediately after demoting PR failed with <em>“image is primary within a remote cluster or demotion is not propagated yet.”</em> Distributed systems have propagation delay. <strong>Lesson:</strong> wait, verify, retry the normal promote. I deliberately avoided --force (which is for a genuinely dead primary and risks split-brain).</p><p>There was also one genuinely funny bug: my status-parsing regex checked a variable <em>before</em> the command that set it had run, so every precheck looked “unknown” while Ceph was perfectly healthy. And entries_behind_primary is state-dependent: require it while the image is PRIMARY, and check ownership instead once it&#39;s demoted.</p><h3>A simplified sketch of the final logic</h3><p>This is trimmed from my script for readability:</p><pre>POOL=libvirt-usd-pool<br>IMAGES=(k8s-master-data k8s-worker-data)</pre><pre>vsh()     { sudo virsh &quot;$@&quot;; }<br>ceph_pr() { ssh -o BatchMode=yes -o ConnectTimeout=10 &quot;$PR_MON1&quot; &quot;sudo -n cephadm shell -- $*&quot;; }<br>ceph_dr() { ssh -o BatchMode=yes -o ConnectTimeout=10 &quot;$DR_MON&quot;  &quot;sudo -n cephadm shell -- $*&quot;; }<br>die()     { echo &quot;ABORT: $*&quot; &gt;&amp;2; exit 1; }</pre><pre># PRIMARY | NON-PRIMARY -- and fail loudly if we can&#39;t tell<br>mirror_state() {<br>  local out<br>  out=$(&quot;$1&quot; rbd info &quot;$POOL/$2&quot;) || die &quot;cannot query $2 via $1&quot;<br>  grep -q &#39;mirroring primary: true&#39; &lt;&lt;&lt;&quot;$out&quot; &amp;&amp; echo PRIMARY || echo NON-PRIMARY<br>}</pre><pre># 1. VMs must be off<br>for vm in k8s-master k8s-worker; do<br>  [[ $(vsh domstate &quot;$vm&quot;) == &quot;shut off&quot; ]] || die &quot;$vm is not shut off&quot;<br>done</pre><pre>for img in &quot;${IMAGES[@]}&quot;; do<br>  # 2. Only while the source is still primary: check lag, then demote<br>  if [[ $(mirror_state ceph_pr &quot;$img&quot;) == PRIMARY ]]; then<br>    ceph_pr rbd mirror image status &quot;$POOL/$img&quot; | grep -Eq &#39;entries_behind_primary&quot;?:\s*0&#39; \<br>      || die &quot;$img is still behind the primary&quot;<br>    ceph_pr rbd mirror image demote &quot;$POOL/$img&quot;<br>  fi</pre><pre>  # 3. Normal promote with retries -- no --force<br>  for attempt in {1..12}; do<br>    [[ $(mirror_state ceph_dr &quot;$img&quot;) == PRIMARY ]] &amp;&amp; break<br>    ceph_dr rbd mirror image promote &quot;$POOL/$img&quot; || sleep 10<br>  done<br>  [[ $(mirror_state ceph_dr &quot;$img&quot;) == PRIMARY ]] || die &quot;DR promote failed for $img&quot;<br>done</pre><pre># 4. Rewrite libvirt XML (switch_site.py), define, start, final verification...</pre><h3>The result</h3><p>Both PR images became PRIMARY (entries_behind_primary: 0 beforehand), both VM definitions pointed at the PR monitor and PRsecret, both VMs booted, and the final checks still showed DR as primary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yO6Xs7tmxaYe4Ub7iPkLVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSSQSe8E2yONjr7k9p1cmw.png" /></figure><h3>Part 12: The anticlimactic finale</h3><p>After all that, my test file wasn’t in /data on the failed-over VM. Brief panic.</p><pre>lsblk -f</pre><p>showed vdb with an ext4 filesystem and the expected UUID, but <strong>no mountpoint</strong>. /dev/vdb was attached and replicated perfectly. It just wasn&#39;t in /etc/fstab, so after a fresh boot /data was an empty directory on the <em>root</em> disk. I mounted it manually, and the original file was right there, fully intact.</p><p><strong>The replication had worked flawlessly the whole time.</strong> The last step of the entire saga was a boring, ordinary Linux mount-point mistake. Which felt appropriate.</p><p>The lesson is that <strong>Ceph-level success and guest-level data availability are separate validation layers</strong>. When the app can’t see its data, walk the stack:</p><pre>VM running? → vdb attached? → vdb the expected RBD? → filesystem present?<br>   → filesystem mounted? → mounted filesystem contains data?</pre><h3>Part 13: Failback (DR → PR)</h3><p>Failback is the same state machine in reverse:</p><pre>Stop VMs → verify shut off → verify DR replication is current<br>   → demote DR → wait for propagation → promote PR → verify PR = PRIMARY<br>   → rewrite libvirt XML back to PR monitors + PR secret → start VMs → validate</pre><p>The governing principle:</p><blockquote><strong><em>Never promote the new site until the old primary has been safely demoted and the demotion has propagated.</em></strong></blockquote><p>This is why two-way mirroring, with rbd-mirror running on both clusters, matters. After failover, the old PR side must be able to <em>replay</em> from DR, or there&#39;s nothing to fail back to.</p><h3>Ceph vs. Kubernetes: the mapping that made it click</h3><p>If you know Kubernetes, most of Ceph’s magic stops being magic:</p><ul><li><strong>Mons (quorum)</strong> ≈ <strong>etcd</strong>: the source of truth, needs a majority.</li><li><strong>Mgr + orchestrator</strong> ≈ <strong>control plane / controllers</strong>: acts on cluster state.</li><li><strong>OSD</strong> ≈ <strong>Pod</strong>: the unit that does the work.</li><li><strong>OSD dies → re-replication</strong> ≈ <strong>Pod dies → rescheduled</strong>: self-healing with no human.</li><li><strong>CRUSH rule</strong> ≈ <strong>(anti-)affinity</strong>: declarative placement.</li><li><strong>Pool</strong> ≈ <strong>Namespace + StorageClass</strong>, roughly: a logical grouping with its own policy.</li><li><strong>rbd-mirror</strong> ≈ <strong>multi-cluster replication</strong>: async copy to a second site.</li></ul><p>Same instincts, same reason both exist: a single machine dying should not be a special, human-intervention-required event.</p><h3>The checklist</h3><ol><li>Decide your <strong>failure domains</strong> (hosts, racks, sites) <strong>before</strong> creating a single pool.</li><li>Choose your <strong>replication factor from the failure domains you really have</strong>, not the other way around.</li><li>Size <strong>RAM per OSD</strong> generously, and don’t let anything else compete with Ceph daemons.</li><li><strong>Pin a release</strong>, know its EOL date, and own the upgrade cadence. Upgrades are one-way.</li><li>Match <strong>client tool versions</strong> to the cluster version.</li><li>Give replication its <strong>own network</strong>, and get <strong>DNS/hosts and time sync</strong> right before bootstrap.</li><li>Pick <strong>one naming convention (FQDN)</strong> for hosts and stick to it.</li><li>If DR matters, use <strong>identical pool names</strong> on both sites from day one, and remember mirroring is <em>not</em> backup.</li><li>Run rbd-mirror on <strong>both</strong> sites if you want to be able to fail back.</li><li><strong>Never assume promote/demote is instant.</strong> Check state, don’t guess. Avoid --force unless the primary is truly gone.</li><li>Write failover automation to be <strong>safely re-runnable</strong> after a partial failure, and never hide errors with || true.</li><li>Don’t forget <strong>/etc/fstab</strong> (with nofail) for anything that must survive a reboot on the other side.</li><li>Don’t cold-start everything at once on constrained hosts, and treat your RAM budget as load-bearing.</li></ol><h3>Closing thought</h3><p>None of these bugs were exotic. Every one was a small, specific “oh, <em>that’s</em> what’s going on” problem you only find by building the thing, not by reading docs or watching a demo. If you write runbooks for infrastructure you’ve never personally broken and rebuilt, you’re one weird production incident away from finding out the hard way. Better to find out on a laptop, on a Saturday, with nothing real at stake.</p><p>HEALTH_OK on both sites, replication caught up, VMs running on DR. Not bad for 16 GB of RAM and a weekend.</p><p><strong>Next up (Part 2):</strong> Kubernetes on top of this storage foundation, and how it behaves during a PR/DR switch.</p><h3>References</h3><ul><li>Ceph RBD Mirroring: <a href="https://docs.ceph.com/en/latest/rbd/rbd-mirroring/">https://docs.ceph.com/en/latest/rbd/rbd-mirroring/</a></li><li>Deploying a new cluster with cephadm: <a href="https://docs.ceph.com/en/tentacle/cephadm/install/">https://docs.ceph.com/en/tentacle/cephadm/install/</a></li><li>cephadm OSD service: <a href="https://docs.ceph.com/en/latest/cephadm/services/osd/">https://docs.ceph.com/en/latest/cephadm/services/osd/</a></li><li>rbd-mirror daemon: <a href="https://docs.ceph.com/en/latest/man/8/rbd-mirror/">https://docs.ceph.com/en/latest/man/8/rbd-mirror/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f9e4a5a2300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka vs RabbitMQ vs ActiveMQ: Picking the Right Backbone Before Production Picks It for You]]></title>
            <link>https://medium.com/@udayrajdhavande8/kafka-vs-rabbitmq-vs-activemq-picking-the-right-backbone-before-production-picks-it-for-you-d046d913b9b0?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d046d913b9b0</guid>
            <category><![CDATA[activemq]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 10:29:27 GMT</pubDate>
            <atom:updated>2026-07-21T10:29:27.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzJes8pzZXMKHz1MaEYa7w.png" /></figure><p>Every distributed systems team eventually has this conversation in a Slack thread at 11 PM: <em>“Why is our message queue falling over?”</em> Nine times out of ten, the answer isn’t “the broker is bad.” It’s “we picked the wrong broker for the job it’s actually doing.”</p><p>Message brokers aren’t interchangeable. They’re not “pick whichever one has the nicest dashboard.” Each of the big three — <strong>Kafka</strong>, <strong>RabbitMQ</strong>, and <strong>ActiveMQ</strong> — was built to solve a fundamentally different problem, and the failure mode you get from using the wrong one looks identical to “bad infrastructure” until you dig into the architecture.</p><p>Think of it like hiring for a restaurant. Kafka is the industrial kitchen’s conveyor belt — built to move enormous volume in one direction, reliably, and let you go back and replay the last three hours if the health inspector asks. RabbitMQ is the floor manager — routing each order to the exact station that needs it, juggling priorities, handling special requests. ActiveMQ is the maître d’ from an old-money restaurant that’s been running since 1962 — rigid, formal, speaks fluent “enterprise,” and refuses to change its dress code (JMS) even when the world moved on.</p><p>Let’s break down what each one actually is, where it breaks, and where I’ve seen each one used for real.</p><h3>Quick Overview</h3><p>Aspect <strong>Kafka</strong> <strong>RabbitMQ</strong> <strong>ActiveMQ</strong> Primary role Distributed event log AMQP message broker JMS message broker Throughput Millions of msgs/sec Tens of thousands/sec Thousands/sec Latency Low Very low (single-digit ms) Low Consumption model Pull-based Push-based Push-based Replay Yes — full history No — gone once consumed No (unless durable subs) Scaling Horizontal (partitions) Vertical + limited horizontal Vertical + clustered Best for Streaming, analytics, event sourcing Task queues, routing, RPC Legacy JMS, multi-protocol, transactional workflows</p><h3>Apache Kafka — The Conveyor Belt That Never Forgets</h3><p>Kafka isn’t really a “queue.” Calling it one is the first mistake people make. It’s a <strong>distributed commit log</strong>. Producers append records to a topic, the topic is sharded into partitions, and consumers read from those partitions at whatever pace they want — the messages don’t disappear when read. They sit there until retention expires, whether that’s a day or forever.</p><p>That single design decision — <em>messages aren’t deleted on consumption</em> — is why Kafka can do things RabbitMQ and ActiveMQ structurally cannot: replay. If a consumer service ships a bug that corrupts six hours of processed data, you don’t page anyone at 3 AM to write a backfill script. You just reset the consumer offset and replay the six hours.</p><h3>Where it actually earns its keep</h3><pre>Producer → Topic (Partition 0, 1, 2, 3) → Consumer Group<br>                    ↑<br>          Sequential disk writes,<br>          batched, replicated across brokers</pre><ul><li><strong>Fraud detection pipelines</strong>: millions of card-swipe events per second, scored in real time, with the raw event stream retained for compliance and model retraining.</li><li><strong>Clickstream / log aggregation</strong>: every microservice fires events into Kafka; a downstream consumer builds dashboards, another feeds a data lake, another triggers alerts — all reading the <em>same</em> stream independently.</li><li><strong>Event sourcing / CQRS</strong>: the log itself is the source of truth, and read models are just derived views rebuilt from replaying it.</li></ul><h3>Where it becomes a liability</h3><p>Kafka is operationally heavy. Partition rebalancing, consumer group lag, broker sizing, ZooKeeper/KRaft metadata — none of that is free. If your actual need is “run this background job reliably” or “route this message to the right of five services,” you’ve just signed up for a distributed systems project to solve a task-queue problem. That’s the classic anti-pattern: teams reach for Kafka because it’s the trendy name, then spend six months debugging consumer lag for a workload that RabbitMQ would’ve handled with a five-line config.</p><blockquote><strong><em>Red Pill:</em></strong><em> Kafka doesn’t push messages to you — it waits for you to come and get them. If your consumer is slow, Kafka won’t notice or care; it’ll happily keep piling up on disk. The pain shows up downstream as consumer lag, not broker alerts. Monitor lag, not just broker health, or you’ll find out about the backlog from an angry stakeholder instead of Grafana.</em></blockquote><h3>RabbitMQ — The Floor Manager Who Routes Everything Correctly</h3><p>RabbitMQ speaks <strong>AMQP</strong> and is written in Erlang — the same language family built for telecom switches that are legally not allowed to go down. Its model is <strong>Producer → Exchange → Queue → Consumer</strong>, and the exchange is where the real intelligence lives.</p><pre>Producer → Exchange → [routing logic] → Queue A → Worker Pool<br>                              ↓<br>                          Queue B → Analytics Service<br>                              ↓<br>                          Queue C → Notification Service</pre><p>An exchange can route by exact key (direct), wildcard pattern (topic), broadcast to everyone (fanout), or by inspecting headers. That means one “order.created” event can fan out to fulfillment, analytics, and notifications simultaneously, with per-route filtering — something that requires real engineering effort to replicate in Kafka.</p><h3>Where it actually earns its keep</h3><ul><li><strong>Background job processing</strong>: image resizing, PDF generation, email dispatch — dump the job on a queue, scale worker pods based on queue depth.</li><li><strong>Request-reply / RPC over messaging</strong>: correlation IDs let a service publish a request and wait for a specific reply, without building your own polling logic.</li><li><strong>Payment and order pipelines needing conditional fan-out</strong>: route a single payment event to fraud-check, ledger update, and customer notification — each with different retry and priority semantics.</li></ul><h3>Where it becomes a liability</h3><p>RabbitMQ isn’t a log. Once a message is acked and consumed, it’s gone. If you’re trying to use it as an audit trail or a place to “replay history for a new consumer,” you’ve picked the wrong tool — that consumer will simply never see anything that happened before it joined. And at genuinely massive throughput (Kafka’s home turf), RabbitMQ starts hitting ceilings that Erlang’s clustering model wasn’t built to push past.</p><blockquote><strong><em>Red Pill:</em></strong><em> A dead-letter queue isn’t a bug tracker, it’s a symptom collector. If messages are piling up in your DLQ, someone downstream is failing silently and the queue is just the messenger. I’ve seen teams treat DLQ growth as “normal background noise” for weeks before realizing a consumer had been crash-looping on a schema mismatch the whole time.</em></blockquote><h3>Apache ActiveMQ — The Old-Money Broker That Refuses to Retire</h3><p>ActiveMQ is the oldest of the three, built around <strong>JMS (Java Message Service)</strong>. It feels like enterprise middleware because it <em>is</em> enterprise middleware — this is the broker you find sitting quietly in the middle of a core banking stack, doing the unglamorous work of guaranteeing that a loan approval message makes it from the verification service to the risk engine to the disbursement system, in order, exactly once, even if a node dies mid-transaction.</p><p>There are two live flavors — <strong>ActiveMQ Classic</strong> and <strong>ActiveMQ Artemis</strong> (a ground-up rewrite) — sharing a name but not much else under the hood, which trips people up when they compare benchmark numbers without checking which one was tested.</p><h3>Where it actually earns its keep</h3><pre>Verification Service → ActiveMQ (JMS Queue) → Risk Assessment<br>                                            → Approval Workflow<br>                                            → Disbursement<br>      (durable, transactional, ordered, guaranteed delivery)</pre><ul><li><strong>Multi-stage financial workflows</strong>: verification → risk scoring → approval, where losing a message mid-chain isn’t an inconvenience, it’s a compliance incident.</li><li><strong>Multi-protocol bridging</strong>: AMQP, MQTT, STOMP, and OpenWire out of the box, which matters when you’re bolting IoT telemetry devices onto a stack that also talks JMS to a 15-year-old Java monolith.</li><li><strong>Legacy integration</strong>: bridging a Spring/Java EE core system to newer services without rewriting the core.</li></ul><h3>Where it becomes a liability</h3><p>It won’t scale the way Kafka or RabbitMQ can, and its clustering story is meaningfully more operationally involved than Kafka’s partition model. If you’re building a greenfield cloud-native system with no legacy JMS dependency, reaching for ActiveMQ is usually a sign someone on the team is more comfortable with what they know than with what the workload needs.</p><blockquote><strong><em>Red Pill:</em></strong><em> In transactional financial workflows, “fast” is not the top requirement — “exactly-once and in-order” is. I’ve watched teams try to shave milliseconds off a banking message pipeline by relaxing acknowledgment settings, not realizing they’d just traded guaranteed delivery for a marginal latency win nobody downstream actually needed. Measure what the workflow requires before you optimize what’s measurable.</em></blockquote><h3>Decision Framework</h3><pre>Need event replay, long retention, or stream processing?<br>        → Kafka</pre><pre>Need complex conditional routing, task queues, or RPC?<br>        → RabbitMQ</pre><pre>Working with legacy JMS, need multi-protocol support,<br>or need airtight transactional guarantees?<br>        → ActiveMQ</pre><pre>Need millions of events/sec with fault tolerance?<br>        → Kafka</pre><pre>Need single-digit millisecond latency at moderate volume?<br>        → RabbitMQ</pre><h3>Real-World Scenarios</h3><p>Scenario Best Choice Why E-commerce order processing RabbitMQ Conditional fan-out to inventory, payment, shipping Real-time fraud detection Kafka Millions of events/sec, stream analytics, replay for retraining Core banking system integration ActiveMQ JMS-native, guaranteed delivery, transactional Clickstream / feed aggregation Kafka Massive volume, long retention, ML reprocessing Image/video processing jobs RabbitMQ Worker pools, priority queues, retries IoT sensor telemetry ActiveMQ (moderate scale) or Kafka (massive scale) MQTT support vs. raw throughput</p><h3>The Actual Takeaway</h3><p>None of these three is “the best message broker.” That question is as meaningless as asking whether a scalpel is “better” than a sledgehammer. The real question is always: <em>does this workload need replay, routing, or guaranteed transactional delivery?</em> Answer that first, and the broker picks itself.</p><p>Most mature organizations don’t pick one — they run two or three, each for the job it’s actually good at: Kafka as the streaming backbone, RabbitMQ for microservice task coordination, ActiveMQ quietly holding together the legacy core that nobody’s allowed to touch. The mistake isn’t running more than one broker. The mistake is running the wrong one and calling it “technical debt” instead of “a design decision made under time pressure that never got revisited.”</p><p>Pick the tool for the shape of the problem, not the shape of the résumé you want to build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d046d913b9b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Retyping the Same Diagnostic Commands: Build Your Own]]></title>
            <link>https://medium.com/@udayrajdhavande8/stop-retyping-the-same-diagnostic-commands-build-your-own-761f593526d8?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/761f593526d8</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 07:42:04 GMT</pubDate>
            <atom:updated>2026-07-21T07:42:04.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXiW2Tim3vDCJxmmVSVDoQ.png" /></figure><p>Every production incident starts the same way. Something’s slow, something’s down, or a pager just went off — and the first sixty seconds are spent typing the same handful of commands you’ve typed a thousand times before: kubectl get pods -o wide, free -h, df -h, kubectl describe pod &lt;name-you-have-to-scroll-up-to-copy&gt;.</p><p>A bouncer at a club doesn’t pat down every guest from scratch every single night — they’ve got a routine, a fixed sequence of checks they run without thinking. That’s what a good SRE’s toolbox should look like: not clever one-off commands typed under pressure, but a fixed, tested, muscle-memory routine that runs the same way every time.</p><p>This article covers exactly how to build that — from a single kubectl shortcut, to a full system sanity-check that diagnoses <em>why</em> a filesystem is filling up, not just <em>that</em> it is.</p><h3>Two Mechanisms, Not One</h3><p>Before writing a single script, understand there are two different ways to create a custom command, and they behave differently.</p><p><strong>Shell alias or function</strong> — defined in ~/.bashrc or ~/.zshrc. Lives only in your interactive shell. The moment you SSH into a different box, or a script runs under /bin/sh, it&#39;s gone. Zero process overhead, but zero portability.</p><p><strong>Standalone executable in </strong><strong>/usr/local/bin</strong> — a real file with a shebang line and execute permission, sitting on $PATH. Works for every user on that box, in cron jobs, in CI runners, in any shell. Slightly more overhead (a new process forks), which is completely irrelevant at human typing speed.</p><pre>$ echo $PATH<br>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin</pre><p>/usr/local/bin is on that list by default on RHEL, Ubuntu, and nearly every mainstream distro — which is exactly why it&#39;s the convention for &quot;commands the sysadmin/DevOps team installed,&quot; as opposed to /usr/bin, which is reserved for what the package manager owns.</p><p><strong>Rule of thumb:</strong> if it’s a plain substitution with no argument parsing, an alias is fine. The moment you need to accept an argument, branch on a condition, or chain multiple tools together, write a script.</p><h3>The Generic Recipe</h3><p>Every example in this article — kubectl shortcuts, regex-based lookups, the sanity check — follows the same underlying steps. Once you internalize this sequence, you can turn <em>any</em> repetitive command into a custom one in under two minutes.</p><p><strong>1. Spot the repetition.</strong> If you’ve typed the same command, or the same three-command sequence, more than twice in a week, it’s a candidate. Don’t pre-optimize commands you run once a month.</p><p><strong>2. Decide: alias or script?</strong> No arguments, no logic → a one-line alias in ~/.bashrc is enough. Needs an argument, a condition, or chains multiple tools → write a script.</p><p><strong>3. Pick the name carefully.</strong> Short, memorable, and — this matters — check it doesn’t already exist:</p><pre>which &lt;name&gt;<br>type &lt;name&gt;</pre><p>Naming your script test, info, or check will silently shadow or collide with existing binaries and built-ins. Prefer something specific: podinfo, not info.</p><p><strong>4. Create the file in </strong><strong>/usr/local/bin.</strong></p><pre>sudo vi /usr/local/bin/&lt;name&gt;</pre><p><strong>5. Start with a shebang, then the logic.</strong></p><pre>#!/bin/bash<br># what this command does, in one line<br>&lt;your command or pipeline&gt;</pre><p>Use &quot;$@&quot; if you want to forward extra arguments the caller passes; use $1, $2 if you want named, specific arguments.</p><p><strong>6. Make it executable.</strong></p><pre>sudo chmod +x /usr/local/bin/&lt;name&gt;</pre><p><strong>7. Confirm it resolves.</strong></p><pre>which &lt;name&gt;</pre><p>If nothing prints, /usr/local/bin isn&#39;t on your $PATH — check echo $PATH and add it in your shell&#39;s profile if it&#39;s missing (rare, but happens on minimal container base images).</p><p><strong>8. Test it exactly the way you’ll actually use it</strong> — with the flags, arguments, and edge cases (empty input, no matches, multiple matches) you expect in a real incident, not just the happy path.</p><p><strong>9. Put it under version control.</strong> A dotfiles repo or a config-management role, not a one-off file that exists only on the box you happened to be SSH’d into when you wrote it. This is the difference between a personal trick and a team capability — more on why that matters at the end.</p><p>That’s the whole recipe. Everything from here is that same nine-step loop, applied to progressively more useful problems.</p><h3>Level 1: Simple Substitutions</h3><p>The lowest-effort win — wrapping a long, frequently-typed command behind a short name.</p><pre>#!/bin/bash<br># /usr/local/bin/pods<br>kubectl get pods -o wide &quot;$@&quot;</pre><pre>#!/bin/bash<br># /usr/local/bin/nodes<br>kubectl get nodes -o wide &quot;$@&quot;</pre><p>The &quot;$@&quot; at the end matters — it forwards any extra flags you pass, so pods -n kube-system still works exactly like the full kubectl command would.</p><pre>chmod +x /usr/local/bin/pods /usr/local/bin/nodes</pre><p>That’s the entire investment. Two files, one chmod, and two commands you&#39;ll type for the rest of your career.</p><h3>Level 2: Commands That Take Arguments</h3><p>This is where a plain alias stops being enough. Say you want a single command that resolves a pod by a regex pattern — not the exact name — and pulls back its image ID, the node it’s scheduled on, and when it was last started.</p><pre>#!/bin/bash<br># /usr/local/bin/podinfo<br>REGEX=$1<br>pods | grep -E &quot;$REGEX&quot; | grep -v &quot;^NAME&quot; | awk &#39;{print $1}&#39; \<br>  | xargs -I {} kubectl get pod {} -o json | jq -r &#39;<br>  &quot;Namespace : \(.metadata.namespace)&quot;,<br>  &quot;Node      : \(.spec.nodeName)&quot;,<br>  &quot;Image ID  : \(.status.containerStatuses[0].imageID)&quot;,<br>  &quot;Started   : \(.status.startTime)&quot;<br>&#39;</pre><p>Walking through the pipeline:</p><ol><li>pods — our own Level 1 command, reused instead of retyping kubectl get pods -o wide.</li><li>grep -E &quot;$REGEX&quot; — filters to lines matching your pattern.</li><li>grep -v &quot;^NAME&quot; — drops the header row. Skip this and a loose regex can accidentally match the literal word NAME, and everything downstream breaks.</li><li>awk &#39;{print $1}&#39; — the -o wide output has multiple columns; this pulls just the first one, the pod name.</li><li>xargs -I {} kubectl get pod {} -o json — fetches full JSON for each matched pod.</li><li>jq -r &#39;...&#39; — extracts exactly the fields you care about, formatted.</li></ol><p>If your regex matches more than one pod, kubectl get pod {} -o json emits multiple JSON documents back-to-back, and jq processes each independently — so you get one info block per match, for free.</p><p>Same pattern, applied to describe:</p><pre>#!/bin/bash<br># /usr/local/bin/desc<br>REGEX=$1<br>pods | grep -E &quot;$REGEX&quot; | grep -v &quot;^NAME&quot; | awk &#39;{print $1}&#39; \<br>  | xargs -I {} kubectl describe pod {}</pre><p>Now desc api- describes every pod whose name starts with api-, without you ever copy-pasting a full pod name out of a get pods output again.</p><h3>Level 3: Beyond Kubernetes — a System Sanity Check</h3><p>The same principle — wrap a repetitive diagnostic sequence into one command — applies just as well outside Kubernetes. Every incident that starts with “the box feels slow” begins with the same three checks: memory, disk, and load. Instead of typing them one at a time, build a sanity-check command that runs all three, and — critically — goes one step further when disk usage looks bad, by identifying <em>what</em> is filling the filesystem instead of just reporting that it is.</p><pre>#!/bin/bash<br># /usr/local/bin/sanity-check</pre><pre>echo &quot;===== Memory =====&quot;<br>free -h</pre><pre>echo<br>echo &quot;===== Load Average =====&quot;<br>uptime</pre><pre>echo<br>echo &quot;===== Disk Usage =====&quot;<br>df -h</pre><pre># Auto-diagnose any filesystem above the threshold<br>THRESHOLD=80</pre><pre>echo<br>df -h --output=pcent,target | tail -n +2 | while read -r pcent mount; do<br>  usage=$(echo &quot;$pcent&quot; | tr -d &#39;% &#39;)<br>  if [ &quot;$usage&quot; -ge &quot;$THRESHOLD&quot; ]; then<br>    echo &quot;⚠️  $mount is at ${usage}% — top consumers:&quot;<br>    du -ahx &quot;$mount&quot; 2&gt;/dev/null | sort -rh | head -10<br>    echo<br>  fi<br>done</pre><p>What’s actually happening in the diagnosis loop:</p><ul><li>df -h --output=pcent,target prints just the usage percentage and mount point for every filesystem — no need to eyeball a wide table and mentally parse columns.</li><li>tail -n +2 drops the header row (same principle as grep -v &quot;^NAME&quot; earlier — always account for the header when piping tabular output into logic).</li><li>For every mount at or above THRESHOLD (80% here, tune to your environment), it runs du -ahx scoped to <em>that mount only</em> — the -x flag stops du from crossing into other mounted filesystems and wasting time walking directories that aren&#39;t the problem.</li><li>sort -rh sorts human-readable sizes numerically (plain sort -r would sort &quot;9.1G&quot; before &quot;10G&quot; alphabetically, which is wrong) and head -10 caps the output to the ten biggest offenders.</li></ul><p>Two production caveats worth knowing before you ship this:</p><p><strong>du can be slow on large filesystems.</strong> Walking a multi-terabyte mount with millions of small files can take minutes. If that&#39;s your environment, wrap the du call with timeout 30s, or reach for ncdu interactively instead of du in a script.</p><p><strong>Check inodes too, not just space.</strong> A filesystem can be at 40% space usage and still refuse to create new files if it’s run out of inodes — common with directories holding millions of tiny files, like session caches or log shards. Add:</p><pre>echo<br>echo &quot;===== Inode Usage =====&quot;<br>df -ih</pre><p>right after the disk usage block, and you’ve covered the two most common “disk full” false negatives in one command.</p><pre>chmod +x /usr/local/bin/sanity-check</pre><p>One command, and the first sixty seconds of almost every “the server feels off” incident are already done before you’ve finished opening a second terminal tab.</p><h3>Making It Repeatable, Not Personal</h3><p>Every example above solves the same underlying problem: turning a <em>sequence of steps you remember</em> into a <em>single command everyone can run</em>. That’s valuable — but only if it doesn’t stay locked inside your own terminal.</p><p><strong>Red Pill:</strong> this is exactly how tribal knowledge silos get built. A command that only exists on your laptop, undocumented, is a production incident waiting to happen — the day you’re on leave and a teammate is debugging a full disk at 2 AM without knowing sanity-check exists, they&#39;re doing it the slow way, under pressure, for no reason. If you build commands like these, ship them through a dotfiles repo, a config-management role (Ansible, Puppet, or even a simple provisioning script baked into your AMI/base image) — not a manual copy-paste onto one bastion host that only you know about.</p><p>Small shortcuts, real leverage — as long as the whole team is standing on the same ground.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761f593526d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActiveMQ in Microservices: Why Your Services Need a Middleman]]></title>
            <link>https://medium.com/@udayrajdhavande8/activemq-in-microservices-why-your-services-need-a-middleman-51d5e98e5ec9?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/51d5e98e5ec9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[activemq]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 17:55:58 GMT</pubDate>
            <atom:updated>2026-07-12T17:55:58.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvGSoh18uNItjFfdFgnTnw.png" /></figure><p>If you’ve ever waited at a restaurant while your order sat quietly on a kitchen ticket rail instead of you shouting it directly at the chef — congratulations, you’ve already used a message queue. You just didn’t call it ActiveMQ.</p><p>This post breaks down what ActiveMQ actually is, why microservices architectures lean on it so heavily, and — just as importantly — the correctness problems it introduces that most intro-level explanations conveniently skip.</p><h3>What ActiveMQ Actually Is</h3><p>ActiveMQ is a <strong>message broker</strong> — a piece of infrastructure that sits between services and handles the job of passing messages from a sender (producer) to a receiver (consumer), without the two ever having to talk directly.</p><p>It implements messaging standards like JMS (Java Message Service) and speaks multiple protocols (AMQP, MQTT, STOMP, OpenWire), which is why it shows up across Java shops, IoT pipelines, and polyglot microservice fleets alike.</p><p>Strip away the protocol jargon and ActiveMQ does exactly three things:</p><ol><li><strong>Accepts a message</strong> from a producer.</li><li><strong>Stores it</strong> (in memory, on disk, or both — configurable durability).</li><li><strong>Delivers it</strong> to one or more consumers, on their own schedule.</li></ol><p>That third point is the whole ballgame. The producer doesn’t wait around. It doesn’t care if the consumer is slow, down, or scaling from 2 pods to 20. It just drops the message and moves on.</p><p>But “drops the message and moves on” is exactly where most people stop thinking about it — and exactly where the real engineering problems start.</p><h3>The Restaurant Analogy</h3><p>Picture a busy restaurant kitchen.</p><ul><li><strong>The waiter (producer)</strong> takes your order and clips the ticket onto the rail.</li><li><strong>The ticket rail (ActiveMQ)</strong> holds every order in sequence — nobody loses a ticket, nothing gets skipped.</li><li><strong>The chefs (consumers)</strong> pull tickets off the rail as they free up, cook the order, and move to the next one.</li></ul><p>Now notice what <em>doesn’t</em> happen: the waiter does not stand at the pass, staring at the chef, waiting for the dish to be plated before taking the next table’s order. If they did, the restaurant would serve about four tables all night.</p><p>This is <strong>decoupling in time</strong>. The waiter’s speed and the chef’s speed are completely independent. If the kitchen gets slammed, orders queue up on the rail — they don’t get lost, and the waiter doesn’t grind to a halt. If a chef calls in sick, someone else works the rail. The system degrades gracefully instead of collapsing.</p><p>That’s precisely the problem ActiveMQ solves for microservices: <strong>Service A shouldn’t have to wait on Service B’s schedule to get its work done.</strong></p><h3>The Traffic Signal Analogy</h3><p>Now picture a traffic intersection with no signal — every car (request) trying to force its way through based on direct negotiation with every other car. That’s synchronous, tightly-coupled service-to-service calling at scale: one slow or crashed service, and the whole intersection gridlocks.</p><p>A traffic signal (the broker) doesn’t eliminate cars or make the intersection instantaneous. What it does is:</p><ul><li><strong>Buffer and sequence</strong> flow so cars don’t collide.</li><li><strong>Absorb bursts</strong> — a surge of cars from one direction queues at the red light instead of causing a pile-up.</li><li><strong>Let each direction move at its own pace</strong>, independent of the others.</li></ul><p>Replace “cars” with “events” and “directions” with “microservices,” and you’ve got the exact mental model for why message brokers exist in distributed systems: <strong>controlled flow instead of chaos, with built-in shock absorption for traffic spikes.</strong></p><p>One thing the analogy doesn’t cover, though: what happens when the signal itself goes down. More on that later — a broker that isn’t highly available just relocates your single point of failure, it doesn’t remove it.</p><h3>Why Microservices Specifically Need This</h3><p>In a monolith, one function calls another function in the same process. It’s instant, and if it fails, the whole call stack knows immediately.</p><p>Break that monolith into 15 services communicating over the network, and every direct HTTP call becomes a liability:</p><ul><li><strong>Latency stacks up</strong> — Service A calling B calling C calling D means A’s response time is now hostage to three network hops.</li><li><strong>Cascading failures</strong> — if D goes down, C’s calls start timing out, which backs up B, which backs up A. One dead service takes the whole chain with it.</li><li><strong>Tight coupling on availability</strong> — A can’t do its job unless B is <em>up right now</em>, even if A’s task doesn’t actually require an instant answer.</li><li><strong>No natural buffer for spikes</strong> — a flash sale or bulk upload can hammer downstream services faster than they can process, with nowhere for the excess to go.</li></ul><p>ActiveMQ (or any broker — Kafka, RabbitMQ, SQS — the concept generalizes) fixes this by inserting a <strong>durable buffer</strong> between services. Producers publish and move on. Consumers process at whatever pace they can sustain. Nobody’s uptime is directly hostage to anybody else’s.</p><p>Worth noting: this only holds if the <em>producer’s</em> publish call itself is resilient. If the broker is briefly unreachable and your producer just blocks or throws on every send(), you&#39;ve quietly reintroduced the tight coupling you were trying to remove. Production producers typically wrap the publish call with a circuit breaker and a small local retry buffer, so a broker hiccup degrades gracefully instead of taking the calling service down with it.</p><h3>How It’s Actually Used: Two Messaging Patterns</h3><p>ActiveMQ supports two core patterns, and picking the right one matters.</p><h3>1. Point-to-Point (Queues)</h3><p>One message, one consumer. Think of it as a single ticket rail with one kitchen — each ticket gets cooked exactly once, even if multiple chefs are pulling from the same rail (only one of them gets each ticket).</p><p><strong>Real use case:</strong> An order-processing service publishes “new order” messages to a queue. A pool of worker services (scaled horizontally) consumes from that same queue. Each order gets processed exactly once, and you can scale workers up during peak hours without touching the producer.</p><p><strong>Ordering caveat:</strong> ActiveMQ preserves order <em>within a single queue as messages are enqueued</em>, but the moment you scale out to multiple competing consumers on that same queue, you lose the guarantee that they’re processed in that order — consumer 2 might finish message 5 before consumer 1 finishes message 3. If strict ordering matters for a given key (say, all events for one customer must apply in sequence), you either pin that key to a single consumer, use exclusive consumers, or accept that ordering is a per-partition concern, not a per-queue one.</p><h3>2. Publish-Subscribe (Topics)</h3><p>One message, broadcast to <em>every</em> subscriber. Think of a restaurant’s kitchen display system that simultaneously updates the chef’s screen, the manager’s inventory tracker, and the customer’s order-status app — from a single ticket.</p><p><strong>Real use case:</strong> An e-commerce “OrderPlaced” event gets published once. The inventory service subscribes and decrements stock. The billing service subscribes and charges the card. The notification service subscribes and sends the confirmation email. The analytics service subscribes and logs it for reporting. <strong>One event, four independent reactions, zero coupling between those four services.</strong> None of them know the others exist.</p><h3>A Concrete Microservices Flow</h3><p>Take an e-commerce checkout, decomposed into services:</p><pre>Order Service ──publishes──▶ [ActiveMQ: OrderPlaced topic]<br>                                      │<br>        ┌─────────────┬──────────────┼──────────────┐<br>        ▼             ▼              ▼              ▼<br>   Inventory     Payment        Notification     Analytics<br>   Service       Service        Service           Service<br>   (decrement    (charge        (send email/      (log event<br>    stock)        card)          SMS)              for BI)</pre><p>Without a broker, the Order Service would need to call all four downstream services synchronously, wait for all of them to respond, and fail the entire checkout if any one of them hiccups.</p><p>With ActiveMQ, the Order Service publishes one message and returns a response to the customer in milliseconds. The four consumers process independently, retry independently on failure, and scale independently based on their own load.</p><p>But independence cuts both ways: <strong>what happens when Inventory successfully decrements stock, and Payment then fails?</strong> You now have reserved inventory for a sale that never actually completed. Async fan-out doesn’t remove this problem — a synchronous call would fail the whole checkout atomically; an async one leaves you with a partial state that something has to notice and undo.</p><p>The standard fix is a <strong>compensating action</strong>, not a rollback — because there’s no shared transaction to roll back across four independent services. Payment Service, on failure, publishes an OrderPaymentFailed event. Inventory Service subscribes to <em>that</em> and reverses its own decrement. This is the same idea behind the Saga pattern: a chain of local transactions, each with a corresponding compensating transaction, instead of one giant distributed transaction nothing can actually enforce.</p><h3>The Correctness Gotchas Nobody Mentions</h3><p>This is the part most ActiveMQ explainers skip entirely, and it’s where systems actually break in production.</p><h3>“Guaranteed delivery” usually means at-least-once, not exactly-once</h3><p>ActiveMQ’s acknowledgment model determines what you actually get:</p><ul><li><strong>AUTO_ACKNOWLEDGE</strong> — the message is marked delivered as soon as the consumer receives it, before it’s actually finished processing. If the consumer crashes mid-work, that message is gone. Fast, but weak guarantees.</li><li><strong>CLIENT_ACKNOWLEDGE</strong> — the consumer explicitly acks after successfully finishing the work. If it crashes before acking, ActiveMQ redelivers the message. Stronger, but now you <em>will</em> see duplicates whenever a crash happens between “finished the work” and “sent the ack.”</li><li><strong>SESSION_TRANSACTED</strong> — the receive-and-process happens inside a transaction; a rollback puts the message back for redelivery. Strongest guarantee, but requires the downstream work to be wrapped in that transaction too.</li></ul><p>None of these give you exactly-once out of the box. Redelivery is a normal, expected event — not an edge case. Which means:</p><h3>Every consumer needs to be idempotent</h3><p>If the Payment Service can receive the same OrderPlaced message twice (broker redelivery after a crashed ack, a network blip, a consumer restart mid-batch), and it charges the card both times, that&#39;s a real customer complaint, not a theoretical risk. The fix is the same pattern as webhook handling: attach an idempotency key (often the message&#39;s JMSMessageID or a business-level order ID) and check a dedup store before acting, not after.</p><h3>Dead letter queues need a human on the other end</h3><p>ActiveMQ’s default redelivery policy retries a failing message a fixed number of times (commonly 6, with a growing delay between attempts) before routing it to ActiveMQ.DLQ. That&#39;s the easy part. The part teams actually miss is that a message sitting in the DLQ is a <strong>silent failure</strong> unless something is watching queue depth on it and alerting. A checkout event stuck in the DLQ with nobody looking is a customer who paid and never got their inventory reserved — and nobody finds out until they complain.</p><h3>Keeping the Broker Itself Highly Available</h3><p>The traffic signal analogy has a gap: what happens when the signal itself loses power. If ActiveMQ goes down and it’s a single instance, you haven’t decoupled your services from each other’s downtime — you’ve just made all of them dependent on one new thing’s uptime instead.</p><p>In practice, this means the broker needs the same HA treatment as any other stateful system:</p><ul><li><strong>Persistent store</strong> — KahaDB (the default, file-based) or a JDBC-backed store, so messages survive a broker restart instead of living only in memory.</li><li><strong>Master-slave failover</strong> — a shared, lockable store (or a replicated LevelDB store) so a standby broker can take over if the active one dies, without losing unacknowledged messages.</li><li><strong>Network of brokers</strong> — for horizontal scale-out, brokers can be meshed together so producers and consumers don’t all have to hit one node.</li></ul><p>None of this is optional if the broker is sitting in the critical path of something like order processing. “We added a queue so nothing is a single point of failure” is only true if the queue itself isn’t one.</p><h3>When You Actually Need This (And When You Don’t)</h3><p>Not every service-to-service interaction should go through a broker. Use it when:</p><ul><li>The caller doesn’t need an immediate response (fire-and-forget or eventual consistency is acceptable).</li><li>You need to protect a downstream service from traffic bursts.</li><li>Multiple independent services need to react to the same event.</li><li>You need guaranteed (at-least-once) delivery even if a consumer is temporarily down.</li></ul><p>Skip it when:</p><ul><li>You need a synchronous request-response with an answer needed <em>right now</em> (e.g., “is this coupon valid” during checkout — that’s a direct API call, not an async event).</li><li>The added operational overhead (managing broker HA, monitoring queue depth, dealing with poison messages and dead-letter queues) isn’t worth it for a two-service system.</li></ul><h3>The Trade-Off Nobody Skips Mentioning</h3><p>Async messaging buys you decoupling and resilience, but it costs you:</p><ul><li><strong>Eventual consistency</strong> — there’s a window where the order exists but inventory hasn’t been decremented yet. Your system has to be designed to tolerate that window, and to compensate cleanly when a downstream step fails inside it.</li><li><strong>Operational complexity</strong> — you’re now running and monitoring a broker as critical infrastructure: disk-backed persistence, consumer lag, dead-letter queue handling, and broker HA (master-slave or network of brokers) all become your problem.</li><li><strong>Harder debugging</strong> — tracing a request across five async hops requires proper correlation IDs and distributed tracing. In practice this means propagating a trace context (a traceparent-style header) as a JMS message property on every hop, so tools like Jaeger can stitch the producer&#39;s span to each consumer&#39;s span into one trace — otherwise you&#39;re grepping five separate log streams by timestamp and hoping.</li></ul><p>None of that is a reason to avoid ActiveMQ. It’s a reason to be deliberate about <em>where</em> in your architecture you introduce it, rather than routing every single service call through a queue because it feels more “microservices.”</p><h3>Bottom Line</h3><p>ActiveMQ isn’t glue you bolt on because microservices are trendy — it’s the ticket rail that keeps your kitchen from seizing up when five waiters are all trying to reach one chef at once. It buys you the ability to scale services independently, survive partial outages gracefully, and let one event fan out to as many downstream reactions as your system needs — without any of those downstream services ever knowing, or caring, who else is listening.</p><p>Just don’t mistake “decoupled” for “correct by default.” Decoupling handles the <em>timing</em> problem. Idempotent consumers, compensating actions, and a highly available broker are what handle the <em>correctness</em> problem — and that part is still entirely on you to design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51d5e98e5ec9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shared Storage Explained: NFS, Windows File Shares, and Kubernetes PV/PVC]]></title>
            <link>https://medium.com/@udayrajdhavande8/shared-storage-explained-nfs-windows-file-shares-and-kubernetes-pv-pvc-835572c286a4?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/835572c286a4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 04:17:58 GMT</pubDate>
            <atom:updated>2026-07-06T04:17:58.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPz9kRFVIOZyJdOrMI4N6Q.png" /></figure><p>If you’ve worked in infra long enough, you’ve hit the same wall every time: a pod dies, gets rescheduled on another node, and suddenly the data it wrote is gone. Or two services need to read the same files, but each node has its own local disk with its own copy. This is the exact problem shared storage — and NFS in particular — solves.</p><p>This post breaks it down from first principles: what NFS actually is, the different flavors of shared storage you’ll run into, how it plugs into Kubernetes via PV/PVC, and the mistakes that bite people in production.</p><h3>What is NFS?</h3><p><strong>NFS (Network File System)</strong> is a protocol that lets a machine mount a directory that physically lives on a <em>different</em> machine, and use it as if it were local. It was built by Sun Microsystems in the 1980s, and it’s still everywhere in enterprise infra today.</p><p>Think of it like this: you have a shared Google Drive folder. Multiple people open it, edit files, save them — and everyone sees the same content. NFS is the same idea, but at the OS/filesystem level instead of the application level.</p><p><strong>Basic setup:</strong></p><ul><li><strong>NFS server</strong>: the machine that owns the actual disk and exports a directory (e.g., /data/shared)</li><li><strong>NFS client</strong>: any machine that mounts that exported directory onto its own filesystem (e.g., mounts it at /mnt/shared)</li></ul><p>Example:</p><pre># On the NFS server<br>sudo exportfs -a<br>cat /etc/exports<br># /data/shared  10.0.0.0/24(rw,sync,no_subtree_check)</pre><pre># On the NFS client<br>sudo mount -t nfs 10.0.0.5:/data/shared /mnt/shared</pre><p>Once mounted, any file written to /mnt/shared on the client actually gets written over the network to the server&#39;s disk. Every other client mounting the same export sees that file immediately.</p><h3>Types of Shared Storage</h3><p>NFS is one option among several. Here’s the landscape, in plain terms:</p><p><strong>1. NFS (file-level, network)</strong> Shares whole directories over the network. Multiple clients read/write the same files concurrently. Good for shared config, logs, media, ML datasets.</p><p><strong>2. SAN — Storage Area Network (block-level, network)</strong> Presents raw block devices over a network (usually Fibre Channel or iSCSI) to a single host at a time, which then formats it like local disk. Fast, but typically not multi-writer — one host owns the block device.</p><p><strong>3. Object Storage (S3, MinIO, Ceph RGW)</strong> No filesystem hierarchy — you interact via HTTP APIs (PUT/GET objects with keys). Built for massive scale, not POSIX file semantics. Good for backups, static assets, immutable data.</p><p><strong>4. Distributed/Cluster Filesystems (Ceph RBD/CephFS, GlusterFS)</strong> Multiple storage nodes work together, replicate data, and survive node failure. CephFS in particular gives you POSIX file semantics <em>and</em> multi-writer access <em>and</em> resilience — this is what a lot of self-managed Kubernetes clusters use instead of NFS at scale.</p><p><strong>5. Local storage</strong> Just the disk attached to that one node. Fast, but dies with the node and can’t be shared. Fine for cache/scratch space, bad for anything you need to survive a pod reschedule.</p><p>Type Access pattern Multi-writer? Survives node loss? Typical use NFS File Yes Depends on server HA setup Shared configs, logs, ML datasets SAN (iSCSI) Block Usually no Yes (on SAN side) Databases, VMs Object (S3) API/object Yes Yes Backups, static assets Ceph RBD Block No (single attach) Yes Databases in k8s CephFS File Yes Yes Shared app data in k8s Local disk File/block No No Cache, scratch space</p><h3>The Windows Side: SMB/CIFS Shared Drives</h3><p>NFS is the Linux/Unix world’s answer to shared storage. Windows-heavy enterprises solve the exact same problem with a different protocol: <strong>SMB (Server Message Block)</strong>, sometimes still called <strong>CIFS</strong> (Common Internet File System — the older name for the same protocol family).</p><p>If you’ve ever typed \\fileserver\finance into Windows Explorer, or seen a company map drive Z: to &quot;Shared Drive,&quot; that&#39;s SMB doing the same job NFS does on Linux — letting a folder physically living on one server appear as local storage on every employee&#39;s machine.</p><h3>How Big Companies Actually Set This Up</h3><p><strong>1. A dedicated file server (or cluster of them)</strong> Usually a Windows Server machine (or several, for redundancy) running the <strong>File and Storage Services</strong> role. IT sets up folders like \\corp-fs01\Finance, \\corp-fs01\HR, \\corp-fs01\Engineering, each as a separate SMB <strong>share</strong>.</p><pre># On the Windows Server (run in PowerShell as admin)<br>New-Item -Path &quot;D:\Shares\Finance&quot; -ItemType Directory<br>New-SmbShare -Name &quot;Finance&quot; -Path &quot;D:\Shares\Finance&quot; -FullAccess &quot;DOMAIN\Finance-Team&quot;</pre><p><strong>2. Active Directory for identity and permissions</strong> This is the real backbone of enterprise file sharing. Instead of managing per-user access on every file server, companies use <strong>Active Directory (AD)</strong> groups. A user is added to a security group like DOMAIN\Finance-Team, and that group is granted access to the share. Remove them from the group, access disappears everywhere — no hunting through servers.</p><pre># Grant an AD group access instead of individual users<br>Grant-SmbShareAccess -Name &quot;Finance&quot; -AccountName &quot;DOMAIN\Finance-Team&quot; -AccessRight Full</pre><p><strong>3. Group Policy maps the drive automatically</strong> Employees don’t manually type \\corp-fs01\Finance every day. IT pushes a <strong>Group Policy Object (GPO)</strong> that auto-maps it to a drive letter (like F:\) the moment they log into any company machine — including a machine they&#39;ve never used before.</p><p><strong>4. DFS (Distributed File System) for scale</strong> Once a company has file servers in multiple offices or regions, they don’t want employees remembering which physical server holds which folder. <strong>DFS Namespaces</strong> create one unified path, e.g. \\corp.company.com\Shared\Finance, and DFS transparently routes the request to whichever backend server actually holds that data — even replicating it between offices via <strong>DFS Replication (DFS-R)</strong> so a team in Mumbai and a team in London see the same files with local-speed access.</p><p><strong>5. Backup and quotas</strong> Enterprise file servers run scheduled snapshots (Volume Shadow Copy / VSS) so a user can right-click → “Restore previous versions” if they accidentally delete a file — no help desk ticket needed. Storage quotas per user/department are enforced via <strong>File Server Resource Manager (FSRM)</strong> to stop one team from eating the whole disk.</p><h3>SMB vs NFS — Quick Contrast</h3><p>NFS SMB/CIFS Native OS Linux/Unix Windows Identity model UID/GID (or Kerberos) Active Directory accounts/groups Typical use App servers, containers, ML data Employee shared drives, corporate docs Access from other OS Windows can mount NFS with extra config Linux can mount SMB via cifs-utils Central management /etc/exports, IdM/FreeIPA Active Directory + Group Policy</p><p>They solve the same underlying problem — network-mounted shared folders — but come from completely different ecosystems, and in a large company, <strong>both usually exist side by side</strong>: SMB for employee/corporate file sharing, NFS (or CephFS/object storage) for backend application and infrastructure data.</p><h3>Mixed Environments: When Linux Needs to Touch a Windows Share</h3><p>This comes up constantly in real infra work — a Linux server or container needs to read/write a Windows SMB share.</p><pre># Install client tools<br>sudo apt install cifs-utils</pre><pre># Mount a Windows share on a Linux box<br>sudo mount -t cifs //corp-fs01/Finance /mnt/finance \<br>  -o username=svc_account,password=****,domain=DOMAIN,vers=3.0</pre><p>For anything beyond a one-off, credentials should go in a secured credentials file (-o credentials=/etc/samba/creds, chmod 600) instead of inline in a mount command or /etc/fstab, since that file is often world-readable by default.</p><h3>NFS in Production: Best Practices</h3><p>From real-world scars, not just docs:</p><ul><li><strong>Don’t run a single NFS server as your only copy of critical data.</strong> It’s a single point of failure. Pair it with RAID, snapshots, or a proper backup pipeline — or better, put an HA layer (like a floating VIP + keepalived) in front of it.</li><li><strong>Watch your mount options.</strong> sync is safer but slower; async is faster but risks data loss on server crash. Choose based on how critical the data is.</li><li><strong>Set sane timeouts (</strong><strong>timeo, </strong><strong>retrans).</strong> A hung NFS mount can hang every process on the client trying to touch that path — including things unrelated to your app. This is one of the most common &quot;why is my whole node stuck&quot; incidents.</li><li><strong>Watch </strong><strong>no_root_squash.</strong> By default, NFS maps root on the client to an unprivileged user (root_squash) for security. Only disable this if you fully trust every client.</li><li><strong>Monitor NFS server load separately.</strong> A slow NFS server silently degrades every client mounting it — this looks like “random app slowness” until you check nfsstat or server-side I/O wait.</li><li><strong>Avoid NFS for high-IOPS workloads like databases.</strong> Network file locking and latency make NFS a poor fit for anything doing heavy random writes. Use block storage there instead.</li><li><strong>Use NFSv4 over v3 where possible</strong> — better security (Kerberos support), single-port operation (easier firewalling), and better locking semantics.</li></ul><h3>NFS and Shared Storage in Kubernetes: PV and PVC</h3><p>This is where it gets practical for platform/SRE work.</p><p>Kubernetes pods are ephemeral — they can be killed and rescheduled on any node at any time. If a pod writes data to its own container filesystem, that data disappears the moment the pod dies. Kubernetes solves this with a storage abstraction layer:</p><ul><li><strong>PV (PersistentVolume)</strong>: a piece of actual storage in the cluster — could be backed by NFS, Ceph RBD, a cloud disk, etc. This is defined by the cluster admin (or dynamically provisioned).</li><li><strong>PVC (PersistentVolumeClaim)</strong>: a <em>request</em> for storage made by a pod/app. The app doesn’t care where the storage physically lives — it just says “give me 10Gi, ReadWriteMany.”</li><li>Kubernetes <strong>binds</strong> a PVC to a matching PV, and the pod mounts that PVC as a volume — same as any other volume mount.</li></ul><h3>Example: NFS-backed PV/PVC</h3><p><strong>Step 1 — Define the PV (pointing at your NFS export):</strong></p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: nfs-pv<br>spec:<br>  capacity:<br>    storage: 10Gi<br>  accessModes:<br>    - ReadWriteMany<br>  nfs:<br>    server: 10.0.0.5<br>    path: /data/shared</pre><p><strong>Step 2 — Define the PVC (what the app asks for):</strong></p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: nfs-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteMany<br>  resources:<br>    requests:<br>      storage: 10Gi</pre><p><strong>Step 3 — Mount it in a pod:</strong></p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: app-pod<br>spec:<br>  containers:<br>    - name: app<br>      image: nginx<br>      volumeMounts:<br>        - mountPath: /usr/share/nginx/html<br>          name: shared-storage<br>  volumes:<br>    - name: shared-storage<br>      persistentVolumeClaim:<br>        claimName: nfs-pvc</pre><p>Now every replica of this app, on any node, mounts the <em>same</em> NFS-backed volume at /usr/share/nginx/html. Scale the deployment to 10 pods across 10 different nodes — they all see the exact same files.</p><h3>Real Use Cases</h3><p><strong>1. Shared config/static assets across replicas</strong> A web app running 5 replicas needs the same uploaded images visible to all of them (e.g., a WordPress-style CMS). NFS with ReadWriteMany (RWX) lets every pod read/write the same directory regardless of which node it lands on.</p><p><strong>2. ML training data shared across worker pods</strong> A distributed training job with 20 worker pods all needs to read the same dataset. Instead of copying gigabytes onto every node, you mount one NFS export as RWX across all workers.</p><p><strong>3. Log aggregation scratch space</strong> Multiple pods writing logs to a shared NFS path that a separate log-shipper pod reads from — common in older, non-sidecar log pipelines.</p><p><strong>4. StatefulSets for databases — the exception</strong> Databases (Postgres, MySQL) typically use ReadWriteOnce (RWO) volumes backed by block storage like Ceph RBD or cloud EBS, <em>not</em> NFS — because databases need low-latency exclusive writes, and multiple pods writing to the same DB files would corrupt it. This is a case where NFS is the <em>wrong</em> tool, and knowing that distinction is itself a good interview signal.</p><p><strong>5. CI/CD shared build cache</strong> Tekton/Jenkins pipeline pods across different nodes sharing a build cache directory (e.g., npm/pip cache) via an NFS-backed PVC, so every pipeline run doesn’t re-download the same dependencies from scratch.</p><h3>Access Modes Cheat Sheet</h3><p>Access Mode Meaning Typical backend RWO (ReadWriteOnce) One node can mount read-write Ceph RBD, EBS, local RWX (ReadWriteMany) Many nodes, read-write simultaneously NFS, CephFS, EFS ROX (ReadOnlyMany) Many nodes, read-only NFS, CephFS</p><p>If your app needs multiple pods on different nodes to write to the same volume — that’s your signal it needs NFS/CephFS (RWX), not RBD/EBS (RWO).</p><h3>Quick Recap</h3><ul><li>NFS shares directories over the network at the file level; simple, POSIX-compliant, but not built for high-IOPS workloads.</li><li>SMB/CIFS is the Windows-world equivalent — the same idea, but built around Active Directory identity, Group Policy drive mapping, and DFS for multi-site scale. Big companies typically run both: SMB for employee file shares, NFS/CephFS/object storage for backend infra.</li><li>Shared storage isn’t one-size-fits-all — pick block for databases, file (NFS/CephFS/SMB) for shared multi-writer access, object for backups/static content.</li><li>In Kubernetes, PV is the actual storage, PVC is the app’s request for it — this abstraction is what lets pods “forget” which node they’re running on and still find their data.</li><li>The access mode (RWO vs RWX) is usually what decides whether NFS is even the right choice for a given workload.</li></ul><p>Understanding <em>when each type of shared storage is the right tool</em> — and, just as importantly, when it isn’t — is one of those things that separates people who’ve only read the docs from people who’ve actually debugged a hung mount, a broken drive mapping, or a stuck PVC at 2 AM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=835572c286a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Server Is Already Compromised — Here’s Why the Gateway Is the Last Thing Standing]]></title>
            <link>https://medium.com/@udayrajdhavande8/your-server-is-already-compromised-heres-why-the-gateway-is-the-last-thing-standing-342012dad6ed?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/342012dad6ed</guid>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 07:03:08 GMT</pubDate>
            <atom:updated>2026-06-30T07:03:08.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODm4SwB-7rmRRRm88Wpv0A.png" /></figure><h3>A security-compliance walkthrough using real FinTech API documentation, not hypotheticals</h3><p>Most API security writing assumes a clean world: attacker outside, system inside, gateway as the wall between them. That model is comforting, and it’s wrong.</p><p>The question that actually matters in a regulated FinTech environment isn’t <em>“how do we stop a breach.”</em> It’s:</p><blockquote><em>Given that something behind our gateway will eventually be compromised, what’s the blast radius — and how long does the attacker have before the door closes on them anyway?</em></blockquote><p>That second question is what JWT and API key expiry actually answer. Not “can this be stolen” — assume it will be. The real question is: <strong>how long is it useful after it is?</strong></p><pre>Old Mental Model                    Reality<br> ┌────────────┐                  ┌────────────┐<br> │  Attacker  │                  │  Attacker  │<br> └─────┬──────┘                  └─────┬──────┘<br>       │ blocked                       │ gets in eventually<br> ┌─────▼──────┐                  ┌─────▼──────┐<br> │  GATEWAY   │ ← &quot;the wall&quot;     │  GATEWAY   │ ← &quot;the blast-radius limiter&quot;<br> └─────┬──────┘                  └─────┬──────┘<br>       │                               │ short-lived, scoped token only<br> ┌─────▼──────┐                  ┌─────▼──────┐<br> │  Backend   │  &quot;safe inside&quot;   │  Backend   │  &quot;assume compromised&quot;<br> └────────────┘                  └────────────┘</pre><h3>The Compliance Frame: Assume Breach, Then Design</h3><p>This isn’t a hot take. OWASP’s API Security Top 10 treats broken authentication as its own top-tier risk category — specifically because APIs that accept tokens without checking the expiration claim, or that accept weakly signed tokens, hand attackers a working credential indefinitely.</p><p>The compliance angle isn’t abstract either. Regulated industries that fail to enforce strong authentication risk noncompliance with standards like <strong>PCI DSS</strong>, <strong>HIPAA</strong>, or <strong>PSD2</strong> — each carrying its own financial consequences.</p><p>Read that carefully: the failure mode named explicitly by these standards isn’t <em>“attacker gets in.”</em> It’s <em>“the system kept trusting a credential it should have stopped trusting.”</em> That’s an expiry and revocation problem, not a perimeter problem.</p><h3>What “Server Compromised” Actually Means for a Gateway</h3><p>Walk through the actual scenario. A backend service — say your transfer-processing service — gets compromised. Maybe an unpatched dependency, maybe a leaked deployment credential. Doesn’t matter how. The attacker is now inside, with whatever the compromised service had access to.</p><p>Here’s where the architecture either saves you or doesn’t.</p><h3>Scenario A — Gateway enforces scope and expiry</h3><pre>Attacker on compromised box<br>        │<br>        ▼<br> Token found in memory: scope=transfer:write (single user)<br>        │                expires_in: 15 min<br>        ▼<br> Token used after 16 minutes  →  ❌ REJECTED (expired)</pre><p>The compromised backend service never had the customer’s long-lived credentials in the first place. It only ever saw a short-lived, scope-limited JWT that the gateway had already validated before forwarding. Permissions are narrow (transfer:write for one user, not admin:all), and the token expires on its own schedule regardless of what the attacker does next.</p><h3>Scenario B — Gateway just routes traffic</h3><pre>Attacker on compromised box<br>        │<br>        ▼<br> Token found in logs/cache: scope=* , expires_in: 30 days<br>        │<br>        ▼<br> Token replayed from outside network  →  ✅ ACCEPTED (still valid)</pre><p>If the gateway isn’t enforcing scope boundaries, and tokens don’t expire aggressively, every token that’s ever passed through stays valid for as long as you let it — including ones the attacker can now intercept or replay from logs, caches, or memory dumps on the box they just took over.</p><h3>The actual mechanical point</h3><p>A <strong>15-minute JWT expiry does nothing to prevent the server from being hacked.</strong> It limits what the attacker can do with anything they scrape off that server afterward.</p><ul><li>A token with a <strong>15-minute window</strong>, pulled from a compromised box’s memory, is worthless within minutes.</li><li>A token with a <strong>30-day window</strong>, pulled from the same box, is a 30-day standing authorization the attacker now holds — indistinguishable from a legitimate session, usable from outside your network, with no further need to maintain access to the compromised box at all.</li></ul><h3>A Real Public FinTech Implementation: A Real Mobile Money OAuth2 Flow</h3><p>This isn’t theoretical. a major mobile money provider’s developer documentation — the one actual companies integrate against for mobile money collections and disbursements across more than a dozen African markets — is built on exactly this pattern.</p><p>This provider uses the OAuth 2.0 protocol to grant API access, where access tokens represent the authorization to act on a resource owner’s behalf, and JWT format carries that authorization data. The flow in their public documentation looks like this:</p><pre>curl -X POST https://api.mobilemoneyprovider.example/auth/oauth2/token \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;client_id&quot;: &quot;your-client-id&quot;,<br>    &quot;client_secret&quot;: &quot;your-client-secret&quot;,<br>    &quot;grant_type&quot;: &quot;client_credentials&quot;<br>  }&#39;</pre><pre>// Response:<br>{<br>  &quot;access_token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&quot;,<br>  &quot;token_type&quot;: &quot;Bearer&quot;,<br>  &quot;expires_in&quot;: 3600<br>}</pre><p>That expires_in: 3600 isn&#39;t an arbitrary default. It&#39;s the entire compliance posture compressed into one field. Every access token issued by this flow is dead in one hour, no matter what happens to it after issuance — leaked in a log, cached on a compromised app server, intercepted on an unencrypted debug proxy. One hour, then it&#39;s inert.</p><p>Documented integration guidance for this exact API tells developers to <strong>cache tokens and reuse until expiration</strong> rather than requesting a fresh one on every call — which tells you the expiry window was sized deliberately, balancing “short enough to cap exposure” against “long enough that you’re not hammering the auth endpoint on every transaction.” That’s a real engineering tradeoff, made visible in a one-hour number, not a hand-wavy “tokens should expire” statement.</p><p>Compare that to what OWASP flags as the actual exploit pattern when this discipline is missing: a JWT signed with a weak secret, or accepted with no algorithm enforcement at all, yields a token that gets reused across sessions without ever being revoked — granting the attacker persistent access. The fix isn’t exotic: enforce strong signing algorithms, reject unsigned tokens, implement short expirations alongside revocation lists. this one-hour window is that exact recommendation, implemented and shipped in a production financial API that real businesses integrate against today.</p><h3>API Key Expiry Is a Different Compliance Problem</h3><p>The OAuth2 flow above also shows why client_id and client_secret — the API key equivalent here — need a <strong>separate</strong> expiry and rotation discipline from the access token itself.</p><pre>client_secret (long-lived, lives in CI/secrets manager)<br>              │<br>              │  mints<br>              ▼<br>        access_token (1 hour, scoped)<br>              │<br>              │  used on requests<br>              ▼<br>           Gateway validates</pre><p>The access token expires every hour by design. The client_secret used to mint new access tokens does <strong>not</strong> expire on the same schedule — it sits in your server config, your CI pipeline, your secrets manager, for as long as the integration is live. If that leaks, the attacker doesn&#39;t need to steal a token at all. They mint their own, indefinitely, using your credentials — and every token they generate passes validation perfectly, because it&#39;s a legitimately issued token from a legitimately compromised secret.</p><p>This is exactly the gap OWASP calls out separately from token expiry: API keys should not be used for user authentication, precisely because a key represents <em>standing authorization to an application</em>, not a time-boxed session. Conflating the two means your “short expiry” story only protects half the credential chain.</p><h3>Rotation, not just expiry</h3><p>Unlike a JWT, you can’t just let an API key “expire” without breaking the integration. You have to issue a new one, run both in parallel during a grace window, then explicitly kill the old one:</p><pre># Generate new key, keep old key valid for a 14-day overlap window<br>POST /credentials/rotate<br>{<br>  &quot;client_id&quot;: &quot;partner-bank-ke&quot;,<br>  &quot;grace_period_days&quot;: 14<br>}</pre><pre># After grace period, old client_secret is explicitly invalidated server-side<br># Any token minted with it after this point fails validation immediately</pre><p>If you don’t have a rotation mechanism — only an expiry on the short-lived token — you’ve solved the symptom and left the root credential standing for years. Audit reports in regulated FinTech don’t ask “do your tokens expire.” They ask <strong>“when was this credential last rotated”</strong> — and if the honest answer is “since the integration was built,” that’s a finding.</p><h3>What the Gateway Does With All of This, Mechanically</h3><p>Pulling it together into what actually happens at the gateway layer on every request, assuming the worst — that something somewhere in your chain has already been compromised:</p><pre>Incoming Request<br>        │<br>        ▼<br> ① Signature check  ──── fail ──→  ❌ Reject (cheapest, first line)<br>        │ pass<br>        ▼<br> ② Expiry check     ──── fail ──→  ❌ Reject (timestamp comparison)<br>        │ pass<br>        ▼<br> ③ Scope/audience    ──── fail ──→  ❌ Reject (read-only ≠ write access)<br>        │ pass<br>        ▼<br> ④ Rate limit (API key) ── fail ──→ ❌ Throttle/Reject<br>        │ pass<br>        ▼<br> ⑤ Audit log emission<br>        │<br>        ▼<br>   Forward to backend</pre><ol><li><strong>Signature check first</strong>, cheapest operation — rejects forged tokens before spending any compute on claims parsing.</li><li><strong>Expiry check</strong>, second cheapest — a timestamp comparison. This is the check that makes the this one-hour window actually matter: even a perfectly forged-looking, correctly signed token from an hour-old session gets bounced here.</li><li><strong>Scope and audience check</strong> — confirms the token’s permissions match the route being called, so a compromised service holding a read-only token can’t use it to call a write endpoint just because the signature is valid.</li><li><strong>Consumer-level rate limit via API key</strong> — independent of the JWT. This is what catches an attacker who’s minted unlimited tokens from a stolen client_secret: the volume from that consumer spikes against its own bucket, distinct from every other legitimate consumer&#39;s traffic.</li><li><strong>Audit log emission</strong> — every one of the above checks, pass or fail, gets logged with the request ID. The moment you suspect compromise, this log is the only record of exactly which tokens were used, from where, and whether any of them outlived their expiry window before being caught.</li></ol><p>None of these five steps assume the backend is clean. That’s the actual compliance posture: build the gateway as if everything behind it might already be compromised, and let expiry, scope, and rate limiting cap the damage — rather than relying on perimeter defense to prevent the compromise from happening at all.</p><h3>The Red Pill Part</h3><p>Most teams treat token expiry as a UX annoyance to be minimized — <em>“shorter expiry means more login prompts, bad for conversion.”</em> That framing is backwards in a regulated financial system. The expiry window isn’t a UX dial. It’s the size of the window an attacker gets if everything else you built fails.</p><p>This provider didn’t pick one hour because it’s a nice round number. Somewhere in that decision is an actual risk calculation: how much fraud can happen in 60 minutes versus how much friction a 60-minute re-auth creates, and which side of that tradeoff a financial services company is willing to live with. If your team has never had that conversation explicitly — if your token expiry is whatever the auth library defaulted to — you don’t have a security posture, you have an accident waiting for an auditor to find it.</p><p>And the credential most teams forget to even ask the question about is the <strong>API key sitting in their CI pipeline since the integration shipped.</strong> Nobody’s logging in with it, so nobody thinks about it expiring. That’s exactly the credential a compromised server is most likely to have sitting in an environment variable — fully valid, fully capable of minting fresh tokens forever.</p><h3>Summary</h3><p>A compromised server isn’t a hypothetical you defend against once at the perimeter. It’s the assumption your gateway should already be built around.</p><ul><li><strong>Short JWT expiry</strong> doesn’t stop the breach — it caps how long anything stolen during the breach stays useful.</li><li><strong>API key rotation</strong> does the same job for the longer-lived credential that mints those tokens in the first place.</li></ul><p>This provider’s public OAuth2 documentation shows this isn’t an academic best practice — it’s what a production financial API serving real money movement across multiple countries actually ships, in a one-hour expiry field that most integrators never stop to ask why it’s there.</p><blockquote><em>If you can’t explain why your token expiry is set to the number it’s set to, that’s the finding — before any auditor ever has to point it out for you.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342012dad6ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is a Load Balancer — And Why Every Organization You’ve Ever Used Depends on One]]></title>
            <link>https://medium.com/@udayrajdhavande8/what-is-a-load-balancer-and-why-every-organization-youve-ever-used-depends-on-one-56ef975f8c81?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ef975f8c81</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 06:08:10 GMT</pubDate>
            <atom:updated>2026-06-29T06:08:10.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHvAhqpdudSOHqurlz7sfA.png" /></figure><blockquote><em>The invisible piece of infrastructure keeping the internet from falling over</em></blockquote><p>You’ve clicked “Pay Now” on Flipkart during a sale. You’ve logged into your bank’s app at 9am on a Monday. You’ve streamed a match on Hotstar the moment it started.</p><p>None of those worked because of one server. They worked because of many — and something in front of them deciding, in milliseconds, which one gets your request.</p><p>That something is a load balancer.</p><h3>The Simplest Explanation</h3><p>Imagine a restaurant. Twenty tables, one entrance. A host stands at the door and directs every customer: “Table 4 is free, go there.” No one walks in and picks randomly. No one piles onto one table while others sit empty. The host distributes load.</p><p>A load balancer is that host, but for your servers.</p><p>When traffic comes in — HTTP requests, TCP connections, database queries — the load balancer sits at the entry point and decides which backend server handles each request. It does this based on rules, algorithms, and health information about each server.</p><p>That’s the core contract. Everything else is features built on top of it.</p><h3>Where It Lives in Your Architecture</h3><p>Before diving into use cases, understand where the load balancer actually sits. Most production systems have more than one.</p><pre>Internet<br>    │<br>    ▼<br>[CDN / Edge Layer]         → Cloudflare, Akamai, AWS CloudFront<br>    │                         (caches, DDoS protection)<br>    ▼<br>[External Load Balancer]   → AWS ALB, HAProxy, Nginx<br>    │                         (TLS termination, path routing, rate limiting)<br>    ▼<br>[Internal Load Balancer]   → Kubernetes kube-proxy, Istio, Linkerd<br>    │                         (east-west traffic between microservices)<br>    ▼<br>[Application Backends]     → Your actual servers, pods, containers<br>    │<br>    ▼<br>[Database Load Balancer]   → PgBouncer, ProxySQL, HAProxy TCP mode<br>                              (connection pooling for PostgreSQL, MySQL)</pre><p>Most teams think about only the external load balancer — the one facing the internet. The others are just as important and just as capable of causing incidents.</p><h3>The Four Things a Load Balancer Actually Does</h3><p>No more, no less.</p><p><strong>1. Accepts connections</strong> — It listens on an IP and port. All traffic comes here first.</p><p><strong>2. Selects a backend</strong> — Using a configured algorithm, it picks which server gets the request.</p><p><strong>3. Forwards the request</strong> — Either proxies it (creates a new connection to the backend) or passes it through transparently.</p><p><strong>4. Checks backend health</strong> — Continuously probes each server. Removes unhealthy ones from rotation so traffic never goes to a dead server.</p><p>That’s the entire job. Rate limiting, SSL offload, URL rewriting, authentication — all of that is functionality layered on top of these four steps.</p><h3>Layer 4 vs Layer 7 — The Distinction That Actually Matters</h3><p>You’ll hear these terms constantly. Here’s what they mean in plain terms.</p><h3>Layer 4 (Transport Layer)</h3><p>The load balancer only sees network-level information: source IP, destination IP, and port numbers. It has no idea what’s inside the packet. It can’t read your HTTP headers, your cookies, or your URL path.</p><p><strong>It’s fast because it does less.</strong></p><p>Use it when:</p><ul><li>Traffic isn’t HTTP (PostgreSQL, Redis, AMQP, custom TCP protocols)</li><li>You need sub-millisecond overhead</li><li>The backend handles TLS directly</li><li>Maximum throughput matters more than routing intelligence</li></ul><p><strong>Example:</strong> A banking system routing database read replicas through an internal HAProxy TCP load balancer. The LBR doesn’t need to understand PostgreSQL. It just needs to distribute TCP connections across three replica nodes.</p><pre>App Servers<br>    │<br>    ▼<br>HAProxy (TCP mode, Layer 4)<br>    │         │         │<br>    ▼         ▼         ▼<br>Postgres  Postgres  Postgres<br>Replica1  Replica2  Replica3</pre><h3>Layer 7 (Application Layer)</h3><p>The load balancer terminates the HTTP connection, reads the request fully — headers, URL path, cookies, request body — and then makes a routing decision based on that content.</p><p><strong>It’s smarter because it sees more.</strong></p><p>Use it when:</p><ul><li>Traffic is HTTP or HTTPS</li><li>You need to route /api/* to one service and /static/* to another</li><li>You need cookie-based session stickiness</li><li>You want the load balancer to return a custom error page when backends are down</li><li>You need to rate limit by a specific header value</li></ul><p><strong>Example:</strong> An e-commerce platform routes API requests to a Node.js backend and static assets to an Nginx file server, all behind one load balancer.</p><pre>User Request: GET /api/products<br>User Request: GET /static/logo.png<br>         │<br>         ▼<br>    HAProxy (HTTP mode, Layer 7)<br>         │<br>    reads the URL path<br>         │<br>    /api/*  ──────► API Backend Pool  (Node.js)<br>    /static/* ────► Static Asset Pool (Nginx/S3)</pre><h3>Real-World Use Cases Across Different Organizations</h3><h3>1. E-Commerce Platform (Flipkart / Amazon Scale)</h3><p>During a sale, traffic spikes 10–20x in seconds. A single server cannot handle this. The load balancer:</p><ul><li>Distributes incoming requests across dozens of application servers</li><li>Detects when one server is struggling (high response time, 5xx errors) and stops sending it traffic</li><li>Routes /checkout to a dedicated high-priority backend pool that&#39;s never shared with browse traffic</li><li>Applies rate limiting so one IP can’t make 10,000 requests per second and starve everyone else</li></ul><p>Without the load balancer, the first server in your DNS rotation dies in the first 30 seconds of the sale. The rest sit idle.</p><h3>2. Banking / FinTech (Multi-Region)</h3><p>A bank operates in Kenya, Tanzania, and Uganda. Each country has its own regulatory requirement to process transactions locally. The load balancer:</p><ul><li>Routes by geographic origin — Kenyan transactions go to Kenyan servers</li><li>Maintains session stickiness for transaction flows — your payment doesn’t get split across two servers mid-flight</li><li>Handles TLS termination centrally so every backend doesn’t need to manage certificates</li><li>Monitors backend health every 2 seconds — if the Tanzania server has a DB issue, traffic stops going there before users see errors</li></ul><p>A critical detail here: in regulated FinTech environments, load balancers often sit in a zero-internet-access network. All traffic is internal. The LBR communicates exclusively with internal private services. Nothing touches the public internet from the backend tier.</p><h3>3. SaaS Product (Multi-Tenant, B2B)</h3><p>A SaaS company serves 500 enterprise customers. Each customer has a subdomain: company1.app.com, company2.app.com. The load balancer:</p><ul><li>Uses host-header-based routing to send each subdomain to the correct tenant’s application instance</li><li>Applies different rate limits per customer tier (free plan vs enterprise plan)</li><li>Routes /api/v1/* to the old backend and /api/v2/* to the new backend, enabling blue-green deployments without downtime</li></ul><pre># HAProxy ACL-based routing<br>acl is_company1 hdr(host) -i company1.app.com<br>acl is_api_v2   path_beg /api/v2</pre><pre>use_backend company1_servers if is_company1<br>use_backend api_v2_servers   if is_api_v2<br>default_backend api_v1_servers</pre><h3>4. Streaming Platform (Hotstar / Netflix)</h3><p>Millions of users start watching at the same time when a match begins. The load balancer:</p><ul><li>Distributes WebSocket connections for live streaming — each user maintains a persistent connection</li><li>Routes by content type — video segment requests go to CDN-edge servers, API requests go to application servers</li><li>Enables gradual traffic shifting during deployments — send 10% of traffic to new encoder version, watch error rates, then shift 100%</li></ul><p>Persistent connections require special handling. WebSocket and gRPC connections stay open for minutes to hours. The load balancer needs timeout tunnel set to hours, not the default 30 seconds that works for regular HTTP.</p><h3>5. Internal Platform / Microservices</h3><p>A company with 50 microservices has each service calling 5 others. Internal load balancing handles east-west traffic — service to service. Kubernetes does this automatically with Services and kube-proxy, but at scale, teams replace it with a service mesh (Istio, Linkerd) that adds observability, circuit breaking, and mTLS between services.</p><pre>Service A<br>    │<br>    ▼<br>Internal Load Balancer (kube-proxy / Istio)<br>    │         │         │<br>    ▼         ▼         ▼<br>Service B  Service B  Service B<br>  Pod 1      Pod 2      Pod 3</pre><h3>Load Balancing Algorithms — Which One and When</h3><p>The algorithm is what decides which backend gets the next request. Wrong choice for your workload costs you in latency, capacity waste, and hotspotting.</p><h3>Round Robin</h3><p>The default. Server 1 gets request 1, server 2 gets request 2, server 3 gets request 3, back to server 1.</p><pre>Request  1 → Server A<br>Request  2 → Server B<br>Request  3 → Server C<br>Request  4 → Server A  ← back to start</pre><p><strong>Works for:</strong> Stateless apps where every request takes roughly the same time — simple REST APIs, static content.</p><p><strong>Breaks for:</strong> Any workload where response times vary. If Server A is handling a 5-second database export and Server B is handling 10ms ping-pong requests, round robin sends them equal traffic. Server A queues. Server B sits idle.</p><h3>Weighted Round Robin</h3><p>Same as Round Robin but you assign a weight to each server. A server with weight 3 gets 3x the traffic of a server with weight 1.</p><pre>server app1 10.0.0.1:8080 check weight 3   # Gets 3x traffic<br>server app2 10.0.0.2:8080 check weight 1   # Gets 1x traffic</pre><p><strong>Works for:</strong> Mixed hardware where some servers are more powerful. New server being introduced gradually (start at weight 1, promote over time). Canary deployments — new version at weight 1, old version at weight 9.</p><h3>Least Connections</h3><p>Routes each new request to the server currently handling the fewest active connections.</p><pre>Server A: 50 active connections  ← next request goes here<br>Server B: 80 active connections<br>Server C: 65 active connections</pre><p><strong>Works for:</strong> Variable-duration requests — file uploads, report generation, streaming, anything where one request might take 10x longer than another. This is smarter than Round Robin for most real workloads because it naturally compensates for slow backends.</p><p><strong>Example:</strong> An image processing service where some images take 100ms and some take 3 seconds. Round Robin piles requests onto a server already processing 20 heavy jobs. Least Connections sees 20 active connections on that server and avoids it.</p><h3>IP Hash (Source IP Affinity)</h3><p>Hashes the client’s IP address and always routes that IP to the same server.</p><pre>Client 192.168.1.10  → always Server A (hash of 192.168.1.10 = A)<br>Client 192.168.1.20  → always Server B (hash of 192.168.1.20 = B)</pre><p><strong>Works for:</strong> Layer 4 stickiness when you can’t use cookies. Legacy apps that store session data locally and have no Redis.</p><p><strong>Breaks badly when:</strong> Clients are behind corporate NAT — a thousand users all look like one IP. 100% of their traffic hits one server while others sit idle. Avoid unless you have no other option.</p><h3>URI Hash</h3><p>Hashes the request URL and routes the same URL to the same backend.</p><pre>GET /product/123  → always Server A<br>GET /product/456  → always Server B<br>GET /product/123  → always Server A  ← cache hit on Server A</pre><p><strong>Works for:</strong> Cache servers where you want the same content to always land on the same node, maximizing cache hit rate. CDN origin tier.</p><h3>Random with Power of Two</h3><p>Picks 2 random backends, routes to the one with fewer connections. Sounds odd. It works.</p><p>The mathematical reason: pure “least connections” creates a thundering herd — every new connection calculation picks the same “least loaded” server simultaneously. Power of two random choices avoids this while still being smarter than pure random.</p><p><strong>Works for:</strong> Large backend pools at high request rates. Used internally by Netflix, Twitter, and similar scale.</p><h3>Algorithm Selection Guide</h3><p>Workload Algorithm Stateless API, uniform response times Round Robin Mixed server capacity Weighted Round Robin Variable request duration Least Connections Cache tier URI Hash Legacy app with local sessions IP Hash (last resort) Very large pools, high concurrency Random (Power of Two)</p><h3>Health Checks — The Part That Prevents Disasters</h3><p>The load balancer needs to know which backends are alive. Health checks are how it knows.</p><h3>TCP Check</h3><p>“Can I open a port?”</p><pre>server app1 10.0.0.1:8080 check   # Default: TCP only</pre><p>This is the default in most configurations. It is also nearly useless for real health detection.</p><p><strong>The problem:</strong> The port can be open while the application is deadlocked, out of memory, returning 500 on every request, or unable to reach its database. TCP open means the process is running. It says nothing about whether the process is functional.</p><h3>HTTP Check</h3><p>“Does the app return 200 OK to a health endpoint?”</p><pre>option httpchk GET /health HTTP/1.1<br>http-check expect status 200<br>server app1 10.0.0.1:8080 check</pre><p>Better — but only if /health actually checks something real.</p><p>A health endpoint that looks like this is useless:</p><pre>@app.route(&#39;/health&#39;)<br>def health():<br>    return {&quot;status&quot;: &quot;ok&quot;}, 200   # Always returns 200</pre><p>A health endpoint that means something:</p><pre>@app.route(&#39;/health&#39;)<br>def health():<br>    try:<br>        db.execute(&quot;SELECT 1&quot;)           # Can we reach the database?<br>        redis_client.ping()              # Can we reach the cache?<br>        if queue_consumer.is_running():  # Is our message consumer alive?<br>            return {&quot;status&quot;: &quot;ok&quot;}, 200<br>    except Exception as e:<br>        return {&quot;status&quot;: &quot;error&quot;, &quot;reason&quot;: str(e)}, 503</pre><p>When any critical dependency fails, return 503. Let the load balancer remove you from rotation before users see errors. That is the entire point.</p><h3>Health Check Timing</h3><pre>server app1 10.0.0.1:8080 check inter 2s fall 3 rise 2</pre><ul><li>inter 2s — check every 2 seconds</li><li>fall 3 — 3 consecutive failures marks the server DOWN</li><li>rise 2 — 2 consecutive successes after recovery marks it UP again</li></ul><p>fall 3 is the standard. fall 1 catches failures faster but causes flapping on transient blips. fall 5 tolerates more noise but keeps a broken server in rotation longer. Tune based on how stable your backends are.</p><h3>TLS Termination — Where HTTPS Ends</h3><p>Every HTTPS request is encrypted. Someone has to decrypt it. That’s TLS termination.</p><p><strong>At the load balancer (standard):</strong></p><pre>Browser ──HTTPS──► Load Balancer ──HTTP──► Backend<br>                   (decrypts here)         (plaintext)</pre><p>The load balancer holds the SSL certificate and private key. It decrypts incoming traffic and forwards plaintext HTTP to backends. Backends don’t need to manage certificates. Certificates are managed in one place.</p><p><strong>Why this matters:</strong> Certificate renewal, cipher updates, and TLS configuration changes happen at one point in your architecture. Not on every backend server individually.</p><p><strong>At the backend (passthrough):</strong></p><pre>Browser ──HTTPS──► Load Balancer ──HTTPS──► Backend<br>                   (passes through)          (decrypts here)</pre><p>The load balancer doesn’t read the traffic. It just forwards the encrypted stream. Used when compliance requires end-to-end encryption and no component between client and server may see plaintext — common in PCI-DSS and banking environments.</p><p><strong>Cost:</strong> The load balancer loses L7 visibility. It can’t route by URL path, can’t read headers, can’t inject request IDs. All it can do is TCP-level routing.</p><h3>Session Stickiness — When You Need the Same User on the Same Server</h3><p>If your application stores session data on the server (not in Redis or a database), you have a problem with load balancing: user logs in on Server A, next request goes to Server B, Server B has no session data, user is logged out.</p><p>Session stickiness solves this by routing the same user to the same server.</p><p><strong>Cookie-based (the right way for HTTP):</strong></p><pre>cookie SERVERID insert indirect nocache<br>server app1 10.0.0.1:8080 check cookie app1<br>server app2 10.0.0.2:8080 check cookie app2</pre><p>HAProxy injects a cookie into the response: Set-Cookie: SERVERID=app1. On the next request, the browser sends this cookie back and HAProxy routes to app1.</p><p>The user never sees this cookie. It’s transparent.</p><p><strong>The real answer:</strong> Sticky sessions are a workaround for stateful applications. The actual fix is moving session storage to Redis or a database so any server can serve any user. Sticky sessions create uneven load (Server A handles all your heaviest users because they happened to log in when it was picked) and complicate deployments (you can’t restart Server A without logging out those users).</p><p>Design stateless. Use sticky sessions only when you can’t.</p><h3>Capacity Planning — The Numbers You Need to Know</h3><p>A load balancer has limits. They’re not always obvious.</p><p>The fundamental formula (Little’s Law):</p><pre>concurrent connections = requests per second × average response time (seconds)</pre><pre>Example:<br>- 5,000 requests/second<br>- Average response time: 200ms = 0.2 seconds<br>- Concurrent connections = 5,000 × 0.2 = 1,000</pre><p>Add a safety buffer of 2x for burst. Your maxconn should be 2,000 in this example.</p><p>Set it too low and you queue. Queue too long and users get timeouts. Queue fills completely and users get connection refused.</p><p>This is the number that causes most LBR incidents in teams that “set and forgot” their configuration two years ago.</p><h3>What Breaks and What to Do</h3><h3>502 Bad Gateway</h3><p>The load balancer connected to the backend but the backend closed the connection without responding properly. Common cause: backend keepalive timeout is shorter than the load balancer’s, so the backend closes a connection the LBR thought was still valid.</p><p>Fix: configure option http-server-close on HAProxy to close backend connections after each request, removing the keepalive mismatch.</p><h3>503 Service Unavailable</h3><p>The load balancer has no healthy backend to send the request to. Either all backends are failing health checks, all backends are at their connection limit and the queue is full, or someone accidentally put all backends in maintenance mode during a deployment.</p><pre># See backend state immediately<br>echo &quot;show servers state&quot; | socat stdio /var/run/haproxy/admin.sock</pre><h3>504 Gateway Timeout</h3><p>The backend connected successfully but didn’t respond before the configured timeout expired. Could mean the backend is slow, the backend is hanging, or your timeout is set too low for the workload. Don’t just raise the timeout without understanding why the backend is slow.</p><h3>Backend Flapping (UP/DOWN rapidly)</h3><p>Health check interval shorter than the time a backend needs to recover. Or backend under memory pressure causing repeated GC pauses that fail health checks. Fix: increase fall count, add slowstart for gradual traffic ramp-up after recovery.</p><h3>TLS Certificates in Production — What Actually Gets Configured and Why</h3><p>This is the section most blog posts skip. They explain what TLS is. They don’t explain what you actually put on the server, where it lives, and what the difference is between a CA-signed cert and a self-signed one when you’re managing real infrastructure.</p><h3>The Three Certificate Scenarios You’ll Actually Encounter</h3><p><strong>Scenario 1: Public-facing traffic — CA-signed certificate</strong></p><p>Any service that end users reach through a browser needs a certificate issued by a trusted Certificate Authority (CA) — Let’s Encrypt, DigiCert, Sectigo, or similar. Browsers ship with a list of trusted CAs. If your cert isn’t from one of them, users see a warning.</p><p>What actually lives on your HAProxy server:</p><pre>/etc/ssl/haproxy/<br>├── fullchain.pem     ← your cert + all intermediate certs concatenated<br>├── privkey.pem       ← your private key (chmod 600, owned by haproxy user)<br>└── dhparam.pem       ← Diffie-Hellman params for perfect forward secrecy</pre><p>HAProxy wants a single file containing both the certificate chain and private key. You concatenate them:</p><pre># Combine fullchain and private key into one file HAProxy can read<br>cat /etc/ssl/haproxy/fullchain.pem /etc/ssl/haproxy/privkey.pem \<br>  &gt; /etc/ssl/haproxy/haproxy.pem<br>chmod 600 /etc/ssl/haproxy/haproxy.pem<br>chown haproxy:haproxy /etc/ssl/haproxy/haproxy.pem</pre><p>Then reference it in config:</p><pre>frontend https_front<br>    bind *:443 ssl crt /etc/ssl/haproxy/haproxy.pem<br>    bind *:80<br>    http-request redirect scheme https unless { ssl_fc }<br>    default_backend app_servers</pre><p><strong>The intermediate certificate trap:</strong> Your cert alone is not enough. You need the full chain — your cert plus every intermediate CA cert between yours and the root CA. If you only put your cert, some clients (older Android, certain curl versions) reject the handshake. The symptom is intermittent SSL errors that only some users hit.</p><p>Always use fullchain.pem from Let&#39;s Encrypt, or manually concatenate intermediates when using commercial CAs.</p><p><strong>Scenario 2: Internal traffic between services — Self-signed certificate</strong></p><p>In private networks — internal microservice communication, backend-to-database TLS, internal monitoring — you don’t need a public CA. You generate your own. This is common in FinTech environments where internal services must communicate over TLS but the services never touch the public internet.</p><p>Generate a self-signed cert:</p><pre># Generate private key<br>openssl genrsa -out /etc/ssl/internal/server.key 2048</pre><pre># Generate Certificate Signing Request<br>openssl req -new \<br>  -key /etc/ssl/internal/server.key \<br>  -out /etc/ssl/internal/server.csr \<br>  -subj &quot;/C=IN/ST=Maharashtra/L=Pune/O=YourOrg/CN=internal-api.yourdomain.local&quot;</pre><pre># Self-sign it (valid for 365 days)<br>openssl x509 -req -days 365 \<br>  -in /etc/ssl/internal/server.csr \<br>  -signkey /etc/ssl/internal/server.key \<br>  -out /etc/ssl/internal/server.crt</pre><pre># Verify<br>openssl x509 -in /etc/ssl/internal/server.crt -text -noout | grep -E &quot;Subject|Not After&quot;</pre><p>The problem with raw self-signed certs: every client that connects needs to either trust that specific cert explicitly or disable certificate verification. Disabling verification defeats the purpose. Trusting one cert at a time doesn’t scale.</p><p><strong>Scenario 3: Internal PKI — Self-signed CA signing internal certs (the right way)</strong></p><p>Instead of per-server self-signed certs, you create your own internal Certificate Authority. Your CA signs every internal service cert. Every machine trusts your CA. One trust relationship scales to all services.</p><pre># Step 1: Create your internal CA<br>openssl genrsa -out /etc/ssl/ca/ca.key 4096<br>openssl req -new -x509 -days 3650 \<br>  -key /etc/ssl/ca/ca.key \<br>  -out /etc/ssl/ca/ca.crt \<br>  -subj &quot;/C=IN/O=YourOrg Internal CA/CN=YourOrg Root CA&quot;</pre><pre># Step 2: Generate a key + CSR for HAProxy (or any internal service)<br>openssl genrsa -out /etc/ssl/haproxy/internal.key 2048<br>openssl req -new \<br>  -key /etc/ssl/haproxy/internal.key \<br>  -out /etc/ssl/haproxy/internal.csr \<br>  -subj &quot;/C=IN/O=YourOrg/CN=haproxy.internal.yourdomain.local&quot;</pre><pre># Step 3: CA signs the cert<br>openssl x509 -req -days 365 \<br>  -in /etc/ssl/haproxy/internal.csr \<br>  -CA /etc/ssl/ca/ca.crt \<br>  -CAkey /etc/ssl/ca/ca.key \<br>  -CAcreateserial \<br>  -out /etc/ssl/haproxy/internal.crt</pre><pre># Step 4: Distribute CA cert to all servers that need to trust internal certs<br>cp /etc/ssl/ca/ca.crt /usr/local/share/ca-certificates/yourorg-internal-ca.crt<br>update-ca-certificates</pre><p>Now any service can verify HAProxy’s cert by checking it against your internal CA. No browser warnings. No --insecure flags. Actual trust.</p><h3>Production HAProxy TLS Configuration — The Full Picture</h3><p>This is a complete, production-grade TLS frontend block with every relevant security setting explained:</p><pre>global<br>    # TLS tuning — global defaults applied to all binds<br>    ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384<br>    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets<br>    ssl-default-server-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256<br>    ssl-default-server-options ssl-min-ver TLSv1.2<br>    tune.ssl.default-dh-param 2048        # DH key size for DHE ciphers<br>    tune.ssl.cachesize 20000              # SSL session cache entries<br>    tune.ssl.lifetime 300                 # Cache SSL sessions for 5 minutes</pre><pre>frontend https_public<br>    bind *:443 ssl crt /etc/ssl/haproxy/haproxy.pem alpn h2,http/1.1<br>    # alpn h2,http/1.1 enables HTTP/2 via ALPN negotiation</pre><pre>    # Force HTTPS — redirect all HTTP to HTTPS<br>    bind *:80<br>    http-request redirect scheme https code 301 unless { ssl_fc }</pre><pre>    # HSTS — tell browsers to only use HTTPS for 1 year<br>    http-response set-header Strict-Transport-Security &quot;max-age=31536000; includeSubDomains; preload&quot;</pre><pre>    # Security headers<br>    http-response set-header X-Frame-Options DENY<br>    http-response set-header X-Content-Type-Options nosniff<br>    http-response set-header X-XSS-Protection &quot;1; mode=block&quot;<br>    http-response set-header Referrer-Policy no-referrer-when-downgrade</pre><pre>    # Strip headers clients might use to spoof internal auth<br>    http-request del-header X-Internal-Token<br>    http-request del-header X-Admin-Override<br>    http-request del-header X-Forwarded-For    # strip before we add our own<br>    option forwardfor                           # now add a clean X-Forwarded-For</pre><pre>    # Add request ID for log correlation<br>    http-request set-header X-Request-ID %[uuid()]</pre><pre>    default_backend app_servers</pre><pre>frontend https_internal<br>    # Internal services use cert signed by internal CA<br>    bind *:8443 ssl crt /etc/ssl/haproxy/internal.pem \<br>                    ca-file /etc/ssl/ca/ca.crt \<br>                    verify required    # mTLS — client must present cert too</pre><pre>    default_backend internal_services</pre><p>The verify required line on the internal frontend is mTLS — the client must also present a certificate signed by your internal CA. Any service without a valid cert gets rejected at the TLS handshake, before a single byte of application traffic is processed.</p><h3>Certificate Expiry — The Incident That Happens on a Schedule</h3><p>Certificate expiry is not an unknown unknown. It happens on a date you can calculate the moment you issue the cert. Yet it takes down production systems regularly because nobody owns the renewal.</p><p>Alerts to set up — mandatory:</p><pre># Script to check cert expiry and alert — run daily via cron<br>#!/bin/bash<br>DOMAINS=(&quot;api.yourdomain.com&quot; &quot;app.yourdomain.com&quot; &quot;internal.yourdomain.local&quot;)<br>ALERT_DAYS=30</pre><pre>for domain in &quot;${DOMAINS[@]}&quot;; do<br>    expiry=$(echo | openssl s_client \<br>        -servername &quot;$domain&quot; \<br>        -connect &quot;$domain:443&quot; 2&gt;/dev/null \<br>        | openssl x509 -noout -enddate 2&gt;/dev/null \<br>        | cut -d= -f2)</pre><pre>    if [ -n &quot;$expiry&quot; ]; then<br>        expiry_epoch=$(date -d &quot;$expiry&quot; +%s)<br>        now_epoch=$(date +%s)<br>        days_left=$(( (expiry_epoch - now_epoch) / 86400 ))</pre><pre>        if [ &quot;$days_left&quot; -lt &quot;$ALERT_DAYS&quot; ]; then<br>            echo &quot;ALERT: $domain expires in $days_left days ($expiry)&quot;<br>            # pipe to Slack webhook, PagerDuty, email — your call<br>        fi<br>    fi<br>done</pre><p>Let’s Encrypt certificates are valid for 90 days. Automate renewal with certbot:</p><pre># Auto-renew and reload HAProxy<br>certbot renew --deploy-hook &quot;cat /etc/letsencrypt/live/yourdomain.com/fullchain.pem \<br>  /etc/letsencrypt/live/yourdomain.com/privkey.pem \<br>  &gt; /etc/ssl/haproxy/haproxy.pem &amp;&amp; systemctl reload haproxy&quot;</pre><h3>HAProxy Log Format — What Every Line Is Actually Telling You</h3><p>HAProxy logs are dense. Every character means something. Most engineers read them for the first time during a P0 and spend 10 minutes figuring out the format instead of the problem. Learn it before you need it.</p><h3>Default Log Format</h3><p>A standard HAProxy HTTP access log line:</p><pre>Jan 15 09:23:41 haproxy[1234]: 203.0.113.45:52341 [15/Jan/2024:09:23:41.123] https_front app_servers/app1 10/0/1/243/254 200 1452 - - ---- 45/45/12/8/0 0/0 &quot;POST /api/payment HTTP/1.1&quot;</pre><p>Breaking this apart field by field:</p><pre>Jan 15 09:23:41          → syslog timestamp<br>haproxy[1234]            → process name and PID<br>203.0.113.45:52341       → client IP and source port<br>[15/Jan/2024:09:23:41.123] → request accept time (millisecond precision)<br>https_front              → frontend name that accepted the connection<br>app_servers/app1         → backend name / server name that handled it<br>10/0/1/243/254           → time breakdown (ms) — explained below<br>200                      → HTTP response status code<br>1452                     → bytes transferred to client<br>-                        → captured request cookie (- = none captured)<br>-                        → captured response cookie (- = none captured)<br>----                     → termination state flags — explained below<br>45/45/12/8/0             → connection counts — explained below<br>0/0                      → queue position / queue depth<br>&quot;POST /api/payment HTTP/1.1&quot; → HTTP request line</pre><h3>Time Breakdown Field — The Most Useful Field in the Log</h3><p>10/0/1/243/254 — five numbers separated by slashes. Each is a duration in milliseconds.</p><pre>Tq / Tw / Tc / Tr / Tt</pre><pre>Tq = 10   → time to receive full HTTP request from client<br>Tw = 0    → time request spent waiting in queue (0 = no queuing)<br>Tc = 1    → time to establish TCP connection to backend<br>Tr = 243  → time backend took to send full response<br>Tt = 254  → total time from accept to last byte sent to client</pre><p><strong>How to use this during an incident:</strong></p><ul><li>Tw &gt; 0 sustained? → backends saturated, maxconn too low, add capacity</li><li>Tc high (&gt;100ms)? → network problem between LBR and backend, or backend not listening</li><li>Tr high? → backend is slow — application or database problem, not LBR</li><li>Tt ≈ Tr? → all time is in backend processing, LBR overhead is negligible</li><li>Tq high? → client sending requests slowly (large uploads, slow clients)</li></ul><h3>Termination State Flags — Why the Connection Ended</h3><p>The ---- field has four characters. Each position means something different.</p><p><strong>Position 1 — Session state when closed:</strong></p><pre>C → closed while waiting for client to send request (client timeout/disconnect)<br>D → closed while waiting in queue (queue timeout)<br>L → closed while waiting for LBR to send response to client<br>R → closed while waiting for server to respond<br>T → closed on timeout (any phase)<br>- → normal close, all data transferred</pre><p><strong>Position 2 — How the session was closed:</strong></p><pre>C → client aborted (closed connection)<br>P → proxy decided to close (e.g., option forceclose)<br>R → server reset the connection<br>S → server aborted<br>- → normal close</pre><p><strong>Position 3 — Cookie status:</strong></p><pre>N → no cookie set or found<br>I → cookie found but server doesn&#39;t exist (stale stickiness)<br>D → cookie found, server exists but is DOWN<br>U → cookie found and valid<br>- → cookies not tracked</pre><p><strong>Position 4 — Persistence / switching:</strong></p><pre>N → no persistence used<br>I → used but ignored (server was down)<br>U → persistence used successfully<br>- → not applicable</pre><p><strong>Common flag combinations you’ll see in logs and what they mean:</strong></p><pre>---- → Normal request. Everything worked. Move on.<br>cD-- → Client disconnected while waiting in queue. Backend was too slow.<br>       Action: check Tw field, check backend capacity.</pre><pre>SC-- → Server closed connection abruptly. Likely backend crash or timeout.<br>       Action: check backend logs, check if keepalive mismatch.</pre><pre>-H-- → Connection closed by HAProxy (header parsing error or security rule).<br>       Action: check if client sent malformed request.</pre><pre>cH-- → Client abort during header reading.<br>       Action: usually bots or scanners. Check source IP.</pre><pre>RR-- → Both sides reset. Network issue between LBR and backend.<br>       Action: check network path, firewall rules.</pre><h3>HAProxy Error Log Entries — What They Look Like in Practice</h3><p>HAProxy writes two types of log entries: access logs (one per request) and event logs (backend state changes, errors, health checks).</p><p><strong>Backend goes DOWN:</strong></p><pre>Jan 15 09:45:12 haproxy[1234]: Server app_servers/app1 is DOWN, reason: Layer7 timeout, check duration: 2001ms. 2 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.</pre><p>Fields: server name, reason (Layer4/Layer7 + what failed), check duration, remaining servers, active sessions.</p><p><strong>Backend comes UP:</strong></p><pre>Jan 15 09:47:33 haproxy[1234]: Server app_servers/app1 is UP, reason: Layer7 check passed, code: 200, check duration: 12ms. 3 active and 0 backup servers online.</pre><p><strong>Connection refused to backend:</strong></p><pre>Jan 15 10:12:04 haproxy[1234]: Connect() failed for server app_servers/app2: Connection refused.</pre><p>This is econ — the LBR couldn&#39;t establish TCP. Backend process not running or port not listening.</p><p><strong>SSL handshake failure:</strong></p><pre>Jan 15 10:33:21 haproxy[1234]: SSL handshake failure (no shared cipher)</pre><p>Cipher suite mismatch. Client supports ciphers the LBR doesn’t offer, or vice versa.</p><p><strong>Rate limit hit:</strong></p><pre>Jan 15 11:02:55 haproxy[1234]: [15/Jan/2024:11:02:55.441] https_front app_servers/&lt;NOSRV&gt; 0/-1/-1/-1/0 429 212 - - PR-- 0/0/0/0/0 0/0 &quot;GET /api/data HTTP/1.1&quot;</pre><p>&lt;NOSRV&gt; in the server field means the request was blocked before reaching a backend. PR-- means HAProxy denied it (proxy rule). 429 is the configured deny status.</p><p><strong>Request blocked by ACL:</strong></p><pre>Jan 15 11:15:03 haproxy[1234]: [15/Jan/2024:11:15:03.221] https_front &lt;NOSRV&gt;/&lt;NOSRV&gt; 0/-1/-1/-1/0 403 212 - - PR-- ...</pre><p>Same pattern. Something in the frontend ACLs rejected this before a backend was selected.</p><p><strong>Queue timeout — backend saturated:</strong></p><pre>Jan 15 14:22:17 haproxy[1234]: [15/Jan/2024:14:22:17.334] https_front app_servers/&lt;NOSRV&gt; 4/30001/-1/-1/30005 503 212 - - sQ-- 50/50/50/50/25 25/100 &quot;GET /api/orders HTTP/1.1&quot;</pre><p>Tw = 30001 — request waited 30 seconds in queue. sQ-- — closed due to queue timeout. 503 to client. The 50/50/50/50/25 connection counts show the backend pool is maxed.</p><h3>Custom Log Format for Production Debugging</h3><p>The default format is good. This format is better for production:</p><pre>defaults<br>    log-format &quot;%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %{+Q}r %[ssl_fc_protocol] %[ssl_fc_cipher]&quot;</pre><p>This adds SSL protocol and cipher to every access log line — useful when debugging TLS issues without needing to run packet captures.</p><h3>Log Rotation — Keeping 10 Days of HAProxy Logs on the Server</h3><p>HAProxy logs to syslog by default. On most Linux systems that means rsyslog writes to /var/log/haproxy/haproxy.log. At any meaningful traffic level, that file grows fast. Without rotation, it fills the disk.</p><h3>Step 1 — Verify HAProxy Is Logging to a Dedicated File</h3><p>In /etc/rsyslog.d/49-haproxy.conf:</p><pre># Capture HAProxy logs to dedicated file<br>if $programname == &#39;haproxy&#39; then /var/log/haproxy/haproxy.log<br>&amp; stop</pre><p>Create the directory with correct ownership:</p><pre>mkdir -p /var/log/haproxy<br>chown syslog:adm /var/log/haproxy<br>chmod 750 /var/log/haproxy<br>systemctl restart rsyslog</pre><h3>Step 2 — Write the Logrotate Configuration</h3><p>Create /etc/logrotate.d/haproxy:</p><pre>/var/log/haproxy/haproxy.log {<br>    # Rotate daily<br>    daily</pre><pre>    # Keep 10 days of rotated logs<br>    rotate 10</pre><pre>    # Compress rotated files with gzip<br>    compress</pre><pre>    # Don&#39;t compress the most recent rotated file<br>    # (gives rsyslog time to finish writing before compression)<br>    delaycompress</pre><pre>    # Don&#39;t error if log file is missing<br>    missingok</pre><pre>    # Don&#39;t rotate if log file is empty<br>    notifempty</pre><pre>    # Don&#39;t create a new empty log file after rotation<br>    # rsyslog creates it automatically on next write<br>    nocreate</pre><pre>    # Date extension instead of .1 .2 .3<br>    # Produces: haproxy.log-20240115.gz instead of haproxy.log.1.gz<br>    dateext<br>    dateformat -%Y%m%d</pre><pre>    # After rotation, signal rsyslog to reopen the log file<br>    # Without this, rsyslog keeps writing to the rotated file<br>    postrotate<br>        /usr/lib/rsyslog/rsyslog-rotate<br>    endscript<br>}</pre><h3>Step 3 — Separate Access Log from Error/Event Log (Production Pattern)</h3><p>HAProxy mixes access logs and event logs (backend state changes, health check results) into one stream by default. In production, separate them. Access logs are high-volume and machine-parsed. Event logs are low-volume and need human attention.</p><p>In haproxy.cfg:</p><pre>global<br>    log /dev/log local0 notice   # event logs (backend UP/DOWN, errors) → notice level<br>    log /dev/log local1 info     # access logs → info level</pre><p>In rsyslog (/etc/rsyslog.d/49-haproxy.conf):</p><pre># HAProxy event logs (backend state, health checks, errors)<br>if $programname == &#39;haproxy&#39; and $syslogseverity &lt;= 5 then /var/log/haproxy/events.log<br>&amp; stop</pre><pre># HAProxy access logs (one line per request)<br>if $programname == &#39;haproxy&#39; then /var/log/haproxy/access.log<br>&amp; stop</pre><p>Logrotate config for both:</p><pre>/var/log/haproxy/access.log<br>/var/log/haproxy/events.log {<br>    daily<br>    rotate 10<br>    compress<br>    delaycompress<br>    missingok<br>    notifempty<br>    nocreate<br>    dateext<br>    dateformat -%Y%m%d<br>    sharedscripts</pre><pre>    postrotate<br>        /usr/lib/rsyslog/rsyslog-rotate<br>    endscript<br>}</pre><p>sharedscripts runs postrotate once even though two files are listed. Without it, rsyslog gets signaled twice.</p><h3>Step 4 — Test and Verify</h3><pre># Dry run — shows what logrotate would do without doing it<br>logrotate -d /etc/logrotate.d/haproxy</pre><pre># Force a rotation right now (for testing)<br>logrotate -f /etc/logrotate.d/haproxy</pre><pre># Verify rotation happened<br>ls -lh /var/log/haproxy/<br># Expected output:<br># haproxy.log              ← current, active<br># haproxy.log-20240115.gz ← yesterday, compressed<br># haproxy.log-20240114.gz<br># ... 10 days total</pre><pre># Verify HAProxy is still logging after rotation<br>tail -f /var/log/haproxy/haproxy.log<br># Send a test request — should appear immediately<br>curl -sI <a href="https://your-lbr-host/health">https://your-lbr-host/health</a></pre><h3>Step 5 — Cron Schedule Verification</h3><p>Logrotate is triggered by cron. Verify it’s set up:</p><pre># Most distros run logrotate daily via this file<br>cat /etc/cron.daily/logrotate</pre><pre># Manually check when it last ran<br>stat /var/lib/logrotate/status | grep Modify</pre><pre># Check logrotate status file to confirm haproxy rotations<br>grep haproxy /var/lib/logrotate/status<br># Output example:<br># &quot;/var/log/haproxy/access.log&quot; 2024-1-15-6:25:1<br># &quot;/var/log/haproxy/events.log&quot; 2024-1-15-6:25:1</pre><h3>Disk Space Estimate — Know Before You Configure</h3><p>Before setting rotate 10, estimate how much disk 10 days of logs consumes:</p><pre># Check current log file growth rate<br>ls -lh /var/log/haproxy/haproxy.log</pre><pre># Check existing rotated files sizes<br>du -sh /var/log/haproxy/*.gz 2&gt;/dev/null</pre><pre># Rough formula:<br># Uncompressed: ~200 bytes per request × RPS × 86400 seconds<br># At 1000 RPS: 200 × 1000 × 86400 = ~17GB/day uncompressed<br># After gzip: typically 5-10x compression = ~2-3GB/day compressed<br># 10 days = ~20-30GB for 1000 RPS workload</pre><pre># Check available disk<br>df -h /var/log</pre><p>If disk is constrained, either reduce rotate days or ship logs to an external store (ELK, Loki, S3) and keep only 2-3 days locally.</p><h3>The Production Reality</h3><p>Most outages where the load balancer is blamed are actually:</p><ul><li><strong>Backend problems</strong> the health check didn’t catch (health endpoint lied)</li><li><strong>Configuration problems</strong> — someone changed a timeout, an ACL, a maxconn value</li><li><strong>Deployment problems</strong> — backends were re-enabled after deploy by a script that failed silently</li><li><strong>Capacity problems</strong> — traffic grew, nobody updated maxconn</li></ul><p>The load balancer itself failing is rare if it’s set up correctly. The load balancer passing traffic to broken backends because of a bad health check is not rare. That’s the gap most teams don’t address until they’ve lived through the P0 it produces.</p><h3>Summary</h3><p>A load balancer is not complicated in concept. It accepts connections, picks a backend, forwards traffic, and checks health. Every feature is an extension of one of those four things.</p><p>What makes it complex is the combination of: traffic patterns that don’t fit the algorithm you chose, health checks that don’t reflect reality, timeouts that don’t match your workload, and configuration that hasn’t been reviewed since the service was first deployed.</p><p>The engineers who handle LBR incidents calmly aren’t smarter. They’ve just read the logs once when nothing was on fire, so they know what they’re looking at when everything is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ef975f8c81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Balancers: The DevOps Engineer’s Complete Survival Guide]]></title>
            <link>https://medium.com/@udayrajdhavande8/load-balancers-the-devops-engineers-complete-survival-guide-0ef08e3c1c75?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ef08e3c1c75</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[load-balancer]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 05:37:23 GMT</pubDate>
            <atom:updated>2026-06-29T05:37:23.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-UYcm8_UG-EKDGJJJS0gg.png" /></figure><blockquote><em>From first principles to P0 war rooms — what your LBR is actually doing, when to look at it, and what to look for.</em></blockquote><h3>Table of Contents</h3><ol><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#1-what-a-load-balancer-actually-does">What a Load Balancer Actually Does</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#2-layer-4-vs-layer-7">Layer 4 vs Layer 7 — Why It Matters in Production</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#3-lbr-in-your-architecture">LBR in Your Architecture: Where It Sits and Why</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#4-key-concepts">Key Concepts Every Engineer Must Know</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#5-algorithms">Load Balancing Algorithms — Pick the Right One</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#6-health-checks">Health Checks: The Core Mechanism</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#7-connections-and-stickiness">Persistent Connections, Keep-Alive, and Session Stickiness</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#8-tls">TLS Termination and Passthrough</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#9-metrics">What to Monitor: Metrics That Matter</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#10-incident-response">Incident Response by Severity: P0 → P3</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#11-sanity-checks">Sanity Checks: LBR Audit Checklist</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#12-implementation-specific">Implementation-Specific: HAProxy, OpenResty/Nginx, AWS ALB/NLB</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#13-failure-patterns">Common Failure Patterns and Root Causes</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#14-capacity-planning">Capacity Planning for Load Balancers</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#15-security">Security Perspective</a></li><li><a href="https://claude.ai/chat/ea221df4-da18-4ed0-a866-baa84b133ec2#16-blog-post">Blog Post: “Your Load Balancer Is Lying to You”</a></li></ol><h3>1. What a Load Balancer Actually Does</h3><p>A load balancer sits between clients and your backend pool and does exactly four things:</p><ol><li><strong>Accepts inbound connections</strong> — terminates or proxies TCP/HTTP connections from clients.</li><li><strong>Selects a backend</strong> — picks which upstream server gets the request, based on a configured algorithm.</li><li><strong>Forwards the request</strong> — either as a new connection (reverse proxy) or transparently (DSR).</li><li><strong>Reports health</strong> — continuously checks backends and removes unhealthy ones from rotation.</li></ol><p>That’s the whole contract. Everything else — SSL offload, rate limiting, WAF, header manipulation, request routing — is a feature layered on top.</p><h3>What it is NOT</h3><ul><li>A firewall (though it can enforce some rules)</li><li>A substitute for application-level circuit breaking</li><li>A solution for your slow database</li><li>Infinitely scalable on its own</li></ul><p>Understanding these limits is the first step to not blaming the LBR for problems it didn’t cause.</p><h3>2. Layer 4 vs Layer 7</h3><p>This distinction dictates what the LBR can see, what it can do, and how it fails.</p><h3>Layer 4 (Transport Layer)</h3><p>Operates on TCP/UDP. Sees: source IP, destination IP, ports. Does NOT see: HTTP headers, URLs, cookies, request bodies.</p><pre>Client → LBR → Backend<br>         ↑<br>      TCP stream routing only<br>      No HTTP awareness</pre><p><strong>Use when:</strong></p><ul><li>Non-HTTP traffic (PostgreSQL, ActiveMQ, custom TCP protocols)</li><li>You need maximum throughput with minimal latency</li><li>Backend handles TLS itself (passthrough)</li><li>You can’t afford the overhead of HTTP parsing</li></ul><p><strong>Tools:</strong> HAProxy TCP mode, AWS NLB, bare nginx stream block</p><p><strong>Limitation:</strong> Can’t do path-based routing, can’t inspect request bodies, health checks are TCP-only (port reachable ≠ app healthy).</p><h3>Layer 7 (Application Layer)</h3><p>Operates on HTTP/HTTPS. Sees: headers, URLs, cookies, request bodies, response codes.</p><pre>Client → LBR (terminates TLS, parses HTTP) → Backend<br>         ↑<br>      Full HTTP visibility<br>      Can rewrite headers, route by path, sticky sessions via cookie</pre><p><strong>Use when:</strong></p><ul><li>HTTP/HTTPS traffic</li><li>You need path-based routing (/api/* → service A, /static/* → service B)</li><li>Session stickiness via cookies</li><li>You need to rate limit by header values</li><li>You want to return custom error pages when backends are down</li></ul><p><strong>Tools:</strong> HAProxy HTTP mode, OpenResty/Nginx upstream, AWS ALB, Kong Gateway</p><p><strong>Limitation:</strong> Higher CPU overhead per request, more complex failure modes, TLS overhead.</p><h3>In Practice — Mixing Both</h3><p>Most production architectures use both. Example from a FinTech stack:</p><pre>External traffic<br>     ↓<br>  HAProxy (L7) — TLS termination, path routing, rate limiting<br>     ↓<br>  Backend Kubernetes Services (NodePort)<br>     ↓<br>  Internal HAProxy (L4) — PostgreSQL/ActiveMQ connection distribution<br>     ↓<br>  Database / MQ cluster</pre><h3>3. LBR in Your Architecture</h3><h3>Where It Sits</h3><p>Load balancers appear at multiple tiers. Know which tier you’re debugging.</p><pre>Internet<br>   │<br>   ▼<br>[Edge / CDN] (optional — Cloudflare, Akamai)<br>   │<br>   ▼<br>[External Load Balancer]<br>   │   HAProxy / AWS ALB / NLB / OpenResty<br>   │   Public IP, TLS termination, DDoS protection<br>   ▼<br>[Internal Load Balancer / Service Mesh]<br>   │   Kubernetes kube-proxy (iptables/IPVS), Istio, Linkerd<br>   │   East-west traffic between services<br>   ▼<br>[Application Backends]<br>   │<br>   ▼<br>[Database-tier Load Balancer] (optional)<br>       PgBouncer, ProxySQL, HAProxy TCP mode</pre><h3>What Each Tier Owns</h3><p>Tier What it loads Who configures it What breaks it Edge LBR Public traffic DevOps/Infra DDoS, cert expiry, upstream timeouts Internal LBR Service-to-service Platform/DevOps Misconfigured ACLs, health check failures, backend flapping DB-tier LBR Connection pooling DBA/DevOps Connection exhaustion, failover events, split-brain</p><h3>4. Key Concepts</h3><h3>Frontend / Listener / VIP</h3><p>The IP:Port combination the LBR listens on. “Frontend” in HAProxy. “Listener” in AWS. “Virtual IP” in IPVS. This is the entry point.</p><h3>Backend / Upstream / Target Group</h3><p>The pool of servers that receives traffic. In HAProxy: backend. In Nginx: upstream. In AWS ALB: Target Group.</p><h3>ACL (Access Control List)</h3><p>Layer 7 routing rules. HAProxy ACLs inspect HTTP content and decide which backend gets the request. Example:</p><pre>acl is_api path_beg /api<br>use_backend api_servers if is_api</pre><h3>Connection Queue</h3><p>When all backend connections are saturated, new connections wait in the queue. Queue depth × queue timeout = max tolerated backlog. In HAProxy: maxconn per server and per frontend. Queue buildup is a leading indicator of backend slowness, not LBR slowness.</p><h3>Timeout Cascade</h3><pre>Client ←connect timeout→ LBR ←connect timeout→ Backend<br>        ←queue timeout→<br>        ←server timeout→         ←app processing→<br>        ←tunnel timeout→ (for websockets/persistent connections)</pre><p>Every timeout has a specific meaning. Matching the right timeout to the right symptom is half the debugging job.</p><p>Timeout What it covers Typical value timeout connect Time to establish TCP to backend 5s–10s timeout client Client idle time 30s–60s timeout server Backend response time 30s–120s timeout queue Max wait in connection queue 10s–30s timeout tunnel Persistent/tunnel connections (WebSocket, gRPC) 1h–24h timeout http-request Time to receive full HTTP request 5s–30s timeout http-keep-alive Keep-alive idle timeout 5s–10s</p><h3>maxconn</h3><p>maxconn is not just a tuning knob — it&#39;s a contract. maxconn on a server tells HAProxy &quot;do not send more than N concurrent connections to this backend.&quot; Requests beyond that go to the queue. Understand this before touching it. Raising it blindly will saturate your backend, not fix your latency.</p><h3>5. Algorithms</h3><h3>Round Robin</h3><p>Default. Distributes evenly across backends in order.</p><p><strong>Use:</strong> Stateless apps with similar response times.<br> <strong>Problem:</strong> Backend B with a slow database gets the same traffic as Backend A with a warm cache. Not actually “equal.”</p><h3>Weighted Round Robin</h3><p>Same as above but assigns more requests to higher-weight servers.<br> <strong>Use:</strong> Backends with different capacities (e.g., different VM sizes).</p><h3>Least Connections</h3><p>Sends new requests to the backend with the fewest active connections.<br> <strong>Use:</strong> Variable request durations. Long-running requests (file uploads, report generation).<br> <strong>Why it’s better than RR for most real workloads:</strong> It naturally adapts to slow backends.</p><h3>Least Response Time (HAProxy: leastconn + slowstart)</h3><p>Combines connection count with response time data.<br> <strong>Use:</strong> When backends have uneven cache hit rates or JIT warmup.</p><h3>IP Hash / Source IP</h3><p>Routes the same client IP to the same backend every time.<br> <strong>Use:</strong> Session stickiness without cookie support (L4 only).<br> <strong>Problem:</strong> Traffic distribution breaks when clients are behind NAT (all traffic looks like one IP).</p><h3>URI Hash</h3><p>Routes based on hash of the request URI.<br> <strong>Use:</strong> Cache servers (same URL always hits same cache node).</p><h3>Random (with power of 2)</h3><p>Picks 2 random backends, routes to the one with fewer connections.<br> <strong>Why:</strong> Avoids thundering herd on a single “least connections” winner.</p><h3>6. Health Checks</h3><p>Health checks are the most important LBR feature and the most commonly misconfigured.</p><h3>Types</h3><h4>TCP Check</h4><p>“Can I open a socket to port X?”</p><pre>server app1 10.0.0.1:8080 check</pre><p><strong>Problem:</strong> Port open ≠ app healthy. The app can be deadlocked, OOMed, or returning 500s while the port is still accepting connections.</p><h4>HTTP Check</h4><p>“Does the app return a 200 OK to GET /health?&quot;</p><pre>option httpchk GET /health HTTP/1.1<br>http-check expect status 200<br>server app1 10.0.0.1:8080 check</pre><p><strong>Better.</strong> But your /health endpoint needs to actually check its dependencies (DB connectivity, cache connectivity, critical background workers). An endpoint that just returns {&quot;status&quot;: &quot;ok&quot;} unconditionally is a health check in name only.</p><h4>Custom Check (HAProxy agent-check)</h4><p>A separate TCP port where your app reports its own health score. Your app can tell the LBR “I’m at 80% capacity, send me less traffic” or “take me out of rotation.”</p><pre>server app1 10.0.0.1:8080 check agent-check agent-port 9999</pre><h3>Health Check Parameters — What to Set and Why</h3><pre>server app1 10.0.0.1:8080 check inter 2s fall 3 rise 2</pre><p>Parameter Meaning Default (HAProxy) Recommended inter Interval between checks 2s 2–5s fall Consecutive failures before marking DOWN 3 3 rise Consecutive successes before marking UP 2 2–3 fastinter Interval when backend is transitioning same as inter 500ms–1s downinter Interval when backend is already DOWN same as inter 10–30s (reduce noise)</p><p><strong>The tradeoff:</strong> fall 1 catches failures faster but increases flapping risk. fall 5 tolerates transient blips but keeps a dead server in rotation longer. Production default: fall 3.</p><h3>Grace Period and slowstart</h3><p>When a new backend comes up, it’s cold. Its JVM hasn’t JIT-compiled, its caches are empty, its connection pools are filling. Sending it full traffic immediately causes latency spikes.</p><pre>server app1 10.0.0.1:8080 check slowstart 60s</pre><p>slowstart 60s ramps traffic from 0 to full weight over 60 seconds. Use this on every backend that has warmup behavior.</p><h3>7. Connections and Stickiness</h3><h3>TCP Keep-Alive vs HTTP Keep-Alive</h3><p>These are different things.</p><p><strong>TCP Keep-Alive:</strong> OS-level probes that detect dead connections. Prevents half-open connections from sitting idle forever.</p><p><strong>HTTP Keep-Alive (HTTP persistent connections):</strong> Reusing a single TCP connection for multiple HTTP request-response pairs. Reduces connection setup overhead. Default in HTTP/1.1.</p><p>In HAProxy, option http-server-close and option forwardfor affect how the LBR handles keep-alive between itself and backends. Know your mode:</p><p>Mode What it does option http-keep-alive Keep-alive to both client and server option http-server-close Keep-alive to client, close to server after each request option forceclose Close connections on both sides after each request option http-tunnel Pass raw data without HTTP analysis (for WebSocket, etc.)</p><h3>Session Stickiness (Persistence)</h3><p>When your app is not fully stateless (session data on the instance, not in Redis), you need to route the same user to the same backend across requests.</p><p><strong>Cookie-based (preferred for L7):</strong></p><pre>cookie SERVERID insert indirect nocache<br>server app1 10.0.0.1:8080 check cookie app1<br>server app2 10.0.0.2:8080 check cookie app2</pre><p>HAProxy injects a Set-Cookie: SERVERID=app1 header. Subsequent requests with that cookie go to app1.</p><p><strong>Source IP-based:</strong></p><pre>balance source</pre><p>Fragile. Breaks with load balancers in the request path, NAT, and VPNs. Avoid when possible.</p><p><strong>The right answer:</strong> Make your app stateless. Sticky sessions are a workaround for apps that store session state locally. If you’re designing from scratch, use Redis/Memcached for session storage and drop stickiness entirely.</p><h3>8. TLS Termination and Passthrough</h3><h3>TLS Termination (Offload)</h3><p>The LBR decrypts TLS, forwards plaintext HTTP to backends.</p><pre>Client ──TLS──► LBR ──HTTP──► Backend</pre><p><strong>Advantages:</strong> Backends don’t need certs. Centralized cert management. LBR can inspect/manipulate HTTP headers. WAF can see plaintext.</p><p><strong>Disadvantages:</strong> LBR holds the private key. Traffic inside the data center is unencrypted (mitigate with mTLS if required). LBR CPU usage increases with TLS overhead.</p><p><strong>HAProxy TLS termination:</strong></p><pre>frontend https_front<br>    bind *:443 ssl crt /etc/ssl/certs/fullchain.pem<br>    default_backend app_servers</pre><h3>TLS Passthrough</h3><p>LBR forwards encrypted TCP stream directly to backend without decrypting.</p><pre>Client ──TLS──► LBR ──TLS──► Backend (decrypts itself)</pre><p><strong>Use when:</strong> End-to-end encryption is required by compliance (PCI-DSS, HIPAA). Backend has hardware HSM.</p><p><strong>Cost:</strong> LBR can only do L4 routing. No HTTP header inspection.</p><pre>frontend tcp_front<br>    bind *:443<br>    mode tcp<br>    default_backend app_servers_tls</pre><pre>backend app_servers_tls<br>    mode tcp<br>    server app1 10.0.0.1:443 check</pre><h3>mTLS (Mutual TLS)</h3><p>Both client and server present certificates. Used for service-to-service authentication in zero-trust architectures. The LBR can participate as either a terminator or a passthrough.</p><h3>Certificate Rotation — What Can Go Wrong</h3><ul><li>Cert expires because no one owns the renewal (set alerts at 30d, 14d, 7d, 1d).</li><li>New cert deployed on LBR but with wrong chain (intermediate missing) → handshake failures from some clients.</li><li>SNI not configured → wrong cert served for multi-domain LBRs.</li><li>OCSP stapling broken → slow handshakes.</li></ul><pre># Quick cert expiry check<br>openssl s_client -connect yourdomain.com:443 -servername yourdomain.com &lt;/dev/null 2&gt;/dev/null \<br>  | openssl x509 -noout -dates</pre><pre># Check full chain<br>openssl s_client -connect yourdomain.com:443 -showcerts 2&gt;/dev/null | grep -E &quot;subject|issuer&quot;</pre><h3>9. What to Monitor: Metrics That Matter</h3><h3>The Five LBR Metric Categories</h3><pre>1. Traffic        — how much is coming in<br>2. Errors         — how much is failing<br>3. Saturation     — how close to limit you are<br>4. Latency        — how slow things are<br>5. Health         — backend pool state</pre><h3>HAProxy Metrics (via stats socket or Prometheus exporter)</h3><p>Metric What it tells you Alert threshold haproxy_frontend_sessions_total Total connections received Baseline + 3σ haproxy_frontend_current_sessions Active connections right now &gt; 80% of maxconn haproxy_backend_current_queue Requests waiting for a backend connection &gt; 0 sustained haproxy_backend_current_servers Backends currently UP &lt; N-1 (at least 1 down) haproxy_server_response_time_average_seconds Average response time per backend &gt; SLO threshold haproxy_backend_http_responses_total{code=&quot;5xx&quot;} 5xx errors from backends &gt; 1% of total haproxy_server_status Individual backend health (0=down, 1=up) == 0 haproxy_frontend_denied_connections_total Connections rejected by ACL/limits Any spike haproxy_backend_connection_errors_total Failures connecting to backend Any nonzero haproxy_frontend_bytes_in_total Inbound bandwidth &gt; 80% of link capacity</p><h3>AWS ALB Metrics (CloudWatch)</h3><p>Metric What it tells you Alert threshold TargetResponseTime Backend latency (p50, p95, p99) &gt; SLO HTTPCode_Target_5XX_Count 5xx from backends &gt; 1% of requests HTTPCode_ELB_5XX_Count 5xx from ALB itself (no backend answered) Any sustained HealthyHostCount UP backends in target group &lt; min required UnhealthyHostCount DOWN backends &gt; 0 RejectedConnectionCount Connections dropped (ALB at capacity) Any nonzero ActiveConnectionCount Current connections Capacity planning RequestCount Total requests Traffic baseline TargetConnectionErrorCount Errors connecting to targets Any spike</p><h3>OpenResty/Nginx Metrics (via stub_status or lua-resty-prometheus)</h3><p>Metric What it tells you nginx_connections_active Active connections nginx_connections_waiting Keep-alive connections idle nginx_http_requests_total Total requests nginx_upstream_response_time Backend latency nginx_upstream_status Per-backend HTTP status distribution</p><h3>Dashboard Design Principle</h3><p>Your LBR dashboard should answer these questions at a glance without clicking:</p><ol><li>Is traffic normal?</li><li>Is error rate within SLO?</li><li>Are all backends healthy?</li><li>Is anything queuing?</li><li>Is latency within SLO?</li></ol><p>Put these five panels on a single row. Everything else is detail.</p><h3>10. Incident Response by Severity</h3><h3>Mental Model: Where Does the LBR Fit?</h3><p>When an incident fires, the LBR is guilty until proven innocent IF:</p><ul><li>The symptom is traffic-wide (affecting all users, all paths)</li><li>The symptom correlates with a recent LBR config change</li><li>Backend metrics show backends are healthy but LBR metrics show errors</li></ul><p>The LBR is probably not the cause IF:</p><ul><li>Only specific backends are erroring (backend problem)</li><li>Only specific paths/services are affected (routing/app problem)</li><li>The LBR metrics are clean but backend metrics are degraded (downstream problem)</li></ul><h3>P0 — Complete Outage (All Traffic Down)</h3><p><strong>Definition:</strong> Service is unreachable. All users affected. Revenue impact every minute.</p><p><strong>When to look at the LBR:</strong> Immediately. It is the first hop after DNS.</p><p><strong>Investigation sequence:</strong></p><pre># Step 1: Can you reach the LBR VIP at all?<br>ping &lt;LBR_VIP&gt;<br>curl -I --connect-timeout 5 https://&lt;LBR_VIP&gt;/health</pre><pre># Step 2: Is the LBR process running?<br># HAProxy<br>systemctl status haproxy<br>haproxy -c -f /etc/haproxy/haproxy.cfg   # config validation<br>echo &quot;show info&quot; | socat stdio /var/run/haproxy/admin.sock</pre><pre># Step 3: How many backends are UP?<br>echo &quot;show servers state&quot; | socat stdio /var/run/haproxy/admin.sock | grep -v &quot;^#&quot;</pre><pre># Step 4: What are active sessions doing?<br>echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock | cut -d&#39;,&#39; -f1,2,5,6,7,18,19</pre><pre># Step 5: Is there a queue buildup?<br>echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock | awk -F&#39;,&#39; &#39;{print $1,$2,$3}&#39;</pre><p><strong>What you’re looking for in P0:</strong></p><p>Symptom Likely Cause Immediate Action LBR process not running Crash, OOM, bad config after reload Restart, check logs, rollback config All backends MAINT/DOWN Health check failing globally Check backend app status, check health endpoint LBR reachable but 502/503 No healthy backends Emergency: manually enable a backend, or failover LBR not reachable at all Network issue, VIP not responding Check upstream router/firewall, check if VIP is bound LBR reachable, returns 200 but wrong Content routing bug Rollback last config change</p><p><strong>P0 Escalation Criteria from LBR perspective:</strong></p><ul><li>All backends are marked DOWN and app teams confirm backends are healthy → LBR health check misconfiguration</li><li>LBR process crashed and auto-restart not recovering → escalate to infra lead</li><li>Config change in last 60 minutes → rollback immediately, diagnose after</li></ul><h3>P1 — Major Degradation (Significant User Impact)</h3><p><strong>Definition:</strong> Core functionality broken for &gt;25% of users, or critical path (payments, auth, core API) degraded.</p><p><strong>When to look at the LBR:</strong> After ruling out obvious app/backend issues. Look at LBR if:</p><ul><li>Error rate is elevated but some requests succeed</li><li>Latency is high but backends report normal processing time</li><li>Specific backends are cycling UP/DOWN (flapping)</li></ul><p><strong>Investigation sequence:</strong></p><pre># Check backend health and response time per server<br>echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock \<br>  | awk -F&#39;,&#39; &#39;NR&gt;1 {print $1,$2,$5,$6,$7,$19,$58}&#39; | column -t</pre><pre># Check queue depth<br>echo &quot;show info&quot; | socat stdio /var/run/haproxy/admin.sock | grep -E &quot;MaxConn|CurrConns|MaxConnRate&quot;</pre><pre># Look at error breakdown<br>echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock \<br>  | awk -F&#39;,&#39; &#39;{print $1,$2,$14,$15,$16}&#39; | head -30<br># Fields: proxy, server, ereq, econ, eresp (request errors, connection errors, response errors)</pre><pre># Check if any backend is in SOFT-STOPPED or DRAIN state<br>echo &quot;show servers state&quot; | socat stdio /var/run/haproxy/admin.sock</pre><pre># Recent log analysis<br>journalctl -u haproxy --since &quot;30 minutes ago&quot; | grep -E &quot;backend|server|DOWN|UP|timeout&quot; | tail -50</pre><p><strong>What you’re looking for in P1:</strong></p><p>Symptom Likely Cause Action One backend cycling DOWN/UP App on that host is sick (OOM, deadlock) Drain that backend, investigate the host Queue depth nonzero and growing Backends too slow, maxconn too low, or traffic spike Increase backend capacity or add emergency backend eresp high, econ low Backends connecting fine but returning errors Backend app issue, not LBR econ high LBR can&#39;t reach backends Network issue, backend not listening Specific path/service affected ACL routing bug Check recent ACL changes Latency high at LBR but not at backend LBR CPU saturated, or connection queue Check LBR host CPU, memory, network</p><p><strong>Backend draining for safe removal:</strong></p><pre># Gracefully drain a backend without dropping active connections<br>echo &quot;set server backend_name/server_name state drain&quot; | socat stdio /var/run/haproxy/admin.sock</pre><pre># Hard disable (immediate, drops in-flight)<br>echo &quot;set server backend_name/server_name state maint&quot; | socat stdio /var/run/haproxy/admin.sock</pre><pre># Re-enable<br>echo &quot;set server backend_name/server_name state ready&quot; | socat stdio /var/run/haproxy/admin.sock</pre><h3>P2 — Partial Degradation (Subset of Users / Non-Critical Path)</h3><p><strong>Definition:</strong> Non-critical features degraded, or &lt;25% of users affected.</p><p><strong>When to look at the LBR:</strong> When latency is elevated for a specific service or user segment.</p><p><strong>Investigation approach:</strong></p><pre># Check per-backend response times<br>echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock \<br>  | awk -F&#39;,&#39; &#39;{printf &quot;%s %s rtime=%s\n&quot;,$1,$2,$58}&#39; | grep -v &quot;^#&quot;</pre><pre># Check slow log (if configured)<br># HAProxy: set log-format to include %TR (time to receive request), %Tw (queue wait), %Tc (connect time), %Tr (response time)<br># Analyze log for specific backends<br>grep &quot;backend_name&quot; /var/log/haproxy/access.log | awk &#39;{print $NF}&#39; | sort -n | tail -20</pre><pre># Check if specific IPs are being rate limited<br>grep &quot;Denied&quot; /var/log/haproxy/access.log | awk &#39;{print $6}&#39; | sort | uniq -c | sort -rn | head -20</pre><pre># AWS ALB: check target response time per AZ<br>aws cloudwatch get-metric-statistics \<br>  --namespace AWS/ApplicationELB \<br>  --metric-name TargetResponseTime \<br>  --dimensions Name=LoadBalancer,Value=&lt;ARN&gt; \<br>  --start-time $(date -u -d &quot;1 hour ago&quot; +%Y-%m-%dT%H:%M:%S) \<br>  --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \<br>  --period 60 --statistics p99</pre><p><strong>P2 LBR-specific things to check:</strong></p><ul><li>Specific backend slower than peers? → heat check on that host</li><li>Rate limiting rules firing unexpectedly? → ACL review</li><li>SSL handshake time elevated? → cert chain issues, cipher mismatch, OCSP stapling</li><li>One AZ getting more traffic than expected? → AZ affinity configuration (AWS ALB: cross-zone load balancing)</li></ul><h3>P3 — Degraded Performance / Non-User-Impacting</h3><p><strong>Definition:</strong> Performance below SLO but not causing user-visible errors. Monitoring alert, not a user complaint.</p><p><strong>When to look at the LBR:</strong> Proactively, as part of the investigation.</p><p><strong>What to check:</strong></p><pre># Trend analysis — is maxconn approaching limit?<br>echo &quot;show info&quot; | socat stdio /var/run/haproxy/admin.sock | grep -E &quot;Maxconn|CurrConns&quot;</pre><pre># Check if SSL session cache is saturating<br>echo &quot;show info&quot; | socat stdio /var/run/haproxy/admin.sock | grep -i ssl</pre><pre># Long-lived connections that should have timed out<br>echo &quot;show sess&quot; | socat stdio /var/run/haproxy/admin.sock | wc -l</pre><pre># Health check timing distribution<br>grep &quot;health&quot; /var/log/haproxy/haproxy.log | tail -100 | awk &#39;{print $NF}&#39; | sort -n</pre><p><strong>Typical P3 LBR findings:</strong></p><ul><li>Maxconn at 70%+ → capacity planning needed, not urgent</li><li>Backend response time trending up over 24h → early indicator of backend degradation</li><li>Health check failures that recover quickly → flapping, investigate backend stability</li><li>SSL session cache hit rate dropping → tune tune.ssl.cachesize</li></ul><h3>11. Sanity Checks: LBR Audit Checklist</h3><p>Run this when: you inherit an architecture, before a production change, after a major incident, or quarterly as part of your reliability review.</p><h3>Configuration Sanity</h3><pre># HAProxy: Validate config before reload (never skip this)<br>haproxy -c -f /etc/haproxy/haproxy.cfg<br>echo &quot;Exit code: $?&quot;</pre><pre># Check for default_backend (what happens when no ACL matches?)<br>grep &quot;default_backend&quot; /etc/haproxy/haproxy.cfg</pre><pre># Verify maxconn values are set and sensible<br>grep -E &quot;maxconn|timeout&quot; /etc/haproxy/haproxy.cfg</pre><pre># Check that all backends have health checks configured<br>grep -A5 &quot;^backend&quot; /etc/haproxy/haproxy.cfg | grep -v &quot;check&quot;<br># Any line showing a server without &quot;check&quot; is a problem</pre><h3>Backend Health Audit</h3><pre># HAProxy: Full backend state dump<br>echo &quot;show servers state&quot; | socat stdio /var/run/haproxy/admin.sock \<br>  | awk &#39;{print $2,$3,$4,$5,$6}&#39; | column -t<br># Look for: any server in DOWN or MAINT that shouldn&#39;t be</pre><pre># Check actual health endpoints are returning meaningful data<br>for backend_ip in 10.0.0.1 10.0.0.2 10.0.0.3; do<br>  status=$(curl -so /dev/null -w &quot;%{http_code}&quot; <a href="http://${backend_ip}:8080/health)">http://${backend_ip}:8080/health)</a><br>  echo &quot;${backend_ip}: ${status}&quot;<br>done</pre><pre># Verify health check hits a real check, not just a static 200<br># If /health returns 200 even when DB is down, your health check is worthless</pre><h3>TLS/Certificate Audit</h3><pre># Check cert expiry for all domains on the LBR<br>for domain in api.yourdomain.com app.yourdomain.com; do<br>  expiry=$(echo | openssl s_client -servername ${domain} -connect ${domain}:443 2&gt;/dev/null \<br>    | openssl x509 -noout -enddate 2&gt;/dev/null | cut -d= -f2)<br>  echo &quot;${domain}: ${expiry}&quot;<br>done</pre><pre># Check cipher suite strength<br>nmap --script ssl-enum-ciphers -p 443 your-lbr-host 2&gt;/dev/null | grep -E &quot;least|grade|cipher&quot;</pre><pre># Verify HSTS is set if you&#39;ve enabled HTTPS everywhere<br>curl -sI <a href="https://yourdomain.com/">https://yourdomain.com</a> | grep -i strict-transport</pre><pre># Check OCSP stapling<br>echo QUIT | openssl s_client -connect yourdomain.com:443 -status 2&gt;&amp;1 | grep -i ocsp</pre><h3>Timeout Configuration Audit</h3><pre># Extract all timeouts and verify they make sense<br>grep &quot;timeout&quot; /etc/haproxy/haproxy.cfg | sort -u</pre><pre># Cross-reference:<br># timeout server should be &gt; your slowest normal response time<br># timeout client should be &gt; timeout server<br># timeout connect should be &lt; 10s for most cases<br># timeout tunnel should be set to hours if you have WebSocket/gRPC</pre><h3>Capacity Audit</h3><pre># HAProxy: Current vs max connections<br>echo &quot;show info&quot; | socat stdio /var/run/haproxy/admin.sock \<br>  | grep -E &quot;^Maxconn|^CurrConns|^MaxConnRate|^ConnRate&quot;</pre><pre># Check OS limits (ulimit) — HAProxy needs enough file descriptors<br>ulimit -n  # Should be &gt; 2x maxconn (each connection = 2 FDs)<br>cat /proc/$(pidof haproxy)/limits | grep &quot;open files&quot;</pre><pre># Memory usage<br>echo &quot;show info&quot; | socat stdio /var/run/haproxy/admin.sock | grep -i mem</pre><pre># Check if LBR host is being throttled<br>dmesg | grep -i &quot;throttl\|OOM\|oom&quot;</pre><h3>Log Quality Audit</h3><pre># Verify LBR is logging with enough detail<br># Minimum: timestamp, client IP, status code, backend, response time</pre><pre># Check log rotation is configured<br>ls -la /etc/logrotate.d/ | grep haproxy<br>logrotate -d /etc/logrotate.d/haproxy</pre><pre># Check log volume is reasonable (anomaly if 0 or millions/min)<br>tail -f /var/log/haproxy/access.log | head -10</pre><pre># Verify you can correlate LBR logs with backend logs (X-Request-ID header set?)<br>grep &quot;x-request-id\|X-Forwarded-For&quot; /etc/haproxy/haproxy.cfg</pre><h3>Redundancy Audit</h3><pre># Is your LBR itself a SPOF?<br># Check if keepalived/VRRP is configured for LBR HA<br>systemctl status keepalived<br>ip addr show | grep -E &quot;VIP|virtual&quot;</pre><pre># HAProxy: Check if you have at least 2 LBR nodes<br># This is an architecture question — if answer is &quot;no&quot;, that&#39;s a P3 risk item</pre><pre># Verify failover has been tested recently<br># If &quot;we&#39;ve never tested LBR failover&quot; — that&#39;s a finding</pre><pre># Check backup/fallback backend is configured<br>grep &quot;backup&quot; /etc/haproxy/haproxy.cfg</pre><h3>Security Audit</h3><pre># Is the stats endpoint protected?<br>grep -A5 &quot;stats&quot; /etc/haproxy/haproxy.cfg | grep -E &quot;auth|uri|realm&quot;</pre><pre># Is admin socket permissions restricted?<br>ls -la /var/run/haproxy/admin.sock</pre><pre># Are internal headers stripped before forwarding to backend?<br>grep -E &quot;del-header|req.del-header&quot; /etc/haproxy/haproxy.cfg</pre><pre># Check if X-Forwarded-For is being set (for real IP logging)<br>grep &quot;forwardfor&quot; /etc/haproxy/haproxy.cfg</pre><pre># Rate limiting rules exist?<br>grep -E &quot;rate\|stick-table&quot; /etc/haproxy/haproxy.cfg</pre><h3>12. Implementation-Specific Reference</h3><h3>HAProxy</h3><p><strong>Config structure:</strong></p><pre>global      → process-level settings (maxconn, logging, socket, SSL tuning)<br>defaults    → default values inherited by frontends/backends<br>frontend    → listener (bind address, ACLs, routing rules)<br>backend     → server pool (algorithm, health checks, timeouts)<br>listen      → combined frontend+backend (shorthand, use sparingly)</pre><p><strong>Most important global settings:</strong></p><pre>global<br>    maxconn 50000              # Max concurrent connections<br>    nbthread 4                 # CPU threads (match physical CPU count)<br>    log /dev/log local0        # Syslog socket<br>    stats socket /var/run/haproxy/admin.sock mode 660 level admin expose-fd listeners<br>    ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256<br>    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets<br>    tune.ssl.default-dh-param 2048</pre><p><strong>Key operational commands:</strong></p><pre># Reload without dropping connections<br>systemctl reload haproxy<br># or<br>haproxy -sf $(pidof haproxy) -f /etc/haproxy/haproxy.cfg</pre><pre># Live stats<br>watch -n 1 &#39;echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock | cut -d&quot;,&quot; -f1,2,5,6,18,19&#39;</pre><pre># Enable/disable specific server<br>echo &quot;set server backend/server1 state maint&quot; | socat stdio /var/run/haproxy/admin.sock<br>echo &quot;set server backend/server1 state ready&quot; | socat stdio /var/run/haproxy/admin.sock</pre><pre># Change server weight live<br>echo &quot;set server backend/server1 weight 50&quot; | socat stdio /var/run/haproxy/admin.sock</pre><h3>OpenResty / Nginx Upstream</h3><p><strong>Config structure:</strong></p><pre>upstream backend_pool {<br>    least_conn;<br>    server 10.0.0.1:8080 weight=1 max_fails=3 fail_timeout=30s;<br>    server 10.0.0.2:8080 weight=1 max_fails=3 fail_timeout=30s;<br>    keepalive 32;               # Keep 32 idle connections to backends<br>}</pre><pre>server {<br>    listen 443 ssl;<br>    <br>    location /api {<br>        proxy_pass <a href="http://backend_pool;/">http://backend_pool;</a><br>        proxy_connect_timeout 5s;<br>        proxy_read_timeout 60s;<br>        proxy_send_timeout 60s;<br>        proxy_next_upstream error timeout http_502 http_503;<br>        proxy_next_upstream_tries 3;<br>    }<br>}</pre><p><strong>Key OpenResty additions (Lua-powered):</strong></p><pre>-- Dynamic backend health check via lua-resty-healthcheck<br>local healthcheck = require(&quot;resty.healthcheck&quot;)<br>local checker = healthcheck.new({<br>    name = &quot;backend_pool&quot;,<br>    shm_name = &quot;healthcheck&quot;,<br>    checks = {<br>        active = {<br>            type = &quot;http&quot;,<br>            http_path = &quot;/health&quot;,<br>            healthy = { interval = 2, successes = 2 },<br>            unhealthy = { interval = 1, http_failures = 3 }<br>        }<br>    }<br>})</pre><p><strong>Nginx-specific debugging:</strong></p><pre># Test config<br>nginx -t</pre><pre># Live reload<br>nginx -s reload</pre><pre># Check upstream status (if nginx-module-vts installed)<br>curl <a href="http://localhost/metrics">http://localhost/metrics</a> | grep nginx_upstream</pre><pre># Check error log for upstream errors<br>tail -f /var/log/nginx/error.log | grep upstream</pre><h3>AWS ALB</h3><p><strong>Key ALB concepts:</strong></p><ul><li><strong>Listener:</strong> Port + protocol (80/HTTP, 443/HTTPS)</li><li><strong>Target Group:</strong> Pool of EC2/ECS/Lambda/IP targets with health check config</li><li><strong>Routing Rules:</strong> Path-based, host-based, header-based</li></ul><p><strong>CLI operations:</strong></p><pre># Check target health<br>aws elbv2 describe-target-health \<br>  --target-group-arn arn:aws:elasticloadbalancing:region:account:targetgroup/name/id</pre><pre># Deregister a target<br>aws elbv2 deregister-targets \<br>  --target-group-arn &lt;TG_ARN&gt; \<br>  --targets Id=&lt;instance-id&gt;</pre><pre># Get ALB access logs (enable first in ALB attributes)<br>aws s3 ls s3://your-alb-logs-bucket/AWSLogs/account-id/elasticloadbalancing/</pre><pre># Parse ALB logs for 5xx errors<br>zcat /tmp/alb-log.gz | awk &#39;{print $9}&#39; | sort | uniq -c | sort -rn | head</pre><pre># CloudWatch: check for ALB-generated 5xx (vs target 5xx)<br># HTTPCode_ELB_5XX_Count &gt; 0 means the ALB itself is erroring (no targets available, request malformed, etc.)<br># HTTPCode_Target_5XX_Count &gt; 0 means targets are erroring</pre><p><strong>AWS NLB vs ALB — when to use which:</strong></p><p>Criterion ALB NLB Protocol HTTP, HTTPS, gRPC, WebSocket TCP, UDP, TLS Latency ~1–5ms overhead &lt;1ms Static IP No (use Route53 alias) Yes (Elastic IP per AZ) IP-based routing No Yes Source IP preservation Via X-Forwarded-For Native Price Higher Lower Use case Web apps, API Gateway UDP, TCP, extreme latency requirements</p><h3>13. Common Failure Patterns and Root Causes</h3><h3>Pattern 1: Backend Flapping (UP/DOWN rapidly)</h3><p><strong>Symptom:</strong> HAProxy logs show repeated Server backend/server1 is DOWN followed by is UP.<br> <strong>Cause:</strong> Health check interval shorter than backend startup/recovery time, or backend under GC pressure.<br> <strong>Fix:</strong> Increase fall count, add slowstart, investigate backend GC/memory.</p><pre># See flapping in real time<br>journalctl -fu haproxy | grep -E &quot;UP|DOWN&quot;</pre><pre># Count flap events in last hour<br>journalctl -u haproxy --since &quot;1 hour ago&quot; | grep -c &quot;is DOWN&quot;</pre><h3>Pattern 2: 502 Bad Gateway</h3><p><strong>Meaning:</strong> LBR connected to backend but backend closed the connection before responding, or returned an invalid response.</p><p><strong>Most common causes:</strong></p><ul><li>Backend process crashed mid-request</li><li>Backend keepalive timeout &lt; LBR keepalive timeout (backend closed connection the LBR thought was still valid)</li><li>Backend returned a malformed HTTP response</li></ul><p><strong>Fix for keepalive mismatch:</strong></p><pre># Nginx backends: set keepalive_timeout lower than HAProxy&#39;s timeout http-keep-alive<br># Or in HAProxy, use http-server-close to close backend connections after each request<br>option http-server-close</pre><h3>Pattern 3: 503 Service Unavailable</h3><p><strong>Meaning:</strong> LBR has no healthy backend to send the request to.</p><p><strong>Causes:</strong></p><ul><li>All backends health check failing</li><li>All backends at maxconn and queue is full</li><li>All backends in MAINT state</li></ul><p><strong>Immediate diagnostic:</strong></p><pre>echo &quot;show servers state&quot; | socat stdio /var/run/haproxy/admin.sock<br>echo &quot;show stat&quot; | socat stdio /var/run/haproxy/admin.sock | grep -E &quot;MAINT|DOWN|0,0&quot;</pre><h3>Pattern 4: Slow Response Under Load (Queue Buildup)</h3><p><strong>Symptom:</strong> p99 latency spikes under high traffic. haproxy_backend_current_queue &gt; 0.</p><p><strong>Cause:</strong> Backend pool can’t process requests fast enough. maxconn per server is the bottleneck.</p><p><strong>Diagnostic sequence:</strong></p><ol><li>Is haproxy_backend_current_queue &gt; 0? → backends saturated</li><li>Is backend CPU high? → app bottleneck</li><li>Is backend response time high even with 1 request? → downstream (DB?) bottleneck</li><li>Is backend CPU normal but queue building? → maxconn too conservative</li></ol><h3>Pattern 5: SSL Handshake Failures</h3><p><strong>Symptom:</strong> curl: (35) OpenSSL SSL_connect: Connection reset by peer</p><p><strong>Causes:</strong></p><ul><li>Cipher suite mismatch between client and LBR</li><li>TLS version mismatch (client tries TLS 1.3, LBR configured for max TLS 1.2)</li><li>Expired or mismatched certificate</li><li>Missing intermediate certificate in chain</li></ul><p><strong>Debug:</strong></p><pre># Verbose SSL debug<br>openssl s_client -connect yourdomain.com:443 -debug 2&gt;&amp;1 | head -50</pre><pre># Check what TLS versions the LBR accepts<br>nmap --script ssl-enum-ciphers -p 443 your-lbr-host</pre><h3>Pattern 6: IP Address Exhaustion (AWS NLB / NAT)</h3><p><strong>Symptom:</strong> Intermittent connection failures despite healthy targets. Only at high scale.</p><p><strong>Cause:</strong> Ephemeral port exhaustion on the LBR node. Each connection uses a source port. Range is 1024–65535 = ~64K ports. With connection recycling speed too slow or too many short-lived connections, you run out.</p><p><strong>Fix:</strong> Enable connection reuse (keepalive), reduce TIME_WAIT with net.ipv4.tcp_tw_reuse = 1, scale horizontally.</p><h3>14. Capacity Planning</h3><h3>Baseline These Numbers</h3><p>Before you can plan capacity, you need baselines:</p><ol><li><strong>Requests per second</strong> — current peak and average</li><li><strong>Concurrent connections</strong> — peak active connections (not RPS)</li><li><strong>Connection rate</strong> — new connections per second (important for TLS overhead)</li><li><strong>Throughput</strong> — MB/s inbound and outbound</li><li><strong>Backend response time</strong> — p50, p95, p99</li></ol><h3>Calculate maxconn from First Principles</h3><pre>maxconn = (peak RPS) × (avg response time in seconds) × (safety_factor)</pre><pre>Example:<br>- Peak RPS: 5000<br>- Avg response time: 100ms = 0.1s<br>- Safety factor: 2x</pre><pre>maxconn = 5000 × 0.1 × 2 = 1000 per backend</pre><p>This is Little’s Law applied. The safety factor handles burst and response time spikes.</p><h3>When to Scale the LBR Itself</h3><p>Signal Action CPU &gt; 70% sustained Scale up or add LBR node maxconn &gt; 80% of configured limit Increase maxconn (after validating OS limits) Network bandwidth &gt; 70% of link Scale up link or add node SSL connection rate high Consider hardware SSL offload or more CPU Memory &gt; 80% Investigate SSL session cache size, connection table</p><h3>LBR HA Architecture (Never Run a Single LBR)</h3><pre>┌─────────────┐<br>                    │   DNS / VIP  │  (Floating IP via VRRP/keepalived)<br>                    └──────┬──────┘<br>               ┌───────────┴──────────┐<br>               ▼                      ▼<br>         ┌──────────┐          ┌──────────┐<br>         │ HAProxy  │ ACTIVE   │ HAProxy  │ STANDBY<br>         │  Node 1  │◄─────────│  Node 2  │<br>         └────┬─────┘  keepalived └─────────┘<br>              │               shared state via rsync/Lua or peer protocol<br>              ▼<br>         Backend Pool</pre><p>Test your failover. Regularly. “We have HA configured” and “our HA actually works” are different statements.</p><h3>15. Security Perspective</h3><h3>What Attacks Hit Your LBR</h3><p>Attack What it does Mitigation SYN Flood Exhausts connection table with half-open connections tcp syncookies, maxconn, upstream DDoS protection Slowloris Sends partial HTTP requests slowly, holds connections timeout http-request, maxconn per-ip HTTP Flood High-volume HTTP requests to exhaust backend Rate limiting (stick-table in HAProxy) Large Request Body Exhausts backend resources option http-buffer-request, tune.bufsize Header Injection Malicious headers passed to backend Strip internal headers before forwarding</p><h3>HAProxy Rate Limiting</h3><pre># Stick table to track connection rate per IP<br>backend rate_limit_table<br>    stick-table type ip size 100k expire 30s store conn_rate(10s),http_req_rate(10s)</pre><pre>frontend https_front<br>    bind *:443 ssl crt /etc/ssl/certs/cert.pem<br>    <br>    # Track rate per IP<br>    stick on src table rate_limit_table<br>    <br>    # Block if &gt;100 HTTP requests in 10s<br>    http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }<br>    <br>    # Block if &gt;50 connections in 10s<br>    tcp-request connection reject if { sc_conn_rate(0) gt 50 }</pre><h3>Header Hygiene</h3><pre># Forward real client IP<br>option forwardfor</pre><pre># Remove internal headers clients might forge<br>http-request del-header X-Internal-Auth<br>http-request del-header X-Admin-Override<br>http-request del-header X-Real-IP</pre><pre># Set security headers on responses<br>http-response set-header X-Frame-Options SAMEORIGIN<br>http-response set-header X-Content-Type-Options nosniff<br>http-response set-header Referrer-Policy no-referrer-when-downgrade</pre><h3>16. Blog Post: “Your Load Balancer Is Lying to You”</h3><p><strong>Posted on Medium | DevOps &amp; SRE Series</strong></p><p>I’ve been on enough P0 calls to have a pattern in my head. Someone opens the incident channel, the alerts are firing, and the first thing a junior engineer says is: “The load balancer is fine, I checked the dashboard.”</p><p>Then we spend 45 minutes debugging the wrong layer before someone notices the LBR’s health checks are passing because the /health endpoint returns 200 even when the database is unreachable.</p><p>That’s not the load balancer being fine. That’s the load balancer lying to you in the most expensive way possible.</p><p>Let me explain what’s actually going on inside this thing we put in front of everything and then kind of forget about.</p><h3>The Load Balancer Is Not a Magic Traffic Wizard</h3><p>A load balancer does four things: accept connections, pick a backend, forward traffic, and check if backends are alive. That’s it. The complexity is entirely in the details of each step.</p><p>Most engineers treat LBRs like a black box because they’re “configured once and forgotten.” That’s fine until they’re not fine, and when they’re not fine, you need to know the internals fast.</p><p>The first thing I check in any incident where traffic looks wrong: <strong>is the LBR even in the picture?</strong> Pull up your LBR metrics dashboard. Three questions:</p><ol><li>Are backends healthy (all green)?</li><li>Is there any queue buildup (connections waiting)?</li><li>Is error rate elevated at the LBR, or at the backend?</li></ol><p>These three questions alone fork your investigation. LBR errors mean one thing. Backend errors mean something else. Queue buildup means your backends are slow, not your LBR.</p><h3>Health Checks: Where Everyone Gets Burned</h3><p>The default health check in most configurations is a TCP check. “Can I open a port?” TCP port open means nothing. The process could be deadlocked. The thread pool could be exhausted. The database connection pool could be at zero with nothing being released. The port is still open.</p><p>Move to HTTP health checks. But then make sure the endpoint actually checks your critical path. A /health endpoint that does this:</p><pre>@app.route(&#39;/health&#39;)<br>def health():<br>    return jsonify({&quot;status&quot;: &quot;ok&quot;}), 200</pre><p>…is a health check written by someone who’s never been on a P0 call where the app was returning 200 to the LBR while users got 500s on every payment request.</p><p>A health check that means something does this: checks DB connection, checks the message queue, checks whatever your app actually needs to function. If any of those fail, return 503. Let the LBR pull you from rotation. That’s the point.</p><h3>Timeouts Are Not Punishments</h3><p>Timeouts exist to prevent one slow request from blocking a connection forever. They’re not aggressive — they’re kind to the rest of your traffic.</p><p>When you see 504 Gateway Timeout, it doesn’t automatically mean your backend is slow. It means the LBR waited as long as it was configured to wait, and the backend didn’t respond. Maybe timeout server is set too low. Maybe the backend actually is slow. Maybe there&#39;s a network partition between the LBR and backend.</p><p>Each timeout has a name and a meaning. Learn them:</p><ul><li>timeout connect fires when the LBR can&#39;t establish TCP to your backend. This is usually a network problem or the backend isn&#39;t listening.</li><li>timeout server fires when the backend connected but didn&#39;t finish the response in time. This is an application performance problem.</li><li>timeout queue fires when a request sat in the connection queue too long. This is a capacity problem — your backend pool is saturated.</li></ul><p>When you see timeout errors, match the timeout type to the cause. Don’t just raise the number and move on. Raising timeout server from 30s to 120s might make the 504s stop but you&#39;ve just given your slow backend 4x the time to hold connections that should be failing fast.</p><h3>The Queue Is Your Early Warning System</h3><p>haproxy_backend_current_queue is the metric that tells you something is wrong before your users notice.</p><p>When queue depth is nonzero and growing, it means: your backends are responding slower than new requests are arriving. You haven’t hit timeout yet. No 503s yet. But you’re getting there.</p><p>This is the moment to act. Add capacity. Drain the slow backend. Scale out. You have maybe 2–5 minutes depending on your timeout configuration before this becomes a user-visible problem.</p><p>If you’re not monitoring queue depth, you’re flying without altitude.</p><h3>P0s and the LBR</h3><p>In a full outage, I check the LBR in the first 60 seconds. Not because it’s usually the cause — it usually isn’t — but because it’s the choke point. If the LBR process is down, or all backends are marked DOWN, or there’s a config reload that went wrong, I need to know that immediately.</p><pre>echo &quot;show servers state&quot; | socat stdio /var/run/haproxy/admin.sock</pre><p>That command tells me if any backend is in a state it shouldn’t be in. If all backends are MAINT when they should be READY, that’s a misconfigured deployment script that forgot to re-enable them. I’ve seen this in real production. The deploy ran, backends came up healthy, but the script that re-enabled them on the LBR failed silently. New code deployed, zero traffic, 100% error rate to users.</p><h3>Your LBR Is a Single Point of Failure Until It Isn’t</h3><p>I’ve talked to teams who have “highly available” infrastructure on paper: two app servers, a database replica, Redis sentinel. One load balancer.</p><p>One load balancer is not highly available. It’s a different single point of failure with better marketing.</p><p>Running HAProxy on two nodes with keepalived giving you a floating VIP takes about 3 hours to set up. After that, if one node dies, the VIP moves to the other in under a second. That’s the minimum for anything production.</p><p>And then you need to test it. Shut down the primary. Watch the VIP move. Watch traffic continue. If you haven’t done this, you don’t actually know if your HA is working. Configuration and behavior are not the same thing.</p><h3>The Three Things to Audit Right Now</h3><p>If you have an LBR in your architecture and you haven’t audited it recently:</p><p>Check your health check endpoint. Does it actually verify your application’s dependencies? Or does it return 200 unconditionally?</p><p>Check your timeout values. Are timeout server and your SLO aligned? Is timeout tunnel configured if you have WebSocket or gRPC connections?</p><p>Check your maxconn. Is it based on a calculation, or was it set years ago and never revisited? Compare it to your peak observed concurrent connections. Are you at 90% headroom? That&#39;s a P3 finding waiting to become a P1.</p><p>The load balancer is one of those things that earns trust through invisibility. When you can’t see it working, it’s working. The problem is when you start confusing “it’s invisible” with “it’s fine.” Those are not the same thing.</p><p>Your LBR is not lying because it wants to. It’s lying because you’re asking the wrong questions. Ask better ones.</p><p><em>Written from production experience managing FinTech banking infrastructure. All failure patterns described are real.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ef08e3c1c75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Real Teams Ship Code Without Breaking Each Other’s Work: A GitLab Git Workflow Guide]]></title>
            <link>https://medium.com/@udayrajdhavande8/how-real-teams-ship-code-without-breaking-each-others-work-a-gitlab-git-workflow-guide-66d942debfba?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/66d942debfba</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 05:52:12 GMT</pubDate>
            <atom:updated>2026-06-28T05:52:12.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJr9Gkkf-2RQDezon1TOSQ.png" /></figure><p>If you’ve worked at a company that actually ships frequently, you’ve probably noticed they don’t merge to main after every change. That would be chaos. Instead, teams keep main stable and do all their real work on branches — and only touch main when something is actually ready.</p><p>This guide covers how that works end-to-end: the repo structure, how multiple engineers push to the same branch without stepping on each other, what to do when conflicts happen, and how to stay sane in orgs that don’t use merge requests.</p><h3>The Monorepo Setup</h3><p>Let’s say you have a GitLab repo called nexus-platform. Inside it, three services live as subdirectories:</p><pre>nexus-platform/<br>├── nexus-api/        # Core API service<br>├── nexus-db/         # Database migrations and schema management<br>└── nexus-worker/     # Background job processor</pre><p>This is a monorepo. One repo, multiple deployable services.</p><p>Why monorepo? Because if nexus-api and nexus-db need a coordinated change, you want one commit, one branch, one PR. You don&#39;t want to orchestrate changes across three separate repos and pray the timing lines up.</p><h3>Branch Strategy: Why Main is Sacred</h3><p>The golden rule in this setup: <strong>main is always deployable</strong>. Nobody pushes directly to it. Every change goes through a branch.</p><p>Here’s what that looks like day-to-day:</p><pre>main              ─────────────────────────────────────────────<br>                       ↑                       ↑<br>feature/add-auth  ─────┴──────────             |<br>fix/db-timeout              ─────────────────── ┘</pre><p>When you start a new piece of work:</p><pre>git checkout main<br>git pull origin main<br>git checkout -b feature/JIRA-1042-add-oauth</pre><p>You push to your branch. CI picks it up, runs tests. Only when everything passes do you merge back to main.</p><p>This means main never has half-finished features, broken migrations, or someone&#39;s debug logs that got committed by accident.</p><h3>Multiple Engineers, One Branch</h3><p>Sometimes a whole team works on the same feature branch together. Say three backend engineers are all building out feature/payment-gateway. This is where discipline matters more than anything else.</p><h3>Pull Before You Touch Anything</h3><p>Before you start work every morning — before you open a file, before you change a line:</p><pre>git checkout feature/payment-gateway<br>git fetch origin<br>git pull origin feature/payment-gateway</pre><p>This one habit eliminates the majority of conflicts teams run into. Most conflict situations happen because someone worked on a stale copy of the branch for half a day, then tried to push.</p><h3>Pull Again Before You Push</h3><p>After you’ve done your work, before pushing:</p><pre>git fetch origin<br>git pull origin feature/payment-gateway<br># now push<br>git push origin feature/payment-gateway</pre><p>If someone pushed while you were working, this pulls their changes in first. If there are no conflicts, git merges automatically and you push cleanly. If there are conflicts, you resolve them locally before your push goes out.</p><h3>If Two People Push at the Same Time</h3><p>Happens constantly. Git won’t let the second person push:</p><pre>! [rejected]  feature/payment-gateway -&gt; feature/payment-gateway (fetch first)<br>error: failed to push some refs to &#39;git@gitlab.company.internal:team/nexus-platform.git&#39;<br>hint: Updates were rejected because the remote contains work that you do not have locally.</pre><p>The fix is always the same: pull first, then push.</p><pre>git pull origin feature/payment-gateway<br># resolve conflicts if there are any<br>git push origin feature/payment-gateway</pre><h3>Handling Merge Conflicts</h3><p>Conflicts are not failures. They’re git telling you that two people modified the same area of the same file and it can’t automatically figure out which version wins. You have to decide.</p><h3>What a Conflict Looks Like</h3><pre>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD<br>def process_payment(amount, currency=&quot;KES&quot;):<br>    return stripe.charge(amount, currency)<br>=======<br>def process_payment(amount, currency=&quot;USD&quot;, idempotency_key=None):<br>    return stripe.charge(amount, currency, idempotency_key=idempotency_key)<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt; origin/feature/payment-gateway</pre><p>HEAD is your local version. Below the ======= is what came from the remote. You need to decide what the final version should be.</p><p>In this case, someone added idempotency_key support, and someone else changed the default currency. The right answer probably keeps both:</p><pre>def process_payment(amount, currency=&quot;KES&quot;, idempotency_key=None):<br>    return stripe.charge(amount, currency, idempotency_key=idempotency_key)</pre><p>After editing, mark it resolved and commit:</p><pre>git add nexus-api/payments.py<br>git commit -m &quot;merge: resolve conflict in process_payment, keep idempotency + KES default&quot;<br>git push origin feature/payment-gateway</pre><h3>Preventing Conflicts in the First Place</h3><p>The cleanest way to avoid conflicts is to keep each person’s work in clearly separate files. If two engineers are both modifying payments.py, that&#39;s a coordination problem more than a git problem. Split the work so one person owns the webhook handler and another owns the refund logic.</p><p>For teams that can’t avoid the same files, shorter-lived branches help a lot. The longer a branch lives without syncing to main, the more diverged it gets and the worse the eventual conflict.</p><p>Rebasing periodically keeps your branch current:</p><pre>git fetch origin<br>git rebase origin/main</pre><p>This replays your commits on top of the latest main. If there are conflicts, git pauses and lets you resolve them one commit at a time:</p><pre># after resolving the conflicted file<br>git add .<br>git rebase --continue</pre><p>If the rebase gets complicated and you want to bail out completely:</p><pre>git rebase --abort</pre><p>You’re back to exactly where you started. No damage done.</p><h3>Merging Back to Main</h3><p>When the feature is done and tested, it goes to main.</p><h3>The Clean Merge</h3><pre>git checkout main<br>git pull origin main<br>git merge --no-ff feature/payment-gateway<br>git push origin main</pre><p>The --no-ff flag creates a merge commit even when a fast-forward is possible. This keeps the branch history visible in the log — you can look back and see &quot;here&#39;s exactly when the payment gateway was merged&quot; as one identifiable commit, instead of a pile of commits that look like they happened directly on main.</p><h3>Squash Merge (When the Branch Has Messy WIP Commits)</h3><p>If your branch has 27 commits with messages like “wip”, “fix typo”, “ok maybe this”, “ACTUALLY this” — squash before merging:</p><pre>git checkout main<br>git pull origin main<br>git merge --squash feature/payment-gateway<br>git commit -m &quot;feat: add payment gateway with Stripe webhook support (JIRA-1042)&quot;<br>git push origin main</pre><p>One clean commit on main that summarizes everything. The branch history still exists if you need to dig into it.</p><h3>Orgs That Don’t Use Merge Requests</h3><p>A lot of teams skip MRs entirely. You have push access, you push directly. No review gate.</p><p>This is more common than people admit — smaller engineering teams, shops that move fast and trust their developers. It’s not inherently wrong. It does mean the responsibility for not breaking things sits entirely with the developer pushing.</p><p>If you’re working in this model, a few things become more important:</p><p><strong>Communicate before touching shared code.</strong> If you know you’re about to modify a file two other people are also working in, say something in Slack. “Heads up, changing the DB config in nexus-db/config.py in ~20 mins.&quot; Saves everyone a round of conflict resolution.</p><p><strong>Write commit messages with enough context to make sense a month later.</strong> Without an MR description, the commit message is the only explanation anyone gets.</p><pre># Bad<br>git commit -m &quot;fix stuff&quot;</pre><pre># Good<br>git commit -m &quot;nexus-worker: increase job retry limit from 3 to 5 for external API timeouts&quot;</pre><p><strong>Signal when a branch is “ready.”</strong> Without MRs, there’s no obvious flag that a branch is done and ready to merge. Some teams use branch naming conventions (feature/done/payment-gateway), others use a Jira status, others just post in Slack. Whatever works — as long as people know.</p><h3>When Things Go Wrong</h3><h3>Pushed to the Wrong Branch</h3><p>Don’t panic. Revert the commit on the wrong branch, then cherry-pick it to the right one:</p><pre>git log --oneline -3   # find the commit SHA<br>git revert &lt;commit-sha&gt;<br>git push origin wrong-branch</pre><pre>git checkout right-branch<br>git cherry-pick &lt;original-commit-sha&gt;<br>git push origin right-branch</pre><p>Avoid git reset --hard on shared branches. It rewrites history and breaks everyone who already pulled since your push.</p><h3>Need to Undo a Merge on Main</h3><pre>git revert -m 1 &lt;merge-commit-sha&gt;<br>git push origin main</pre><p>-m 1 tells git which parent to treat as the mainline. This creates a new revert commit rather than rewriting history — which is what you want on a shared branch that others are already working from.</p><h3>Safe Practice Checklist</h3><p>Situation What to Do Starting new work Branch from latest main Start of every working day git pull origin &lt;your-branch&gt; before opening any file Before every push git pull again, then push Push rejected Pull, resolve if needed, push again Conflict markers in file Edit to correct state, git add, git commit Branch too far behind main git rebase origin/main, resolve, git rebase --continue Merging a feature branch --no-ff to preserve history, --squash for messy WIP branches No MR workflow Communicate in Slack, write good commit messages, signal when done Pushed to wrong branch git revert + git cherry-pick Need to undo a merge git revert -m 1 &lt;merge-commit-sha&gt;</p><p>The engineers who make this feel effortless are the ones who pull before they push, write commit messages that make sense to a stranger, and tell the person next to them before touching the same file.</p><p>Git handles the rest.</p><p><em>Have a workflow that burned you once and taught you something? Drop it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66d942debfba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Kubernetes Actually Pulls Images From Docker — The Part Nobody Explains]]></title>
            <link>https://medium.com/@udayrajdhavande8/how-kubernetes-actually-pulls-images-from-docker-the-part-nobody-explains-8151ad0c9d8d?source=rss-d0dbda6e7e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8151ad0c9d8d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Udayraj Dhavande]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 19:27:51 GMT</pubDate>
            <atom:updated>2026-06-26T19:27:51.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9Di5NFaEacwLfH6LtaxwA.png" /></figure><p><em>A breakdown for engineers who use Docker + K8s every day but have never looked under the hood</em></p><p>Everyone in tech has used Docker. Everyone talks about Kubernetes. But ask: “How exactly does Kubernetes pull a Docker image?” and you get silence, hand-waving, or a vague “it uses the registry.”</p><p>If you work in fintech, banking, or any service-based company running production workloads on a Docker + Kubernetes stack, this is the mental model you’ve been missing. No hand-waving.</p><h3>First, Kill the Most Common Misconception</h3><p>“Kubernetes runs Docker containers.”</p><p>Partially true. Historically, yes. But Kubernetes does not talk to Docker directly anymore. Since Kubernetes 1.24, dockershim was removed. What Kubernetes actually does is talk to a Container Runtime via the CRI (Container Runtime Interface). The most common runtimes in production today:</p><p>Runtime Who uses it containerd Most cloud providers (EKS, GKE, AKS), bare-metal CRI-O OpenShift, Red Hat workloads Docker Engine (via cri-dockerd) Legacy setups, some fintech bare-metal shops</p><p>So when someone says “Kubernetes runs Docker,” what they mean is: Kubernetes runs OCI-compliant container images, which Docker also happens to produce. The image format is the shared contract, not Docker the tool.</p><blockquote><strong><em>Red pill #1:</em></strong><em> In most modern production clusters, Docker isn’t even installed on the nodes. containerd pulls and runs the images. Docker was just used to build the image.</em></blockquote><h3>The Image Journey: From docker build to Running Pod</h3><p>Here’s the full journey an image takes in a real fintech production environment:</p><pre>Developer Machine          Private Registry           Kubernetes Node<br>─────────────────          ────────────────           ───────────────<br>docker build .      ──▶    docker push          ──▶   kubelet<br>docker tag          ──▶    harbor / ECR / ACR   ──▶   containerd<br>                           (image stored here)        pulls image<br>                                                      runs container</pre><p>Docker’s job ends at the push. After that, Kubernetes takes over.</p><h3>Image Tagging: The Part That Always Confuses People</h3><p>An image tag is not just a name. It’s a fully qualified address that tells the container runtime where to go, what repository to look in, and which version to fetch.</p><h3>The Full Anatomy of an Image Reference</h3><pre>registry/repository/image:tag<br>   │          │        │    │<br>   │          │        │    └── Version or identifier (latest, v1.2.3, git-sha)<br>   │          │        └─────── Image name (payment-service, auth-api)<br>   │          └──────────────── Namespace or project (team, org, env)<br>   └─────────────────────────── Where to fetch from (hostname:port)</pre><h3>Real Examples Across Environments</h3><p><strong>Local development (your laptop):</strong></p><pre>docker build -t payment-service:dev .<br># Stored locally. No registry involved yet.</pre><p><strong>Pushing to localhost registry (Kind cluster, local Harbor):</strong></p><pre>docker tag payment-service:dev localhost:5000/payment-service:dev<br>docker push localhost:5000/payment-service:dev</pre><p><strong>Pushing to a private Harbor registry (typical fintech setup):</strong></p><pre>docker tag payment-service:dev harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2<br>docker push harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2</pre><p><strong>Pushing to AWS ECR (cloud-native fintech):</strong></p><pre>docker tag payment-service:dev 123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-service:v1.4.2<br>docker push 123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-service:v1.4.2</pre><p>The tag is not decoration. It’s a routing address. Get it wrong and the kubelet can’t find the image. Leave it as latest and you lose reproducibility — and at some point you will have an incident because of it.</p><blockquote><strong><em>Red pill #2:</em></strong><em> </em><em>latest is not a &quot;latest version&quot; guarantee. It&#39;s just a tag like any other. If nobody pushes to it, it sits stale. Production clusters in serious companies pin to semantic versions or git SHAs, never </em><em>latest.</em></blockquote><h3>How Kubernetes Interprets the Image Field in a YAML</h3><p>When you write a Deployment manifest, the image: field is the address the kubelet hands to the container runtime.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: payment-service<br>  namespace: fintech-prod<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: payment-service<br>  template:<br>    spec:<br>      containers:<br>        - name: payment-service<br>          image: harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2<br>          imagePullPolicy: IfNotPresent</pre><h3>Step-by-Step: What Happens After kubectl apply</h3><pre>1. kubectl apply -f deployment.yaml<br>        │<br>        ▼<br>2. kube-apiserver validates and stores the spec in etcd<br>        │<br>        ▼<br>3. kube-scheduler assigns the pod to a node<br>        │<br>        ▼<br>4. kubelet on that node sees a new pod spec<br>        │<br>        ▼<br>5. kubelet reads: image: harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2<br>        │<br>        ▼<br>6. kubelet calls containerd via CRI gRPC socket<br>   /run/containerd/containerd.sock<br>        │<br>        ▼<br>7. containerd resolves the registry hostname via DNS<br>   harbor.internal.dtbbank.com → 10.0.1.55 (internal IP)<br>        │<br>        ▼<br>8. containerd authenticates (imagePullSecret or node-level credential)<br>        │<br>        ▼<br>9. containerd pulls image layers (only missing ones, thanks to layer caching)<br>        │<br>        ▼<br>10. containerd unpacks layers into overlayfs snapshots<br>        │<br>        ▼<br>11. kubelet starts the container using the unpacked filesystem</pre><p>That’s the real pipeline. Kubernetes doesn’t “run Docker.” It hands an image reference to a CRI-compliant runtime, which handles everything from DNS resolution to filesystem layer unpacking.</p><h3>imagePullPolicy: The Setting That Causes Production Bugs</h3><p>This one line in your YAML has more production impact than most engineers realize.</p><pre>imagePullPolicy: Always       # Always re-pull from registry on pod start<br>imagePullPolicy: IfNotPresent # Use cached image if it exists on the node<br>imagePullPolicy: Never        # Never pull; fail if image isn&#39;t cached</pre><h3>What Actually Happens in Production</h3><p><strong>Scenario A: You deploy </strong><strong>payment-service:latest with </strong><strong>imagePullPolicy: IfNotPresent</strong></p><ul><li>Pod lands on Node A, image gets pulled. ✅</li><li>You push a bug fix with the same latest tag.</li><li>Pod restarts on Node A — it uses the cached old image because IfNotPresent says &quot;don&#39;t re-pull if it&#39;s there.&quot;</li><li>Your fix is not running. You’re debugging in production wondering why nothing changed.</li></ul><p><strong>Scenario B: You deploy </strong><strong>payment-service:v1.4.2 with </strong><strong>imagePullPolicy: Always</strong></p><ul><li>Every pod restart triggers a full registry pull.</li><li>In a cluster with 50 nodes and rolling deployments, this means 50 parallel pulls.</li><li>If your registry is internal and underpowered (self-hosted Harbor on spinning disks), you get pull rate bottlenecks during deployments.</li></ul><h3>How to Confirm Which Version Is Actually Running</h3><p>This is the command most engineers forget exists:</p><pre># Check the actual image digest running inside the container<br>kubectl get pod payment-service-6d8f9-xkp2j -n fintech-prod \<br>  -o jsonpath=&#39;{.status.containerStatuses[0].imageID}&#39;</pre><pre># Output:<br># harbor.internal.dtbbank.com/fintech/payment-service@sha256:a1b2c3d4...</pre><pre># Compare against what the registry shows for the tag you deployed<br># If the SHA256 doesn&#39;t match → the node is running a cached stale image</pre><p>The digest is the ground truth. The tag is just a pointer. If you deployed v1.4.2 an hour ago and the pod&#39;s imageID digest matches what Harbor reported a week ago, you know the node served cache.</p><p><strong>The fintech production standard:</strong></p><ul><li>Pin to immutable tags (git SHA or semver).</li><li>Use IfNotPresent with immutable tags — safe and fast.</li><li>Reserve Always only for tags that are intentionally mutable (like a staging tag).</li></ul><blockquote><strong><em>Red pill #3:</em></strong><em> Many production incidents aren’t code bugs. They’re engineers deploying </em><em>latest with </em><em>IfNotPresent, then wondering why different nodes in the same cluster are running different versions of the same service.</em></blockquote><h3>Image Pull Secrets: Authentication in Production</h3><p>Public images (like nginx:stable) don&#39;t need credentials. Your private registry does.</p><h3>How Kubernetes Authenticates to a Private Registry</h3><p><strong>Option 1: </strong><strong>imagePullSecrets in the Pod spec</strong></p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: harbor-credentials<br>  namespace: fintech-prod<br>type: kubernetes.io/dockerconfigjson<br>data:<br>  .dockerconfigjson: &lt;base64-encoded-docker-config&gt;</pre><pre>spec:<br>  imagePullSecrets:<br>    - name: harbor-credentials<br>  containers:<br>    - name: payment-service<br>      image: harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2</pre><p>The .dockerconfigjson is a base64-encoded version of what lives in ~/.docker/config.json on your machine after docker login:</p><pre>{<br>  &quot;auths&quot;: {<br>    &quot;harbor.internal.dtbbank.com&quot;: {<br>      &quot;auth&quot;: &quot;dXNlcjpwYXNzd29yZA==&quot;<br>    }<br>  }<br>}</pre><p>That auth field is base64(username:password). Kubernetes hands this to containerd, which uses it as an HTTP Basic Auth header when hitting the registry API.</p><p><strong>Option 2: Attach the secret to the ServiceAccount (cleaner for teams)</strong></p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: fintech-deployer<br>  namespace: fintech-prod<br>imagePullSecrets:<br>  - name: harbor-credentials</pre><p>Now any pod using serviceAccountName: fintech-deployer inherits the pull secret without you repeating it in every deployment YAML.</p><p><strong>Option 3: Node-level credentials (legacy, but still common in bare-metal fintech)</strong></p><p>On each node, configure /etc/containerd/config.toml to include registry credentials. Every pod on that node can pull without secrets in YAML. Less Kubernetes-native, but simpler for tightly controlled bare-metal environments.</p><h3>What Secret Rotation Actually Looks Like as an Incident</h3><p>Here’s a realistic failure sequence:</p><pre># 09:14 — Platform team rotates Harbor service account password (routine)<br># 09:17 — Kubernetes secret still has the old password<br># 09:22 — A deployment rollout triggers. New pods start pulling.</pre><pre>kubectl get pods -n fintech-prod<br># NAME                          READY   STATUS             RESTARTS<br># payment-service-7b9f2-abc12   0/1     ImagePullBackOff   0<br># payment-service-7b9f2-def34   0/1     ImagePullBackOff   0</pre><pre>kubectl describe pod payment-service-7b9f2-abc12 -n fintech-prod<br># Events:<br>#   Warning  Failed  kubelet  Failed to pull image &quot;harbor.internal.dtbbank.com/...&quot;:<br>#            rpc error: code = Unknown desc = failed to pull and unpack image:<br>#            failed to resolve reference: unexpected status code 401 Unauthorized</pre><pre># Fix: update the secret with the new credentials<br>kubectl create secret docker-registry harbor-credentials \<br>  --docker-server=harbor.internal.dtbbank.com \<br>  --docker-username=svc-k8s-puller \<br>  --docker-password=&lt;new-password&gt; \<br>  --namespace=fintech-prod \<br>  --dry-run=client -o yaml | kubectl apply -f -</pre><pre># Pods won&#39;t automatically recover. You need to trigger a rollout.<br>kubectl rollout restart deployment/payment-service -n fintech-prod</pre><p>The 401 Unauthorized in the containerd error tells you it&#39;s auth, not DNS. That distinction saves you 20 minutes of chasing the wrong thing.</p><blockquote><strong><em>Red pill #4:</em></strong><em> If you rotate your registry password and forget to update the Kubernetes secret, every new pod that hasn’t cached the image will fail with </em><em>ImagePullBackOff. Automate secret rotation or use short-lived tokens (IRSA on AWS, Workload Identity on GCP).</em></blockquote><h3>How Tagging Works in a Real CI/CD Pipeline</h3><p>Here’s a realistic Tekton pipeline flow from a fintech GitOps setup:</p><pre>Git Push (main branch)<br>        │<br>        ▼<br>Tekton PipelineRun triggers<br>        │<br>        ▼<br>Task: git-clone<br>  └── clones repo, extracts git SHA<br>      export GIT_SHA=$(git rev-parse --short HEAD)<br>      # e.g., GIT_SHA=a3f9c12<br>        │<br>        ▼<br>Task: docker-build<br>  └── builds image with multiple tags<br>      docker build \<br>        -t harbor.internal.dtbbank.com/fintech/payment-service:${GIT_SHA} \<br>        -t harbor.internal.dtbbank.com/fintech/payment-service:latest \<br>        .<br>        │<br>        ▼<br>Task: docker-push<br>  └── pushes both tags<br>      docker push harbor.internal.dtbbank.com/fintech/payment-service:${GIT_SHA}<br>      docker push harbor.internal.dtbbank.com/fintech/payment-service:latest<br>        │<br>        ▼<br>Task: update-gitops-repo<br>  └── updates Helm values or kustomize overlay<br>      # In values.yaml or deployment patch:<br>      image:<br>        tag: a3f9c12   ← git SHA pinned here<br>        │<br>        ▼<br>Argo CD detects drift in gitops repo<br>        │<br>        ▼<br>Argo CD syncs → kubectl apply<br>        │<br>        ▼<br>Kubernetes pulls:<br>harbor.internal.dtbbank.com/fintech/payment-service:a3f9c12</pre><p>The SHA tag (a3f9c12) is immutable. Once pushed, it never changes. The latest tag is just for human convenience and debugging. The SHA is what controls production.</p><h3>The localhost → DNS Transition: Why It Matters</h3><p>This is the leap most engineers never consciously make.</p><p>When you’re developing locally:</p><pre>docker build -t payment-service:dev .<br># Image lives in your local Docker daemon. No registry.</pre><pre>docker run payment-service:dev<br># Docker finds it locally. Works fine.</pre><p>Now you try to put this in a Kubernetes YAML:</p><pre>image: payment-service:dev</pre><p>It breaks. The kubelet on the Kubernetes node has no idea what payment-service:dev means. There&#39;s no hostname. Kubernetes (via containerd) tries to resolve this against docker.io by default, hits Docker Hub, finds nothing, and you get ImagePullBackOff.</p><p>The fix is always to push to a registry the cluster can reach and use the full reference:</p><p>Environment Registry Full image reference Local (Kind/Minikube) localhost:5000 localhost:5000/payment-service:dev On-prem bare-metal Harbor on internal DNS harbor.company.com/team/payment-service:v1.2 AWS ECR 123456789.dkr.ecr.region.amazonaws.com/payment-service:v1.2 Azure ACR company.azurecr.io/payment-service:v1.2 GCP GAR asia-south1-docker.pkg.dev/project/repo/payment-service:v1.2</p><p>For local Kubernetes development, the common pattern is to load the image directly into the cluster’s runtime:</p><pre># Kind<br>kind load docker-image payment-service:dev --name my-cluster</pre><pre># Minikube<br>minikube image load payment-service:dev</pre><pre># After this, the image exists in containerd&#39;s local store on that node.<br># No registry needed. Use imagePullPolicy: Never in YAML.</pre><blockquote><strong><em>Red pill #5:</em></strong><em> When an image has no registry prefix, Kubernetes defaults to Docker Hub (</em><em>docker.io). In air-gapped fintech environments with no internet access, a generic </em><em>image: redis silently fails. Always use fully qualified image references in production YAMLs.</em></blockquote><h3>How Layers Work: Why Pulls Are Fast (or Slow)</h3><p>Docker images are not monolithic files. They’re stacks of read-only layers, each representing a filesystem change.</p><pre>Image: payment-service:v1.4.2<br>──────────────────────────────<br>Layer 5: COPY ./app /app         (your code — changes every build)<br>Layer 4: RUN pip install -r ...  (dependencies — changes when requirements change)<br>Layer 3: COPY requirements.txt . (requirements file)<br>Layer 2: RUN apt-get install ... (OS packages — rarely changes)<br>Layer 1: FROM python:3.11-slim   (base image — cached forever after first pull)</pre><p>When containerd pulls an image, it checks its local content store for each layer by SHA256 digest. If a layer already exists, it skips it.</p><ul><li>First pull of a new service: all layers download. Slow.</li><li>Second deployment (only app code changed): only Layer 5 downloads. Fast.</li><li>100 microservices using the same base image: base layers downloaded once, shared.</li></ul><h3>Dockerfile Layer Order: The Mistake That Kills Your Cache</h3><p>Most engineers learn Docker basics but never think about layer ordering. Here’s what breaks caching vs. what preserves it:</p><pre># BAD: Copies all files first, then installs dependencies<br># Every code change invalidates the pip install layer<br>FROM python:3.11-slim<br>COPY . /app                  # ← Any file change busts everything below<br>RUN pip install -r /app/requirements.txt<br>CMD [&quot;python&quot;, &quot;/app/main.py&quot;]</pre><pre># GOOD: Copy only requirements first, then the rest of the code<br># pip install only re-runs when requirements.txt actually changes<br>FROM python:3.11-slim<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \<br>    curl &amp;&amp; rm -rf /var/lib/apt/lists/*  # OS packages (changes rarely)<br>COPY requirements.txt .                  # requirements file alone<br>RUN pip install -r requirements.txt      # ← stays cached unless requirements change<br>COPY ./app /app                          # ← your code (changes every build)<br>CMD [&quot;python&quot;, &quot;/app/main.py&quot;]</pre><p>In the bad version, a one-line change in main.py triggers a full pip install on every node during rollout. In a cluster running 40 Python services, that&#39;s the difference between a 30-second deploy and a 10-minute one.</p><blockquote><strong><em>Red pill #6:</em></strong><em> The </em><em>docker pull output showing &quot;Already exists&quot; for most layers is not a quirk. It&#39;s the core efficiency mechanism. In a fintech cluster running 40 services all built on </em><em>python:3.11-slim, that base layer exists on every node once and is never re-downloaded. Randomly changing base images between versions destroys this caching and every deployment becomes a full pull.</em></blockquote><h3>What ImagePullBackOff Actually Means</h3><p>This is the error every K8s engineer fears but doesn’t fully understand.</p><pre>$ kubectl get pods -n fintech-prod<br>NAME                          READY   STATUS             RESTARTS<br>payment-service-6d8f9-xkp2j   0/1     ImagePullBackOff   0</pre><p>The “BackOff” part means Kubernetes is retrying the pull with exponential backoff (10s → 20s → 40s → 80s… up to 5 min). It’s not stuck. It’s waiting between retries.</p><h3>Root Causes (In Order of Frequency in Production)</h3><ol><li>Wrong image reference: typo in the name, wrong tag, doesn’t exist in registry.</li><li>Registry unreachable: DNS failure, firewall rule, registry down, network policy blocking egress.</li><li>Authentication failure: imagePullSecret missing, expired, or wrong namespace.</li><li>Image doesn’t exist: CI/CD pipeline failed before push, so the tag was never pushed.</li><li>Rate limiting: Docker Hub has pull limits for unauthenticated/free-tier clients. Bare-metal clusters hitting docker.io directly get throttled.</li></ol><h3>A Real Diagnosis Workflow</h3><p>Don’t guess. Run this sequence every time:</p><pre># Step 1: Look at the pod events — the error message is here<br>kubectl describe pod payment-service-6d8f9-xkp2j -n fintech-prod<br># Events section at the bottom will show:<br># Failed to pull image &quot;harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2&quot;:<br># rpc error: code = Unknown desc = failed to pull and unpack image:<br># ... 401 Unauthorized       ← auth issue<br># ... dial tcp: i/o timeout  ← registry unreachable<br># ... not found              ← tag doesn&#39;t exist</pre><pre># Step 2: Verify the tag actually exists in the registry<br># From the node or via harbor UI:<br>curl -u user:pass \<br>  <a href="https://harbor.internal.dtbbank.com/v2/fintech/payment-service/tags/list">https://harbor.internal.dtbbank.com/v2/fintech/payment-service/tags/list</a></pre><pre># Step 3: Verify DNS resolves from inside a pod on that node<br>kubectl run dns-debug --image=busybox --rm -it -- \<br>  nslookup harbor.internal.dtbbank.com<br># If this fails, it&#39;s a network policy or CoreDNS issue, not an auth issue</pre><pre># Step 4: Verify the pull secret exists and is in the right namespace<br>kubectl get secret harbor-credentials -n fintech-prod -o yaml<br># Check: is it type kubernetes.io/dockerconfigjson?<br># Check: is the .dockerconfigjson value current?</pre><pre># Step 5: Test the credentials manually (on the node)<br>crictl pull \<br>  --creds &quot;username:password&quot; \<br>  harbor.internal.dtbbank.com/fintech/payment-service:v1.4.2<br># If this works but the pod still fails → the Kubernetes secret has wrong creds</pre><p>Each step narrows the problem to one layer. Most engineers go straight to googling after Step 1. The remaining steps cut diagnosis time from 40 minutes to 5.</p><h3>The Harbor Setup Most Fintech Companies Run</h3><p>For air-gapped or compliance-heavy environments, the typical setup:</p><pre>Internet<br>    │<br>    │  (restricted, compliance-controlled)<br>    ▼<br>DMZ Proxy / Artifact Proxy Cache<br>    │  (Harbor proxy cache project — pulls from Docker Hub,<br>    │   caches internally, serves to internal cluster)<br>    ▼<br>Internal Harbor Registry<br>harbor.internal.dtbbank.com<br>    │<br>    ├── Project: fintech/          ← microservices built in-house<br>    ├── Project: base-images/      ← approved base images (Python, Node, etc.)<br>    ├── Project: thirdparty/       ← vetted third-party images (Redis, Kafka)<br>    └── Project: scanning/         ← Trivy vulnerability scan results gated here<br>    │<br>    ▼<br>Kubernetes Nodes (containerd)<br>    └── All pulls go to Harbor. Zero direct internet access.</pre><p>Why this matters for fintech:</p><ul><li><strong>Compliance:</strong> Every image in production is scanned and logged. Regulators can ask for an audit of what software ran on what date.</li><li><strong>Reproducibility:</strong> The registry is the source of truth. If Harbor has the image, it exists. If it doesn’t, it won’t run.</li><li><strong>Air-gap:</strong> No surprise behavior from external registry changes. A base image won’t silently change under you.</li></ul><blockquote><strong><em>Red pill #7:</em></strong><em> Most public cloud “managed Kubernetes” tutorials assume open internet access. Most production fintech clusters don’t have it. Understanding how your registry sits in your network topology, and how the kubelet/containerd reaches it, is what separates an ops engineer from a tutorial engineer.</em></blockquote><h3>Putting It All Together: The Mental Model</h3><pre>[Developer]<br>    docker build -t harbor.company.com/team/app:a3f9c12 .<br>    docker push harbor.company.com/team/app:a3f9c12<br>          │<br>          ▼<br>[Harbor Registry]<br>    Stores image as content-addressable layers<br>    SHA256 digest: sha256:e3b0c44...<br>          │<br>          ▼<br>[Tekton / CI updates GitOps repo]<br>    deployment.yaml → image: harbor.company.com/team/app:a3f9c12<br>          │<br>          ▼<br>[Argo CD detects diff, applies to cluster]<br>          │<br>          ▼<br>[kube-apiserver] → stores Pod spec in etcd<br>          │<br>          ▼<br>[kube-scheduler] → assigns pod to Node B<br>          │<br>          ▼<br>[kubelet on Node B]<br>    → reads image field<br>    → calls containerd via /run/containerd/containerd.sock<br>          │<br>          ▼<br>[containerd]<br>    → resolves harbor.company.com via internal DNS<br>    → authenticates with imagePullSecret<br>    → checks local content store for each layer SHA256<br>    → pulls only missing layers over HTTPS<br>    → unpacks into overlayfs snapshots<br>          │<br>          ▼<br>[Container starts]<br>    Running on Node B. Visible in kubectl get pods.</pre><p>No magic anywhere. Docker builds and pushes. The registry stores. Kubernetes schedules. containerd pulls. The pod runs. Just well-defined interfaces and protocols at every step.</p><h3>TL;DR</h3><p>Common belief Reality “K8s runs Docker” K8s uses a CRI runtime (usually containerd). Docker is just a build tool. “latest means latest&quot; latest is just a tag. It&#39;s only as fresh as the last push to it. &quot;Image names are just names&quot; They&#39;re registry URLs. Get the syntax wrong and nothing pulls. &quot;ImagePullBackOff means broken cluster&quot; Almost always: wrong tag, missing auth, or unreachable registry. &quot;Kubernetes pulls from Docker&quot; Kubernetes pulls from whatever registry the image reference points to. &quot;Layer caching is a build optimization&quot; It&#39;s also a pull optimization. Same layers across images = one download per node, ever. &quot;Bad layer order is just a style issue&quot; It breaks Docker cache on every build and turns a 30-second deploy into a 10-minute one.</p><h3>What to Read Next</h3><ul><li><strong>OCI Image Spec:</strong> the standard both Docker and containerd implement</li><li><strong>containerd documentation:</strong> specifically how it handles snapshots and content store</li><li><strong>Harbor documentation:</strong> proxy cache, Trivy scanning, replication policies</li><li><strong>Kubernetes KEP-2221:</strong> the dockershim removal that changed everything</li></ul><p>The engineers who understand these layers are the ones who fix ImagePullBackOff in 10 minutes while everyone else is still googling. The five-step diagnosis workflow above is the difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8151ad0c9d8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>