<?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 Amir Hossein Najafi Zadeh on Medium]]></title>
        <description><![CDATA[Stories by Amir Hossein Najafi Zadeh on Medium]]></description>
        <link>https://medium.com/@amirhossein-najafizadeh?source=rss-d0576542d783------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cJIzNalo0gGTBHwDucDbTA.jpeg</url>
            <title>Stories by Amir Hossein Najafi Zadeh on Medium</title>
            <link>https://medium.com/@amirhossein-najafizadeh?source=rss-d0576542d783------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:51:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amirhossein-najafizadeh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your Prompt Doesn’t Fit in GPU Memory. Now What?]]></title>
            <link>https://itnext.io/your-prompt-doesnt-fit-in-gpu-memory-now-what-483174583034?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/483174583034</guid>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[llm-inference]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 23:22:38 GMT</pubDate>
            <atom:updated>2026-12-01T00:43:55.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rMfcBCxwfXn0XQ52MBDYw.png" /></figure><p><em>A quick tour of what vLLM does when KV-cache space runs out in GPU memory, and why it matters for agentic workloads.</em></p><p>Ever wondered what happens when the KV-cache of your prompt doesn’t fit in GPU memory?</p><p>Most of us quietly assume it always fits. Spoiler: it doesn’t always. Let’s walk through what actually happens, using vLLM as our example serving engine.</p><h3>KV-cache in 60 seconds</h3><p>New to KV-cache? Here’s the quick version.</p><p>An LLM writes its answer one <strong>token</strong> at a time (a token is roughly three-quarters of a word). To pick each next token, the model looks back at every token that came before it.</p><p>For every token, each layer of the model computes two small vectors: a <strong>key</strong> (K) and a <strong>value</strong> (V). Think of them as the model’s notes about that token. Recomputing all those notes at every step would be painfully slow, so the serving engine computes them once and keeps them. That pile of saved notes is the <strong>KV-cache</strong>.</p><p>Two things matter for this story:</p><ul><li><strong>It grows with every token.</strong> For Qwen3–235B-A22B, each token adds about 0.19 MB (94 layers × 4 KV heads × 128 numbers × K and V × 2 bytes). A 100K-token prompt needs roughly 19 GB.</li><li><strong>It has to live in GPU memory</strong> while the model works on your request, because the model reads it right there.</li></ul><p>vLLM doesn’t store the cache as one big chunk. It splits it into fixed-size <strong>blocks</strong> (16 tokens each by default), a lot like memory pages in an operating system. Blocks get handed to a request as it grows and returned when it finishes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Hn0M9CKpR8UfZB2AtpKww.png" /></figure><h3>GPU memory is smaller than you think</h3><p>Even an NVIDIA H200, with 141 GB of high-bandwidth memory, gets crowded fast. Serve a big model like Qwen3–235B-A22B and the model weights plus CUDA’s runtime overhead grab most of it. The room left for KV-cache can shrink to around 16 GB.</p><p>Now, what if your prompt needs 20 GB of KV-cache? That’s not a crazy number for today’s agentic workloads, where long contexts and shared prefixes pile up quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6JItX11hPEbZw8vJKYuCA.png" /></figure><h3>Two safety gates in vLLM</h3><p>vLLM has a setting called max_model_len: the most input plus output tokens one request can use. It must be less than or equal to the model&#39;s context length, and it&#39;s what keeps a single request from blowing past GPU memory. Since KV-cache grows with tokens, capping tokens caps the KV-cache too.</p><p><strong>Gate 1, at startup.</strong> vLLM profiles the GPU to see how much memory is left for KV-cache. Then it checks whether one full max_model_len request would fit. If not, the instance refuses to start and tells you to lower max_model_len or raise gpu_memory_utilization.</p><p><strong>Gate 2, at request time.</strong> If your prompt is longer than max_model_len, the API rejects it right away, before it burns any GPU time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-qZ57eVDnWit8PwGHVzSA.png" /></figure><p>So a single request on an idle GPU is always safe. The trouble starts when the GPU is busy.</p><h3>When the GPU is already full</h3><p>In production, an instance serves a whole batch of requests at once. Together they can fill every KV-cache block. Then your request needs room. What now? Two scenarios:</p><p><strong>Scenario A: your request is already running.</strong> It needs a new block for its next tokens. vLLM first grabs a free block. Some “free” blocks still hold KV-cache from finished requests, kept around in case a new prompt starts with the same text (this is called prefix caching). No active request is using them (their reference count is zero), so they can be overwritten. If there are none, it <strong>preempts</strong> another running request (the lowest priority, or the newest one). Preempting means pausing a request and taking its blocks. That victim loses its KV-cache, goes back to the waiting queue, and later has to rebuild its whole cache from scratch. Your request keeps going. The cost? Someone else pays for it with wasted compute and extra latency.</p><p><strong>Scenario B: your request is still waiting.</strong> If there aren’t enough free blocks, it just sits in the queue. And because the scheduler serves the queue in order (FIFO), everyone behind you waits too, even small requests that would fit. Picture one shopper with a full cart at the only checkout lane, and a line of people holding a single item each. That’s the famous <strong>head-of-line blocking</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2waDgO4rvVaW6gsDtd0Nw.png" /></figure><h3>Where our research comes in</h3><p>Notice the pattern: when KV-cache doesn’t fit, today’s engines either make you wait or throw work away and recompute it. They don’t stop to weigh their options.</p><p>To add to the complexity, KV-cache can also live outside the GPU (CPU DRAM, local SSDs, or remote storage) and be restored when needed. That gives you two ways to get a missing KV-cache back:</p><ul><li><strong>Restore:</strong> copy the saved cache back from CPU memory or SSD. This costs I/O bandwidth.</li><li><strong>Recompute:</strong> run the model over those tokens again to rebuild it. This costs GPU time.</li></ul><p>So every time space runs out, the scheduler faces a real question: restore or recompute? Our paper helps it decide. The idea is a KV-cache management system that advises the scheduler on block reservation and request ordering, without starving anyone or hurting throughput. One key finding: splitting a restore between the storage path and GPU recompute meets latency targets in 2–10× more configurations than always restoring or always recomputing.</p><p>Want the details? Read (and cite!) the paper:</p><blockquote><em>Amir Zadeh, Vasily Tarasov, Alex Merenstein, Yue Zhu, and Erez Zadok. </em><a href="https://dl.acm.org/doi/abs/10.1145/3837053.3837336"><em>LLM KV-cache: To Restore or To Recompute, That Is the Question</em></a><em>. </em>HotStorage ’26, <em>ACM, 2026.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483174583034" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/your-prompt-doesnt-fit-in-gpu-memory-now-what-483174583034">Your Prompt Doesn’t Fit in GPU Memory. Now What?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Pod Died of “Out of Ephemeral Storage” but the Disk Is Half Empty!!]]></title>
            <link>https://itnext.io/your-pod-died-of-out-of-ephemeral-storage-but-the-disk-is-half-empty-775851ccd08c?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/775851ccd08c</guid>
            <category><![CDATA[ephemeral-storage]]></category>
            <category><![CDATA[noisy-neighbors]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 17:36:47 GMT</pubDate>
            <atom:updated>2026-07-30T17:36:47.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1C_mMT4wVkdd65yF1tX8w.png" /></figure><p>If you run workloads on Kubernetes long enough, you eventually hit this ghost story. A pod gets killed. The event log says:</p><pre>Status:           Failed<br>Reason:           Evicted<br>Message:          The node was low on resource: ephemeral-storage.</pre><p>You SSH to the node, run df -h, and stare at hundreds of gigabytes of free space! Nothing adds up. Worse, the pod that died wasn&#39;t even the one hogging the disk. It was a quiet, well-behaved service that happened to share a node with a greedy neighbor.</p><p>I went down this rabbit hole while deploying large AI workloads on our GPU machines. Suddenly, some of my observability pods started getting killed seemingly out of nowhere.</p><p>This post is what I wish I’d known beforehand: what Kubernetes “ephemeral storage” actually is, why the Kubelet kills pods that look perfectly innocent, why it matters far more than most people realize, and how much of the problem you can already solve with the tools you have today.</p><h3>What “ephemeral storage” actually is</h3><p>Ephemeral storage isn’t a device or a mount. It’s an <em>accounting category</em>. For any pod, the Kubelet adds up three things:</p><ol><li><strong>The container writable layer; </strong>everything your process writes that <em>isn’t</em> on a mounted volume (think /tmp, or a file dropped in the working directory).</li><li><strong>Container logs; </strong>everything written to stdout/stderr, captured to files on the node. This is the most common silent consumer.</li><li><strong>emptyDir volumes; </strong>scratch space that isn&#39;t memory-backed.</li></ol><p>It does <em>not</em> count read-only image layers, PersistentVolumeClaims, or tmpfs-backed emptyDirs (those go against memory).</p><p>The key word is <em>accounting</em>. There is no cgroup for disk space the way there is for memory or CPU. Nothing physically walls off your slice of the node’s disk.</p><h4>So why is the disk only half full?</h4><p>Here’s the objection that trips everyone up: <em>“If my pod died of ephemeral storage, either the disk is actually full, in which case </em><em>df should say so, or pod passed its limit. Which is it?&quot;</em></p><p>Honestly, it’s one of those two. But a half-empty df is consistent with <strong>both</strong>, for different reasons. That&#39;s the part that confuses people.</p><p><strong>Reason 1: you exceeded your own limit.</strong> Your limits.ephemeral-storage (say 1GB) is a <em>logical accounting number</em>, completely decoupled from the physical disk. The Kubelet sums your writable layer + logs + emptyDir and, if that crosses <em>your</em> budget, evicts <em>you. </em>No matter how empty the node is. Here df isn&#39;t lying, it&#39;s simply irrelevant: it reports the whole 500GB filesystem while you were killed for crossing a 1GB line that exists only on paper. The eviction message names your limit, something like <em>&quot;Pod ephemeral local storage usage exceeds the total limit of containers.&quot;</em></p><p><strong>Reason 2: the node itself hit disk pressure.</strong> If the node’s free space drops below the Kubelet’s eviction-hard threshold, the node goes into DiskPressure and starts evicting pods to reclaim space. <em>&quot;But then </em><em>df should show full!&quot;. </em>Not necessarily, and here&#39;s why you can still see plenty of free space:</p><ol><li><strong>The threshold isn’t 100%.</strong> It’s something like nodefs.available&lt;10%. On a big disk that&#39;s still gigabytes free at the exact moment of eviction.</li><li><strong>The check lags, and space gets reclaimed.</strong> The eviction manager scans every ~10 seconds and acts on the state <em>then</em>. By the time you SSH in and run df, it has already deleted the evicted pod&#39;s files and garbage-collected images. So it looks fine <em>now</em>. You&#39;re seeing the aftermath, not the moment.</li><li><strong>You may be looking at the wrong filesystem.</strong> The Kubelet watches nodefs (the filesystem holding /var/lib/kubelet) and imagefs (the container runtime&#39;s store, e.g. /var/lib/containerd). If those sit on a different partition than the path you df&#39;d, the full one isn&#39;t the one you&#39;re staring at.</li><li><strong>It might be inodes, not bytes.</strong> df -h shows block space; the Kubelet also evicts on nodefs.inodesFree. Millions of tiny files can exhaust inodes while blocks look half-empty. Run df -i and check.</li></ol><p><strong>How to tell which one killed you:</strong> look at kubectl get pod &lt;name&gt; -o yaml (status.message) and kubectl describe node &lt;node&gt; for the DiskPressure condition. If the message names <em>your</em> limit and DiskPressure was false, it&#39;s Reason 1 and df was never the constraint. If it says <em>&quot;The node was low on resource: ephemeral-storage,&quot;</em> it&#39;s Reason 2, and run df -i on the right partition (/var/lib/kubelet, the runtime dir) before trusting a half-empty df -h.</p><p>The thread tying both together: <strong>the limit is a rule written on paper, not a wall.</strong> The Kubelet enforces it like an absentee landlord, walking the property every ~10 seconds and evicting whoever’s over the line, with no write-time check. A bursty pod can overshoot and only get caught at the next scan. There’s no per-pod disk-space cgroup the way there is for memory, which is exactly why df inside your container shows the whole node and cheerfully lets you write past your quota.</p><h3>The noisy neighbor: why innocent pods die!?</h3><p>Reason 2 above (node-level DiskPressure) is where the collateral damage happens, because the Kubelet can evict a pod that&#39;s completely within its own budget just to reclaim space. And the ranking it uses to choose victims is genuinely counterintuitive. Under disk pressure it evicts, in order:</p><ol><li>Pods whose usage <strong>exceeds their </strong><strong>requests.ephemeral-storage</strong>, then</li><li>by <strong>Priority</strong>, then</li><li>by how far over their request they are.</li></ol><p>Now watch what that does. A <strong>Best-Effort</strong> pod, one with no resource requests at all, has an ephemeral-storage request of <strong>zero</strong>. So <em>any</em> usage puts it in bucket #1: first to die. Meanwhile a greedy pod that <em>reserved</em> a big ephemeral-storage request and stays under it sits in a later bucket and is protected.</p><p><strong>The pod that reserved space survives. The modest pod that didn’t reserve gets executed for the neighbor’s crime.</strong></p><h4>Reproduce it in ten minutes</h4><p>You don’t have to take my word for it. Here’s the essence of a lab that makes it happen on a throwaway cluster (minikube with a VM driver, or kind with a small loopback-backed node disk so you never threaten your host disk).</p><p>Give the Kubelet a small disk and an easy-to-hit threshold:</p><pre>minikube start --driver=qemu --disk-size=10g \<br>  --extra-config=kubelet.eviction-hard=&quot;nodefs.available&lt;3Gi&quot; \<br>  --extra-config=kubelet.eviction-minimum-reclaim=&quot;nodefs.available=500Mi&quot;</pre><p>Deploy three innocent Best-Effort pods that each write ~1GB of normal working data and then idle, <strong>no resource requests</strong> (that’s what makes them Best-Effort):</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: innocent-victim<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      role: victim<br>  template:<br>    metadata:<br>      labels:<br>        role: victim<br>    spec:<br>      terminationGracePeriodSeconds: 0<br>      containers:<br>        - name: app<br>          image: busybox:1.36<br>          command: [&quot;/bin/sh&quot;, &quot;-c&quot;]<br>          args:<br>            - |<br>              # We each write ~1Gi of ordinary working data to our own scratch<br>              # dir, then sit idle. This is normal, well-behaved usage -- but we<br>              # set NO resource requests (see below), so the kubelet treats every<br>              # byte as &quot;over budget&quot;.<br>              echo &quot;[victim] writing ~1Gi of normal working data&quot;;<br>              dd if=/dev/zero of=/scratch/data bs=1M count=1024 2&gt;/dev/null || true;<br>              echo &quot;[victim] done; idling&quot;;<br>              while true; do sleep 30; done<br>          volumeMounts:<br>            - name: scratch<br>              mountPath: /scratch<br>          # NO resources block -&gt; QoS class &quot;BestEffort&quot; -&gt; ephemeral-storage<br>          # request is effectively 0. Under node disk pressure the kubelet<br>          # evicts pods that exceed their request FIRST, so these BestEffort<br>          # pods are killed before the noisy neighbor -- even though the neighbor<br>          # is what pushed the node over the edge. Because we hold real space,<br>          # evicting us actually reclaims disk and relieves the pressure, which<br>          # is why the (reserved) noisy neighbor survives.<br>      volumes:<br>        - name: scratch<br>          emptyDir: {}</pre><p>Then unleash the noisy neighbor: it writes ~1.5Gi but <strong>reserves 4Gi</strong>, so its own usage stays under its request:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: noisy-neighbor<br>  labels:<br>    role: noisy<br>spec:<br>  restartPolicy: Never<br>  terminationGracePeriodSeconds: 0<br>  containers:<br>    - name: filler<br>      image: busybox:1.36<br>      command: [&quot;/bin/sh&quot;, &quot;-c&quot;]<br>      args:<br>        - |<br>          echo &quot;[noisy] filling ephemeral storage (emptyDir on the node disk)&quot;;<br>          # Write ~1.5Gi, then hold. Combined with the victims&#39; usage this tips<br>          # the NODE past its DiskPressure threshold. But our own usage (~1.5Gi)<br>          # stays UNDER our 4Gi reservation below, so the kubelet ranks us as<br>          # &quot;within budget&quot; and evicts us LAST -- after the un-reserved victims.<br>          for i in $(seq 1 6); do<br>            dd if=/dev/zero of=/scratch/blob_$i bs=1M count=256 2&gt;/dev/null || true;<br>            echo &quot;[noisy] written $((i * 256)) MiB&quot;;<br>            sleep 1;<br>          done<br>          echo &quot;[noisy] done filling, holding forever&quot;;<br>          sleep 1000000<br>      resources:<br>        requests:<br>          # We DELIBERATELY reserve a large ephemeral-storage request. Our real<br>          # usage (~1.5Gi) is well under it, so the eviction manager protects us<br>          # while the BestEffort victims get culled. This is the punchline:<br>          # reserving space is what saves you from node-level eviction.<br>          ephemeral-storage: &quot;4Gi&quot;<br>          cpu: &quot;50m&quot;<br>          memory: &quot;32Mi&quot;<br>        # NOTE: no ephemeral-storage LIMIT on purpose -&gt; nothing physically<br>        # stops us from pushing the shared node disk toward pressure.<br>      volumeMounts:<br>        - name: scratch<br>          mountPath: /scratch<br>  volumes:<br>    - name: scratch<br>      emptyDir: {}</pre><p>Watch:</p><pre>$ kubectl get pods -o wide -w<br>NAMESPACE     NAME                               READY   STATUS    RESTARTS   AGE<br>default       innocent-victim-7447dfc485-cs56g   1/1     Running   0          2m3s<br>default       innocent-victim-7447dfc485-h87s5   0/1     Pending   0          72s<br>default       innocent-victim-7447dfc485-qq5z2   0/1     Error     0          2m3s<br>default       innocent-victim-7447dfc485-zwv84   1/1     Running   0          2m3s<br>default       noisy-neighbor                     1/1     Running   0          81s</pre><p>Describe:</p><pre>Name:             innocent-victim-7447dfc485-qq5z2<br>Namespace:        default<br>Priority:         0<br>Service Account:  default<br>Node:             minikube/10.0.2.15<br>Start Time:       Wed, 29 Jul 2026 13:08:52 -0700<br>Labels:           pod-template-hash=7447dfc485<br>                  role=victim<br>Annotations:      &lt;none&gt;<br>Status:           Failed<br>Reason:           Evicted<br>Message:          The node was low on resource: ephemeral-storage. Threshold quantity: 3Gi, available: 3053684Ki. Container app was using 4Ki, request is 0, has larger consumption of ephemeral-storage. </pre><p>Within a minute or so the node flips to DiskPressure=True, and the <strong>Best-Effort victims get Evicted first</strong> while the noisy neighbor keeps running. One subtlety that matters for correctness: the victims must hold <em>real</em> space, because evicting empty pods reclaims nothing and the Kubelet would just move on to the next pod. Because our victims each hold ~1GB, evicting a couple of them actually clears the pressure, and the reserver walks away untouched.</p><h3>Why this is worth caring about?</h3><p>For a stateless web app, an eviction is a blip. The reason this matters now is <em>what</em> increasingly runs on Kubernetes.</p><p>Expensive, long-running jobs, AI training, large data-processing, depend on ephemeral scratch space <em>by design</em>. E.g., Spark spills shuffle data to spark.local.dir, which Kubernetes backs with an emptyDir. ML pipelines download datasets, cache them, and stage checkpoints on fast local disk precisely because it&#39;s faster and simpler than a network volume. These are the workloads where a mid-run eviction hurts most.</p><p>The scale of “hurts most” is well documented. Meta’s Llama 3 run on 16,384 H100s hit a failure roughly <strong>every three hours</strong>, and the wasted compute from interruptions has been estimated in the millions of dollars. Academic cluster traces (Microsoft’s Philly) found <strong>over a third of GPU time</strong> went to jobs that ended in failure or were killed. Ephemeral eviction is only one slice of that failure budget, but it’s a <em>preventable</em>, non-hardware slice, and at those stakes preventable slices are worth eliminating.</p><h3>How much can you fix <em>today</em>?</h3><p>You can contain the noisy-neighbor scenario right now by combining existing tools. Two ways:</p><p><strong>The cheap, config-only way.</strong> A per-pod limits.ephemeral-storage is charged against all three consumers <em>in aggregate</em> (writable layer + logs + emptyDir). So:</p><ul><li>give your important pods requests.ephemeral-storage, they get ranked &quot;within budget&quot; and are protected from node-level eviction;</li><li>give risky pods a limit, they get evicted for exceeding <em>their own</em> budget before they can fill the node;</li><li>enforce it cluster-wide with <strong>Kyverno</strong> or <strong>OPA Gatekeeper</strong> so nobody ships a pod without them.</li></ul><p><strong>The hard-wall way.</strong> Cap each consumer physically: <strong>log rotation</strong> (containerLogMaxSize, Fluent Bit) for logs; a capacity-enforcing CSI driver like <strong>TopoLVM</strong> via <em>generic ephemeral volumes</em> for scratch (note: emptyDir.sizeLimit is <em>not</em> a hard wall, it&#39;s still eviction-based); and, for the writable layer, project quotas or the newer containerd <strong>EROFS snapshotter</strong>. Layer observability on top (k8s-ephemeral-storage-metrics plus Prometheus alerts at ~80%).</p><p>Both genuinely work. So if you’re hitting this problem, the first move isn’t to rebuild anything, it’s to <strong>set requests and limits, enforce them with policy, and turn on log rotation.</strong> That alone eliminates most of the pain.</p><h3>The gap that’s still open!</h3><p>So is there anything left to solve? I think so, but it’s narrower than the noisy-neighbor demo suggests.</p><p>Every existing approach does one of three things: it <strong>observes</strong> (metrics, alerts), it <strong>hard-caps by failing writes</strong> (ENOSPC at the quota), or it <strong>reacts to pressure by evicting</strong> (Node Problem Detector feeding the Descheduler, which <em>accelerates</em> the thing you&#39;re trying to avoid). What nobody does is treat an approaching ephemeral limit as a <strong>recoverable condition</strong>.<strong> </strong>Reclaiming a pod&#39;s <em>own</em> reclaimable space in place (rotating its logs, pruning stale scratch, signaling the app to flush) so the workload <em>keeps running</em> instead of dying.</p><p>That distinction matters most for exactly the expensive jobs from earlier: the hard-cap and limit approaches protect the <em>innocent</em> neighbors by killing or failing the <em>culprit</em>,<em> </em>but if that culprit is your six-figure training run, it still dies, just via a different error. Graceful, in-place recovery, plus a single per-pod view across all three consumers so an operator isn’t stitching three subsystems together, is the piece the ecosystem hasn’t assembled into one thing yet.</p><h3>TL;DR</h3><ul><li><strong>Ephemeral storage is accounting, not a wall.</strong> df shows the whole node disk because there&#39;s no per-pod space cgroup.</li><li><strong>Enforcement is a lagging ~10s scan</strong>, so pods can briefly overshoot before eviction.</li><li><strong>Under node disk pressure, Best-Effort pods die first</strong>. Even innocent ones, while pods that <em>reserved</em> ephemeral storage are protected.</li><li><strong>It matters most for expensive, scratch-hungry jobs</strong> (AI training, Spark) and has a real <strong>security angle</strong> (CVE-2020–8557, CVE-2025–0426).</li><li><strong>You can fix most of it today:</strong> set requests/limits.ephemeral-storage, enforce with Kyverno/OPA, and turn on log rotation. Reach for TopoLVM/quotas if you need hard walls.</li><li><strong>The open frontier</strong> is <em>graceful, in-place recovery</em> that keeps a pod alive as it approaches its budget rather than observing, failing writes, or evicting.</li></ul><p>If you’ve been bitten by a mystery eviction, start by setting requests and limits. And the next time df tells you the disk is half empty while your pod lies dead beside it, now you know who really did it.</p><h3>References</h3><ul><li>Kubernetes docs — Local ephemeral storage: <a href="https://kubernetes.io/docs/concepts/storage/ephemeral-storage/">https://kubernetes.io/docs/concepts/storage/ephemeral-storage/</a></li><li>Kubernetes 1.25: Local Storage Capacity Isolation reaches GA: <a href="https://kubernetes.io/blog/2022/09/19/local-storage-capacity-isolation-ga/">https://kubernetes.io/blog/2022/09/19/local-storage-capacity-isolation-ga/</a></li><li>KEP-1029, Ephemeral Storage Quotas: <a href="https://github.com/kubernetes/enhancements/blob/master/keps/sig-node/1029-ephemeral-storage-quotas/README.md">https://github.com/kubernetes/enhancements/blob/master/keps/sig-node/1029-ephemeral-storage-quotas/README.md</a></li><li>The Llama 3 Herd of Models (failure cadence at scale): <a href="https://arxiv.org/pdf/2407.21783">https://arxiv.org/pdf/2407.21783</a></li><li>Analysis of Large-Scale Multi-Tenant GPU Clusters (Philly, USENIX ATC’19): <a href="https://www.usenix.org/system/files/atc19-jeon.pdf">https://www.usenix.org/system/files/atc19-jeon.pdf</a></li><li>CVE-2020–8557 (node disk DoS via /etc/hosts): <a href="https://github.com/kubernetes/kubernetes/issues/93032">https://github.com/kubernetes/kubernetes/issues/93032</a></li><li>CVE-2025–0426 (kubelet checkpoint endpoint disk DoS): <a href="https://www.sentinelone.com/vulnerability-database/cve-2025-0426/">https://www.sentinelone.com/vulnerability-database/cve-2025-0426/</a></li><li>containerd EROFS snapshotter (writable-layer cap): <a href="https://github.com/containerd/containerd/blob/main/docs/snapshotters/erofs.md">https://github.com/containerd/containerd/blob/main/docs/snapshotters/erofs.md</a></li><li>k8s-ephemeral-storage-metrics: <a href="https://last9.io/blog/monitor-ephemeral-storage-metrics-in-kubernetes/">https://last9.io/blog/monitor-ephemeral-storage-metrics-in-kubernetes/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775851ccd08c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/your-pod-died-of-out-of-ephemeral-storage-but-the-disk-is-half-empty-775851ccd08c">Your Pod Died of “Out of Ephemeral Storage” but the Disk Is Half Empty!!</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Did My Test Suite Just Kill the GitHub Actions Runner!?]]></title>
            <link>https://itnext.io/did-my-test-suite-just-kill-the-github-actions-runner-42c2a0a11f71?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c2a0a11f71</guid>
            <category><![CDATA[adversarial-testing]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[file-descriptor]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 04:13:51 GMT</pubDate>
            <atom:updated>2026-07-13T07:03:49.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yF1wCSD0AiWb5DGMmx359w.png" /></figure><blockquote>A debugging story about file descriptors, adversarial tests, and the three different ways a suite that works on my machine can still detonate in CI.</blockquote><h3>Introduction</h3><p>I had a test suite that passed perfectly when I ran it by hand on the CI machine. The exact same commands, on the exact same box, under GitHub Actions, failed and not with a normal test failure. The <strong>runner itself</strong> crashed, and left this in the log:</p><pre>[Worker] Cancellation/Shutdown message received.<br>[Worker] System.IO.InvalidDataException: Found invalid data while decoding.<br>at GitHub.Runner.Common.StreamString.ReadStringAsync(CancellationToken)<br>at GitHub.Runner.Common.ProcessChannel.ReceiveAsync(CancellationToken)<br>at GitHub.Runner.Worker.Worker.RunAsync(String pipeIn, String pipeOut)</pre><p>That is not a message about my code. That’s GitHub’s own runner process dying while trying to read from a pipe. My tests had reached out and corrupted the runner’s internal machinery. This post is the whole trail, because it turned out to be three stacked failures, each wearing the same disguise: <strong>green by hand, red in CI</strong>. The last one is the interesting one, but the first two are worth knowing because they waste hours if you don’t recognize them.</p><h4>The setup</h4><p>I was moving a sandbox runtime’s test suite into CI, to run <strong>natively on a self-hosted Linux runner</strong> (no Docker, the runner is already Linux, so why pay for a container?). Two kinds of tests:</p><ul><li>an <strong>e2e</strong> suite that checks the sandbox enforces its policy, and</li><li>a <strong>security</strong> suite that is deliberately <strong>adversarial</strong>.</li></ul><p>That second suite is the one that matters here, so it’s worth explaining how it works.</p><p>The idea is simple: <em>plant a secret, a canary, inside the sandbox, then play the attacker and try to smuggle that canary out through every escape route you can think of. If the canary never reaches the outside, the sandbox held. Each escape route is one self-contained test.</em></p><p>The suite runs a whole battery of them, one after another: write the secret to a file on a shared path, send it over the network to a listener, hand it off through a socket, stuff it into the system clipboard, sneak it through kernel pseudo-files, and so on.</p><p>To catch a leak, the suite stands up <strong>observers outside the sandbox</strong>,<strong> </strong>little listener and watcher processes, and after each attempt checks whether the canary showed up anywhere it shouldn’t have.</p><p>The important thing for this story: these tests are, by design, doing genuinely hostile things, opening arbitrary file descriptors, forking helper tools, sending signals, binding sockets. That’s fine inside a throwaway container, where the blast radius is the container. Run the same suite <strong>bare on a CI runner</strong>, and “the attacker” is now rummaging around in the runner’s own process which, as I was about to learn, it is not supposed to survive.</p><h4>Red herring #1: “The Build That Was Never Rebuilt”</h4><p>The first “fixed bug still failing” was the cheapest and the most embarrassing. The engine under test is fetched and built on a self-hosted Linux runner. The fetch script had a fast path: <em>”already present? skip.” </em>So after I pushed a fix, CI dutifully rebuilt the old engine. My fix wasn’t in the binary the tests ran against.</p><p>Lesson, engraved: <strong>a cache that keys on “does it exist” instead of “is it current” is a correctness bug, not an optimization</strong>. The fix was to compare the fetched commit against the branch HEAD and refetch on drift.</p><p>Cost:<em> an hour of staring at a fix that “didn’t work.”</em></p><h4>Red herring #2: “Paths That ONLY Exist In a Container”</h4><p>With the real binary built, the e2e suite went green <strong>12/12 on the runner</strong>.<strong> </strong>The sandbox itself worked natively: user namespaces available, seccomp enforced, the works. The security suite died immediately:</p><pre>mkdir: cannot create directory &#39;/data&#39;: Permission denied<br>mkdir: cannot create directory &#39;/exfil&#39;: Permission denied<br>FATAL: could not reach the loopback listener; aborting</pre><p>The suite hardcoded /data (where it staged the secret) and /exfil (where its observers captured exfil attempts). Those are absolute mount points that exist<em> </em>in the Docker image the suite was born in. On a bare runner running as an unprivileged user, /data isn’t yours to create. The observer setup couldn’t write its capture files, so the listener never came up, and the suite aborted.</p><p>Lesson: <strong>”no Docker” means the container’s filesystem contract is gone too.</strong></p><p>Anything the suite assumed about absolute paths is now your problem. The fix was to root everything under a per-run temp directory.</p><p>Both of these are the boring kind of environment mismatch. The next one is not.</p><h3>The real event: “My Tests Corrupted the Runner’s IPC Channel”</h3><p>With paths fixed, I pushed again. This time the security suite got further. It cleared the first few escape attempts (the file dump, the network send, the socket handoff) and then the runner crashed with the decode error from the top of this post. The job showed `failure`, the step was stuck `in_progress`, and the logs never finalized. It always died in the same place: <strong>the clipboard test</strong>.</p><p>Here’s the clue that cracked it. A colleague ran the identical suite by hand on the same runner;<strong> </strong>flawless. Every test passed. Works interactively. Crashes under Actions. Same machine, same script.</p><p>When you see that, stop looking at your code. <strong>The bug is in the difference between the two execution environments</strong>, and for a shell script that difference is almost always one of three things: environment variables, the controlling terminal, or <strong>inherited file descriptors.</strong></p><h4>What GitHub’s runner is actually doing?</h4><p>The GitHub Actions runner is two processes: a <strong>Listener</strong> and a <strong>Worker</strong>. They talk to each other over a pipe using a length-prefixed string protocol `ProcessChannel`, built on `StreamString`. The reader trusts that framing absolutely. The Worker launches job’s shell as a child. And here’s the landmine: the Worker-Listener pipe is a <strong>file descriptor the Worker holds, </strong>and it is not reliably marked close-on-exec. So the shell running your step, <em>and everything that shell forks</em>, inherits that pipe on some fd greater than 2.</p><p>Now what my clipboard test does? It’s the first attempt in the suite that uses shell <strong>process substitution</strong> and forks external <strong>clipboard tools, </strong>things that quietly allocate and write to file descriptors the script never explicitly opened. Somewhere in that, one of those children wrote bytes into the inherited pipe. The Worker read those bytes, tried to interpret them as a length-prefix, and got:</p><pre>System.IO.InvalidDataException: Found invalid data while decoding.</pre><p>Garbage in the length field. The channel is corrupt. The Worker cannot recover a protocol it no longer trusts, so it shuts down. Job dead.</p><h4>Why it’s invisible by hand?</h4><p>An interactive shell on that runner has file descriptors 0, 1, 2; a terminal. <strong>It does not have the Worker’s pipe fd</strong>, because there’s no Worker in that session. So the adversarial writes hit nothing interesting, and the suite sails through. The bug is <em>structurally invisible</em> to the way every human verifies it. That’s the whole trap: <em>the reproduction you reach for is the one environment that can’t reproduce it.</em></p><h4>The other half: “The Hang”</h4><p>Before I fully understood the decode crash, I hit a related symptom, the step would hang forever even though the script had clearly finished. Same family of bug, different fd.</p><p>A GitHub Actions step doesn’t complete when your script exits. It completes when the step’s <strong>stdout pipe is closed</strong>. Which means every process holding that pipe open must exit. My security suite backgrounds socket and signal observers. Any it forgets to reap keeps the stdout pipe open, and the step waits on them until the job timeout. Interactively, the shell returns to a prompt and you never notice the orphans still breathing in the background.</p><h3>The Fix: isolate the suite from the runner</h3><p>The root cause of both the crash and the hang is the same: <strong>an adversarial child process reaching machinery it should never see</strong>. So the fix is to sever every channel between the suite and the runner before the suite runs.</p><p>E.g., I wrapped each suite in an isolating launcher that does three things:</p><pre>run_one() {<br>  local script=&quot;$1&quot; dir; dir=&quot;$(mktemp -d)&quot;<br>  set -m # give the suite its own process group<br>  (<br>    # 1. Close every inherited fd &gt; 2. This severs the runner&#39;s Worker&lt;-&gt;Listener<br>    # pipe, so nothing the suite forks can corrupt the length-prefixed channel.<br>    for f in /proc/self/fd/*; do<br>      n=${f##*/}<br>      case &quot;$n&quot; in 0|1|2) ;; *) eval &quot;exec $n&gt;&amp;-&quot; 2&gt;/dev/null || true ;; esac<br>    done<br>    <br>    # 2. Hard timeout as a backstop for anything that still wedges.<br>    exec timeout - signal=KILL 300 bash &quot;$script&quot;<br>  ) &amp; local pid=$!<br>  <br>  wait &quot;$pid&quot;; local rc=$?<br>  <br>  # 3. SIGKILL the whole process group: reap leaked observers so they can&#39;t hold<br>  # the CI step&#39;s stdout pipe open and hang the step.<br>  kill -KILL - -&quot;$pid&quot; 2&gt;/dev/null || true<br><br>  set +m<br>  rm -rf &quot;$dir&quot;<br><br>  return &quot;$rc&quot;<br>}</pre><ul><li><strong>Closing fds &gt; 2</strong> is the direct fix for the decode crash. The subshell scrubs its descriptor table and then `exec`s the suite, which re-opens only what it legitimately needs. The runner’s pipe is simply gone from the suite’s world.</li><li><strong>Own process group and </strong>`<strong>kill $pid</strong>` reaps every orphaned observer, so the step’s stdout pipe closes and the step actually completes.</li><li>`<strong>timeout</strong>` is the seatbelt for whatever I didn’t anticipate.</li></ul><p>Next push: <strong>e2e 12/12, security all clear, step green.</strong> Both suites now run natively on the Linux runner as a per-PR gate.</p><h3>Notes</h3><ol><li><strong>“Works interactively, fails in CI” is a fingerprint, not a mystery</strong>. It means the two environments differ, and for shell-based jobs the usual suspects are, in order: inherited <strong>file descriptors</strong>, environment variables, and the absence of a <strong>TTY</strong>. Don’t debug the code, diff the environment<strong>.</strong></li><li><strong>A GitHub Actions step waits on its stdout pipe, not on your script.</strong> Any backgrounded process that outlives your script and holds that pipe will hang the step until the job times out. Reap what you spawn, or run it in a process group you can kill.</li><li><strong>The runner passes its own guts down to your job.</strong> The Worker-Listener IPC pipe can be inherited by step children. Write to it and you get `<em>Found invalid data while decoding</em>` and a dead Worker. If your job spawns anything that touches arbitrary fds, scrub the descriptor table first.</li><li><strong>Adversarial tests need containment, not just isolation-under-test.</strong> A suite whose <em>job</em> is to poke at fds, signals, sockets, and namespaces is a hazard to whatever hosts it. In a container that’s fine. Bare on a shared runner, “the attacker” is now attacking your CI infrastructure. Either sandbox the sandbox, or sever every handle before it runs.</li><li><strong>Caches must key on identity, not existence.</strong> “Already present, skip” quietly serves stale artifacts and makes a fixed bug look unfixed. Compare versions.</li></ol><p>The satisfying part: none of the three failures were in the sandbox logic itself. The sandbox was correct the whole time. Every failure lived in the seam between an adversarial, container-born test suite and the very specific, very opinionated process model of a CI runner. That seam is where “<strong>works on my machine</strong>” goes to die, and it’s a genuinely fun place to debug once you know to look there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c2a0a11f71" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/did-my-test-suite-just-kill-the-github-actions-runner-42c2a0a11f71">Did My Test Suite Just Kill the GitHub Actions Runner!?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IPFS: Manage data without a central server]]></title>
            <link>https://amirhossein-najafizadeh.medium.com/ipfs-manage-data-without-a-central-server-b32334f94a39?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/b32334f94a39</guid>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[ipfs-tutorial]]></category>
            <category><![CDATA[ipfs]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 02:14:15 GMT</pubDate>
            <atom:updated>2025-03-23T02:14:15.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qwb4XRJPS_rL21PVdAhLFw.jpeg" /></figure><p>I first learned about IPFS during a networking course. I explored it further and found it fascinating. However, I struggled to find a clear and comprehensive explanation of how it works. In this story, I will explain IPFS in separate terms.</p><h3>IPFS</h3><p>The <strong>Inter-Planetary File System (IPFS)</strong> is a decentralized system that allows users to store, access, and share files, websites, apps, and data directly with one another.</p><p>Instead of relying on a single large file system (like NFS), IPFS uses a <strong>peer-to-peer protocol</strong> to spread the file system across multiple nodes.</p><h4>Okay, but why peer-to-peer?</h4><p>IPFS uses a peer-to-peer (P2P) architecture to decentralize data storage and sharing, eliminating the need for centralized servers. This approach offers several advantages:</p><ol><li><strong>Decentralization</strong> — By distributing data across multiple nodes, IPFS reduces reliance on any single server, making it more resistant to censorship and single points of failure.</li><li><strong>Efficiency</strong> — P2P allows nodes to directly exchange data, reducing latency and improving overall network efficiency.</li><li><strong>Scalability</strong> — As more nodes join the network, IPFS can handle increased data volumes without the need for centralized infrastructure upgrades.</li></ol><h4>Advantages of Peer-to-Peer in IPFS</h4><ol><li><strong>Censorship Resistance</strong> — Data is harder to censor since it is distributed across many nodes.</li><li><strong>Fault Tolerance</strong> — The network remains operational even if some nodes go offline.</li><li><strong>Improved Performance</strong> — Data can be retrieved from nearby nodes, reducing latency.</li><li><strong>Cost-Effective</strong> — Eliminates the need for expensive centralized infrastructure.</li></ol><h4>Remember BitTorrent?</h4><p>When you hear <em>“peer-to-peer,”</em> you might think of <strong>BitTorrent</strong>, a popular protocol that allows users to share files directly without relying on a central server. It is often used to bypass censorship and ensure content remains available.</p><p>IPFS works in a similar way but introduces several improvements to make file sharing more efficient and reliable.</p><h4>But, how is it different from BitTorrent?</h4><p>IPFS differs from BitTorrent in several key ways:</p><ol><li><strong>Content Addressing</strong> — IPFS uses unique cryptographic hashes to identify files, whereas BitTorrent relies on torrent files or magnet links. This ensures that files in IPFS remain verifiable and unchanged.</li><li><strong>Permanent Storage</strong> — Unlike BitTorrent, where files disappear if no seeders remain, IPFS stores content as long as at least one node keeps it pinned.</li><li><strong>Decentralized Discovery</strong> — IPFS does not rely on trackers like BitTorrent. Instead, it uses a Distributed Hash Table (DHT) to find and retrieve content efficiently.</li><li><strong>Efficient Deduplication</strong> — IPFS splits files into smaller chunks and stores only unique pieces, reducing redundancy and saving storage space.</li><li><strong>Web Integration</strong> — IPFS can serve websites in a decentralized manner, enabling censorship-resistant and distributed web hosting.</li></ol><p>In short, while both use peer-to-peer networks, IPFS is designed for long-term, verifiable, and efficient content distribution beyond just file sharing.</p><h3>What is Content-addressing?</h3><p><strong>Content-addressing</strong> is a way of identifying and retrieving data based on its content rather than its location. Instead of using traditional file paths or URLs, content-addressing assigns a unique identifier, called a <strong>Content Identifier (CID)</strong>, to each piece of content. This CID is generated using a cryptographic hash of the file’s data. If even a small part of the file changes, the CID will be completely different.</p><h4>Why is content-addressing useful?</h4><ul><li>Ensures data integrity (you always get the exact file you requested).</li><li>Prevents duplication (identical files have the same CID).</li><li>Makes data retrieval more efficient and decentralized.</li><li>Improves resistance to censorship (files are not tied to specific locations).</li></ul><h3><strong>What is DHT?</strong></h3><p>A <strong>Distributed Hash Table (DHT)</strong> is a decentralized system for storing and finding data across a network of computers. Instead of relying on a central server, nodes in a DHT work together to keep track of where content is stored.</p><h4>How does DHT work in IPFS?</h4><ul><li>When a file is added to IPFS, its CID is stored in the DHT along with information about which nodes have the file.</li><li>When someone requests the file, IPFS looks up the CID in the DHT to find the nearest available node with that content.</li><li>The file is then retrieved directly from that node.</li></ul><h4><strong>Why is DHT useful?</strong></h4><ul><li>Enables fast and decentralized content discovery.</li><li>Makes the system scalable and efficient, even with millions of nodes.</li><li>Helps locate content even if the original uploader is offline.</li></ul><p>In summary, content-addressing ensures that files are identified by their actual data, while DHT helps locate and retrieve them efficiently in a decentralized way.</p><h3>How does IPFS store data?</h3><p>IPFS stores data in a decentralized manner, using a peer-to-peer network of nodes. Here’s a step-by-step overview of how it works:</p><ol><li><strong>File Chunking</strong> — When you upload a file to IPFS, it is broken down into smaller chunks of data. Each chunk is then cryptographically hashed to create a unique identifier, known as a <strong>Content Identifier (CID)</strong>.</li><li><strong>Content Addressing</strong> — Files are identified by their content rather than their location. If the content changes, its CID changes too, ensuring data integrity and immutability.</li><li><strong>Distributed Storage</strong> — A file is distributed among multiple nodes in the network. However, by default, files are stored in a node’s cache storage unless they are “pinned” for permanent storage.</li><li><strong>File Retrieval</strong> — When you request a file using its CID, the IPFS network locates the nearest node that has the file. The file is then reassembled from its chunks and delivered to you. This process ensures faster access and reduces reliance on any single server.</li></ol><h3>How does IPFS replicate data?</h3><p>IPFS does not automatically replicate data across all nodes in the network. Instead, data replication occurs when a file is requested by another node. Here’s how replication works:</p><ul><li><strong>On-Demand Replication</strong> — Files only propagate through IPFS when they are requested by a node. If a node requests a file, it will store a copy of that file in its cache storage. This process allows the file to be available on more nodes over time as it is requested by different users.</li><li><strong>Pinning for Persistence</strong> — To ensure that a file remains available even when nodes go offline or clear their cache, you can use <strong>pinning services</strong>. Pinning involves storing files persistently on nodes, ensuring they are not removed during garbage collection. This is crucial for maintaining data availability and redundancy.</li><li><strong>IPFS Cluster for Replication</strong> — For more robust data durability, tools like <strong>IPFS Cluster</strong> can be used to orchestrate multiple nodes, ensuring that files are replicated across multiple locations. This approach allows for customizable replication levels (e.g., 2x, 3x) to enhance data resilience.</li></ul><h3>How does IPFS retrieve data?</h3><p>IPFS handles data retrieval from different nodes through a combination of mechanisms that ensure efficient and reliable access to content across the decentralized network. Here’s how it works:</p><p>1. <strong>Content Routing</strong> — When a node requests data, it uses <strong>content routing</strong> to find other nodes that have the requested Content Identifier (CID). This process is facilitated by the <strong>Distributed Hash Table (DHT)</strong> or by querying connected peers via <strong>Bitswap</strong>. The DHT acts as a decentralized directory, mapping CIDs to node addresses. It allows nodes to locate peers that store specific content without needing a central registry.</p><p>2. <strong>Bitswap Protocol </strong>— Bitswap is a peer-to-peer protocol used for both content routing and data transfer. It enables nodes to request and exchange data blocks with their peers. Nodes maintain wantlists of CIDs they are interested in. If a peer receives data matching a wantlist, it can forward it to the requesting node.</p><p>3. <strong>Block Fetching and Verification</strong> — Once a node identifies providers of the requested CID, it fetches the data blocks from these providers. The blocks are then verified by hashing them to ensure they match the expected CID. This verification process allows nodes to trustlessly retrieve data from any node in the network, ensuring data integrity.</p><p>4. <strong>Local Access</strong> — After fetching and verifying all necessary blocks, the node reassembles the data into its original form, making it available for local access.</p><p>5. <strong>Caching for Performance</strong> — Frequently accessed files are cached locally by nodes to optimize performance, reducing bandwidth usage and accelerating delivery for popular content.</p><p>By leveraging these mechanisms, IPFS efficiently retrieves data from different nodes across the network, ensuring high availability and fault tolerance.</p><h3>How does IPFS ensure data availability if all nodes with a copy of the file are down?</h3><p>IPFS does not inherently ensure data availability if all nodes with a copy of the file are down. In such a scenario, the file becomes inaccessible until at least one node with the file comes back online or another node caches the file.</p><h3>IPFS Implementation</h3><p>IPFS has been implemented in multiple programming languages, with several key implementations providing flexibility and accessibility across different development environments. The primary implementations include:</p><ul><li><strong>Go</strong> — The reference implementation, known as <strong>Kubo</strong>, is written in Go. It serves as the standard for IPFS functionality and is the most widely used version.</li><li><strong>JavaScript</strong> — The JavaScript implementation, <strong>js-ipfs</strong>, allows developers to interact with IPFS using Node.js, making it suitable for web-based applications.</li><li><strong>C</strong> — A C implementation exists to provide a lightweight and efficient way to interact with IPFS, particularly useful for resource-constrained environments.</li><li><strong>Python</strong> — Python client libraries are available, enabling developers to integrate IPFS functionality into Python applications easily.</li><li><strong>libp2p</strong> — While not a standalone IPFS implementation, libp2p is a modular networking stack used in IPFS to handle peer-to-peer communication.</li></ul><p>In addition to these main implementations, there are client libraries and experimental versions in other languages, including <strong>Rust, Java, Swift, and Elixir</strong>, expanding IPFS’s usability across various ecosystems. These implementations allow developers to integrate IPFS into a wide range of applications, from decentralized storage solutions to distributed web applications.</p><h3>IPFS Usages</h3><ol><li><strong>Decentralized E-commerce Websites</strong> — IPFS can be used to host e-commerce websites, allowing for decentralized and censorship-resistant online stores. These platforms can integrate cryptocurrencies for payments, enhancing security and privacy. Frameworks like Fleek provide tools for building and hosting e-commerce sites on IPFS, leveraging its decentralized nature for secure transactions and content delivery.</li><li><strong>Decentralized Data Storage for Blockchain Projects</strong> — IPFS is often used in blockchain projects to store data off-chain, reducing costs and improving scalability. This is particularly common for NFT projects, where metadata and media are stored on IPFS and accessed via smart contracts. Many NFT collections use IPFS to store images and metadata, ensuring data integrity and availability.</li><li><strong>Content Delivery Networks (CDNs)</strong> — IPFS can act as a decentralized CDN, distributing content across a network of nodes to improve delivery speed and resilience. By hosting static websites on IPFS, businesses can ensure fast and reliable content delivery without relying on centralized infrastructure.</li><li><strong>Decentralized Document Management</strong> — IPFS can be used for decentralized document signing and management, ensuring version control and security. Documents are stored on IPFS, and signatures are recorded on blockchain platforms. Services like decentralized document signing platforms use IPFS to store documents securely and track changes.</li><li><strong>Distributed Package Management</strong> — IPFS can host software packages in a decentralized manner, allowing for secure and transparent version control. This approach ensures that package updates are verifiable and publicly accessible. By hosting software packages on IPFS, developers can ensure that updates are tracked and verified through unique CIDs, enhancing security and collaboration.</li></ol><h3>References</h3><ul><li><a href="https://ipfs.tech/">https://ipfs.tech/</a></li><li><a href="https://en.wikipedia.org/wiki/InterPlanetary_File_System">https://en.wikipedia.org/wiki/InterPlanetary_File_System</a></li><li><a href="https://www.ipfs.com/">https://www.ipfs.com/</a></li><li><a href="https://github.com/ipfs/ipfs">https://github.com/ipfs/ipfs</a></li><li><a href="https://developers.cloudflare.com/web3/ipfs-gateway/concepts/ipfs/">https://developers.cloudflare.com/web3/ipfs-gateway/concepts/ipfs/</a></li><li><a href="https://github.com/libp2p/go-libp2p">https://github.com/libp2p/go-libp2p</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b32334f94a39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Having your Kubernetes over NFS]]></title>
            <link>https://itnext.io/having-your-kubernetes-over-nfs-0510d5ed9b0b?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/0510d5ed9b0b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-storage]]></category>
            <category><![CDATA[nfs-client-provisioner]]></category>
            <category><![CDATA[nfs-server]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 05:00:07 GMT</pubDate>
            <atom:updated>2025-03-07T04:16:21.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTNRSEzTVny7V4QGK9idCw.jpeg" /></figure><p>In this story, I’ll share how I moved my entire <strong>Kubernetes</strong> cluster — including <strong>Kubelet</strong> data and Persistent Volumes (PVs) — to a 4TB NFS server. This helped boost storage performance and made managing storage much easier.</p><h3>Intro</h3><p>Using an <strong>NFS</strong> server made storage migration and management much easier. My worker nodes (bare metal) had only 45GB of storage, and my control node (a VM) had just 10GB — far too little for running heavy AI/ML workloads. Moving everything to a 4TB NFS server solved this problem.</p><p>NFS is fast, simple, and perfect for local-network environments.</p><p>Setting up your Kubernetes cluster on NFS involves two main steps:</p><ol><li>Configure <strong>Kubelet</strong> to mount its data to the NFS server.</li><li>Move your Persistent Volumes (PVs) to NFS so that all in-cluster data is stored there.</li></ol><p>To do this, you need to install the NFS client on all nodes. If you don’t have an NFS server, you’ll need to set one up first.</p><p>I set up my Kubernetes cluster using <strong>Kubeadm</strong>, with <strong>containerd</strong> as the runtime and <strong>NVIDIA Toolkit</strong> for GPU support. All my nodes run <strong>Ubuntu 22.04</strong>.</p><h4>Install NFS-server</h4><p>First, install the <strong>NFS kernel server</strong> and start its service:</p><pre>$ sudo apt update<br>$ sudo apt install -y nfs-kernel-server<br>$ sudo systemctl enable --now nfs-kernel-server</pre><p>This sets up the NFS server and ensures it starts automatically on boot. You can configure the directories to be exported by adding them to the /etc/exports file.</p><pre>/srv                *(ro,sync,subtree_check)<br>/home               *.hostname.com(rw,sync,no_subtree_check)<br>/node1              *(rw,async,no_subtree_check,no_root_squash)<br>/node2              *(rw,async,no_subtree_check,no_root_squash)<br>/controller         *(rw,async,no_subtree_check,no_root_squash)<br>/workloads/data     *(rw,async,no_subtree_check,no_root_squash)</pre><p>After modifying the file, run the following command to apply the changes:</p><pre>$ sudo exportfs -ra</pre><p>This refreshes the NFS exports and makes the new configurations take effect.</p><blockquote><strong>Note:</strong> You need to enable <strong>no_root_squash</strong> because <strong>Kubelet</strong> runs as root. Without this setting, the NFS server will block root commands to prevent unauthorized access.</blockquote><blockquote><strong>Note:</strong> If you prefer not to enable <strong>no_root_squash</strong> for security reasons, you can mount the NFS directories on the client side to a local directory. This way, you can still use the root user without modifying permissions on the NFS server.</blockquote><p>For example, on each node, you can mount the NFS share like this:</p><pre>$ sudo mount -t nfs &lt;NFS_SERVER_IP&gt;:/path/to/nfs/share /local/mount/point</pre><p>To make it persistent across reboots, add the following entry to <strong>/etc/fstab</strong>:</p><pre>&lt;NFS_SERVER_IP&gt;:/path/to/nfs/share /local/mount/point nfs defaults 0 0</pre><h4>NFS-client</h4><p>Install the NFS client on all nodes with the following command:</p><pre>$ sudo apt update<br>$ sudo apt install nfs-common  # Debian/Ubuntu<br>$ sudo yum install nfs-utils   # CentOS/RHEL</pre><p>This allows your nodes to connect to and use the NFS server. After installing the NFS client, you can create <strong>bind mounts</strong> on your nodes. The general syntax for adding a bind mount in the <strong>/etc/fstab</strong> file is:</p><pre>example.hostname.com:/node1 /opt/example nfs rsize=8192,wsize=8192,timeo=14,intr</pre><p>Then apply the changes:</p><pre>$ sudo mount -a</pre><h3>Kubelet</h3><p>Kubernetes nodes run <strong>kubelet</strong> to manage pods and other resources. Kubelet stores its data in the /var/lib/kubelet directory, which contains folders like:</p><ul><li><strong>pki</strong> — Stores certificates</li><li><strong>pod-resources</strong> — Contains sockets for pod communication</li><li><strong>pods</strong> — Stores pod-related data</li><li><strong>checkpoints</strong> — Keeps track of system states</li></ul><p>Each Kubernetes node has specific directories inside the <strong>Kubelet root folder</strong>. To change the root directory, you need to:</p><ol><li><strong>Create a mount point</strong> on your local machine.</li><li><strong>Modify the Kubelet start command</strong> to set the --root-dir flag.</li></ol><p>First, create the mount point and bind it to the NFS directory:</p><pre>$ sudo mkdir -p /mnt/nfs/kubelet<br>$ sudo mount -o bind /mnt/nfs/kubelet /var/lib/kubelet</pre><p>To make this change permanent, add the following line to <strong>/etc/fstab</strong>:</p><pre>/mnt/nfs/kubelet /var/lib/kubelet none bind 0 0</pre><p>Then, modify the <strong>Kubelet service file</strong> to set the new root directory:</p><pre>$ sudo sed -i &#39;s|/var/lib/kubelet|/mnt/nfs/kubelet|g&#39; /etc/systemd/system/kubelet.service.d/10-kubeadm.conf</pre><p>Reload and restart Kubelet:</p><pre>$ sudo systemctl daemon-reload<br>$ sudo systemctl restart kubelet</pre><p>If you are using <strong>Kubeadm</strong>, this file is probably in <strong>etc/systemd/system/kubelet.service.d/10-kubeadm.conf</strong></p><pre>[Service]<br>Environment=&quot;KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf&quot;<br>Environment=&quot;KUBELET_CONFIG_ARGS=--config=/var/lib/kubelet/config.yaml&quot;<br>Environment=&quot;KUBELET_EXTRA_ARGS=--root-dir=/mnt/nfs/kubelet --cgroup-driver=systemd&quot;<br>ExecStart=<br>ExecStart=/usr/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_CONFIG_ARGS $KUBELET_EXTRA_ARGS</pre><p>If you don’t find the <strong>10-kubeadm.conf</strong> file, you can modify the Kubelet configuration in:</p><pre>/var/lib/kubelet/config.yaml</pre><p>Look for the root-dir option and set it to your desired path, for example:</p><pre>root-dir: /mnt/nfs/kubelet</pre><p>If the option is missing, add it manually.</p><p>After making the changes, restart Kubelet to apply them:</p><pre>$ sudo systemctl daemon-reload<br>$ sudo systemctl restart kubelet<br>$ sudo systemctl status kubelet</pre><p>Check the status of <strong>Kubelet</strong> and make sure it’s running without errors. You can also check its logs using:</p><pre>$ sudo journalctl -u kubelet -f</pre><h3>Kubernetes PVs</h3><p>For Kubernetes Persistent Volumes (PVs), we will use the <strong>nfs-subdir-external-provisioner</strong>. This tool automatically creates and manages subdirectories on a remote NFS server for storage.</p><p>You can install this operator using helm charts:</p><pre>$ helm install nfs-provisioner nfs-subdir-external-provisioner/nfs-subdir-external-provisioner \<br>  --set nfs.server=127.0.0.1 \<br>  --set nfs.path=/workloads/data \<br>  --set storageClass.defaultClass=true \<br>  --set storageClass.reclaimPolicy=Delete \<br>  --set securityContext.runAsUser=3884 \<br>  --namespace=kube-storage</pre><p>Now check the pods, there should be a controller pod:</p><pre>$ kubectl get pods -n kube-storage<br>NAME                                                              READY   STATUS    RESTARTS   AGE<br>nfs-provisioner-nfs-subdir-external-provisioner-78c595dcc4rq7f7   1/1     Running   0          7d2h</pre><p>You should also have an storage class for NFS-client:</p><pre>$ kubectl get sc<br>NAME                   PROVISIONER                                                     RECLAIMPOLICY   VOLUMEBINDINGMODE   ALLOWVOLUMEEXPANSION   AGE<br>nfs-client (default)   cluster.local/nfs-provisioner-nfs-subdir-external-provisioner   Delete          Immediate           false                  8d</pre><p>Check the provisioner field and the logs of controller.</p><p>Now, you can create PVCs by setting the nfs-client storage class:</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: nfs-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteMany<br>  storageClassName: nfs-client<br>  resources:<br>    requests:<br>      storage: 10Gi</pre><p>Check your PV and PVC. The status should be bound with a PV created for your PVC.</p><pre>$ kubectl get pvc -A<br>NAMESPACE       NAME            STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE<br>ml-scheduling   nfs-pvc         Bound    pvc-800344bd-0a4c-4a75-b56d-a4c652e8e0fa   50Gi       RWX            nfs-client     &lt;unset&gt;                 4d</pre><pre>$ kubectl get pv -A<br>NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                         STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE<br>pvc-800344bd-0a4c-4a75-b56d-a4c652e8e0fa   50Gi       RWX            Delete           Bound    ml-scheduling/nfs-pvc         nfs-client     &lt;unset&gt;                          4d</pre><h4>Testing</h4><p>Deploy a pod that mounts the NFS volume:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test-nfs<br>spec:<br>  volumes:<br>    - name: nfs-volume<br>      persistentVolumeClaim:<br>        claimName: nfs-pvc<br>  containers:<br>    - name: busybox<br>      image: busybox<br>      command: [ &quot;sleep&quot;, &quot;3600&quot; ]<br>      volumeMounts:<br>        - mountPath: &quot;/mnt/nfs&quot;<br>          name: nfs-volume</pre><p>Verify that the pod can write to the NFS mount.</p><p>Congratulations! Your Kubernetes cluster is now fully set up with NFS storage. 🚀</p><h3>Conclusion</h3><p>Using NFS for your Kubernetes cluster is useful in a local network. It’s fast and provides dynamic storage management.</p><p>However, a challenge I’m still working on is monitoring NFS storage. The client side doesn’t provide enough metrics to check storage status, and installing exporters on the server isn’t very helpful.</p><p>One idea is to use <strong>nfsiostat</strong> for some insights, but I’m still looking for better ways to monitor NFS effectively.</p><p>Thank youfor your time.<br>I hope that you find this story useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0510d5ed9b0b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/having-your-kubernetes-over-nfs-0510d5ed9b0b">Having your Kubernetes over NFS</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EMQX v5: Under Magnifier]]></title>
            <link>https://amirhossein-najafizadeh.medium.com/emqx-v5-under-magnifier-ad4f6e0b8932?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4f6e0b8932</guid>
            <category><![CDATA[emqx-cluster]]></category>
            <category><![CDATA[emqx-broker]]></category>
            <category><![CDATA[mri-a]]></category>
            <category><![CDATA[mnesia]]></category>
            <category><![CDATA[emqx-v5]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 02:35:50 GMT</pubDate>
            <atom:updated>2024-09-26T03:41:05.972Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether you have been using EMQX for many years, are just hearing about it for the first time, or are required to use it by your managers, it is useful to learn about the new architecture of EMQX (also known as EMQX v5). Regardless of whether you currently use EMQX, the concepts in this new version can provide valuable insights for designing your distributed applications. In this story, I will explore EMQX v5 to examine its new architecture. By comparing it to EMQX v4, we will highlight its benefits.</p><p>I will not delve deeply into its underlying logic or related topics such as the MQTT protocol, distributed systems, RPCs, etc. Instead, I will provide an overview of these topics along with some technical details about EMQX. It doesn’t matter whether you should use it or not; what matters is understanding its purpose. I am not focused on comparing it to other message brokers like NATS or Kafka. The main concern here is the logic behind EMQX. If you are looking for an endorsement of MQTT and a recommendation to use it, you can stop reading this article. However, if you are willing to set aside any biases, consider EMQX as the only message broker you know, and observe how it has been implemented. I will not make any judgments or claim whether EMQX is good or bad. As the title indicates, I will simply review their documents, articles, and statements in detail. Think of this as an insightful exploration into the world of EMQX.</p><h3>Introduction</h3><p>During my time as a cloud engineer, I worked with EMQX as a centeral message queue. Specifically, my task was to investigate the split-brain issue associated with EMQX and ultimately find a solution to prevent this problem. At that time, we had recently upgraded our EMQX cluster from v4 to v5, and none of us, including myself, fully understood how it operated. After some time, we began exploring their documents and source code. Our goal was to gather as much information as possible to understand the semantics of our cluster.</p><h3>EMQX</h3><p>First things first, let’s talk about EMQX so we could have a basic viewpoint of it. EMQX is a message broker that operates using the MQTT protocol. As they said, “<em>EMQX is a large-scale distributed MQTT messaging platform that offers unlimited connections, seamless integration, and anywhere deployment</em>”.</p><p>EMQX is a message broker that can function both as a single-node component and a distributed cluster. Like other applications, you may want to scale it when faced with increased load. As with any distributed system, it offers a mechanism to replicate data across multiple nodes. Additionally, it aims to ensure fault tolerance, maintain high availability, reduce latency, and facilitate easy maintenance through automated methods for fault detection and self-healing. However, the semantics of these features are not very clear, and the documentation could be improved.</p><figure><img alt="EMQX Cluster overview" src="https://cdn-images-1.medium.com/max/1024/1*LmRlOhDyvZcjEcL9pMJiJQ.png" /><figcaption>EMQX uses MQTT to manage events between devices</figcaption></figure><p>Their approach is certainly one of the best available. Before delving into the details of EMQX v5, let’s first examine v4. The reason we focus on the newer version is that the evolution from v4 to v5 represents a significant transformation; they have fundamentally changed many aspects of the system.</p><h4>EMQX v4</h4><p>At its core, EMQX functions like a typical message broker, without any particularly unique features. Developed using Erlang, it utilizes an integrated distributed database called <strong>Mnesia</strong>, which serves to replicate data between cluster nodes. It serves as an embedded storage and replication layer for OTP applications requiring low read latency and high availability.</p><p>The nodes data consists of two important components.</p><ul><li><strong>Routing tables</strong>, which is a metadata to get data from client and send data between nodes to give back to desired client</li><li><strong>Topic tress</strong>, which were used to partition data in order to be able to manage them</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5E7EZyfswDoDf1vohp-_g.png" /></figure><pre>// An example of a EMQX topic tree<br>chat/room/1<br>chat/*<br>sensor/10/temperature<br>sensor/+/temperature<br>sensor/#<br>// It also includes system topics<br>$SYS/brokers<br>$SYS/brokers/${node}/uptime</pre><p>The publish and subscribe mechanism relies on this data. When a new subscriber joins, it dynamically builds topic trees and updates the routing table. Subsequently, a node must replicate this data. Since a client’s request is independent and does not require complex logic or validation, nodes can simply share their <strong>routing</strong> and <strong>topic</strong> trees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfp4xMrS6JvtdmIghyblbw.png" /><figcaption>An example of EMQX flow. When a new subscrib request comes, all nodes update their routing tables. After that, they use it to forward messages.</figcaption></figure><p>Overall, the system is straightforward. However, what could go wrong? One significant issue is that the cluster topology is fully meshed, meaning that all N nodes are interconnected. This design leads to numerous RPC calls when attempting to replicate data. Furthermore, if a split-brain scenario occurs, the situation can become quite problematic. As each node performs read and write operations independently, each section can inadvertently create its own cluster without anyone noticing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hzPcuZlf-jqCD__VcrxZsg.png" /><figcaption><strong>Mnesia</strong> fully mesh topology</figcaption></figure><p>Let’s consider a cluster with <em>N</em> nodes. For each transaction (we’ll use a subscribe request as an example, since it is more complex), we can calculate the total number of RPC calls required to commit this transaction:</p><ol><li>The client sends a request to any node (RPC_Count = 0).</li><li>The node stores the user request (RPC_Count = 0).</li><li>The node calls the other nodes to update their routing tables (RPC_Count = <em>N — 1</em>).</li><li>For commitment, the nodes share their data with each other (RPC_Count = <em>N * (N — 1)</em>).</li></ol><p>In total, the RPC calls for this transaction would be <em>0 + 0 +(N−1) + N∗(N−1) = (N-1)*(N+1) = N² — 1</em>.</p><p>Therefore, the overall number of RPC calls for a single subscribe request is on the order of <em>O(N²)</em>. This is not ideal, as increasing the number of nodes results in an exponential growth in RPC calls.</p><h4>Challenges</h4><p>This architecture leads to<strong> high latency</strong>, increased <strong>network traffic</strong>, no <strong>fault tolerance</strong>, a higher likelihood of <strong>split-brain</strong> scenarios, and concerns regarding <strong>data safety</strong>. Additionally, we must consider the publish transactions that also need to be routed between nodes. Given these factors, it does not make sense to use more than five nodes in such a configuration.</p><h3>EMQX v5</h3><p>In v5, EMQX introduced an enhanced version of <strong>Mnesia</strong> called <strong>Mria</strong>. As they said “<em>Mria is an extension for Mnesia database that adds eventual consistency to the cluster</em>”. Moreover in their ACM article they stated “<em>We analyze the limitations of Mnesia’s replication protocol scalability in large clusters under high load. To address these limitations, we developed Mria, an extension to the Mnesia database that provides eventual consistency within a cluster and achieves better horizontal scalability</em>”.</p><p>This built-in database includes a significant new feature: <strong>RLOG</strong>. The <strong>RLOG</strong> feature allows nodes to operate in one of two modes: <strong>CORE</strong> or <strong>REPLICANT</strong>. In this setup, only CORE nodes are responsible for managing routing tables, topic trees, and write operations. All other operations, such as read and publish routing, are handled by REPLICANT nodes. As they mentioned “<em>data is read locally on all nodes, but only a few nodes actively participate in the transaction. This allows to improve write throughput of the cluster without sacrificing read latency, at the cost of strong consistency guarantees</em>”.</p><p>For performance reasons, <strong>Mnesia</strong> tables are separated into disjunctive subsets called <strong>RLOG</strong> shards. Transactions for each shard are replicated independently. Currently transaction can only modify tables in one shard. Usually it is a good idea to group all tables that belong to a particular OTP application in one shard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gwsFy3vjW6EixUTQFWyoQ.png" /><figcaption><strong>Mria</strong> architecture, <strong>COREs</strong> and <strong>REPLICANTs</strong></figcaption></figure><p>Since CORE nodes are responsible for storing and managing data, they are stateful. In contrast, REPLICANT nodes are stateless, which means they do not require a persistent volume.</p><p>In the new architecture, each REPLICANT is connected to a CORE node. The CORE shares its tables in batches with its REPLICANTs. To reduce the number of RPC calls between CORE and REPLICANTs, each REPLICANT maintains its own local database, which is eventually synchronized with the CORE nodes. As the said “<em>dirty reads and read-only transactions run locally on the replicant. The semantics of the read operations are the following: they operate on a consistent, but potentially outdated snapshot of the data</em>”.</p><p>CORE nodes function similarly to the normal nodes in <strong>v4</strong>, forming a fully meshed topology and sharing data through <strong>RPC</strong> calls (which they use gen_rpc for it). However, they do not handle routing or read operations, which reduces the overall workload on CORE nodes. As a result, the overall latency is decreased.</p><h4>New Features</h4><p>EMQX v5 incorporates a new module called <strong>Ekka</strong>, which provides features such as auto-healing, auto-recovery, heart beat checking, centralised monitoring/managing, and cluster rebalancing.</p><p>With this new architecture, you can increase the number of REPLICANTs as needed. Since the number of required CORE nodes is relatively small, the likelihood of split-brain scenarios is reduced. Furthermore, because the topology is fully meshed, you can utilize a majority factor to detect network partitions and remove split nodes.</p><p>By keeping the critical logic simple and concentrated in a few nodes, EMQX v5 provides a fault-tolerant cluster. Operations can be performed in parallel, and monitoring can be easily managed by a central unit (which consists of all CORE nodes).</p><p>Additionally, REPLICANTs can operate on a separate network, creating an isolated partition for CORE nodes. This allows you to establish a connection link between COREs and REPLICANTs, effectively preventing the influence of faulty nodes on your CORE nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*NMkspfeepZV1gf7g8chD3A.png" /><figcaption>Two isolated networks for COREs and REPLICANTs</figcaption></figure><p>The main idea is to divide our operations into two categories: Idempotent and Non-idempotent. Read operations fall under the idempotent category, meaning they are safe and do not alter the system’s state. In contrast, write operations are non-idempotent, as they change the system’s state. The important point to consider is that determining whether an operation is truly idempotent is not always straightforward. For instance, even when handling a read operation, data consistency is crucial. You must ensure that the data is valid and up-to-date every time.</p><p>In the case of EMQX, they implement eventual consistency. Additionally, they reduce the time required for idempotent operations by moving them to REPLICANT nodes. This allows CORE nodes to focus more on maintaining consistency and performance.</p><h3>Conclusion</h3><p>The concept of separation within a distributed system architecture is highly advantageous for several reasons. By managing COREs and REPLICANTs independently, we not only enhance the <strong>overall maintenance</strong> of the system but also <strong>improve its semantics</strong>, leading to clearer definitions of responsibilities and behaviors within each component. This independent management allows for focused optimizations and adjustments without impacting the entire system, thereby fostering a more modular and manageable architecture.</p><p>Additionally, this separation significantly increases <strong>fault tolerance</strong>. Since the majority of nodes are stateless and can be easily replaced, the system can continue to function effectively even in the face of individual node failures. This design mitigates the risks associated with hardware malfunctions or temporary outages, ensuring that service availability remains high. Furthermore, the architecture allows for the integration of additional modules designed to <strong>automate</strong> various tasks related to <strong>system management</strong>. These modules can handle critical functions such as rebalancing workloads, detecting failures, managing nodes, and more, thereby streamlining operations and reducing the need for manual interventions.</p><p>However, while the separation of COREs and REPLICANTs offers numerous benefits, there are several critical points that require careful attention. Firstly, our approach introduces a <strong>potential single point of failure</strong> within the system. Although there are multiple CORE nodes intended to distribute the workload, they could still become a <strong>bottleneck</strong>. In situations where a particular CORE node becomes overloaded or fails, it can adversely affect the entire system, leading to reduced performance or complete system outages. As said, the architecture remains vulnerable to split-brain scenarios, where multiple parts of the system may operate independently without a unified understanding of the overall state. This situation necessitates the implementation of robust mechanisms to detect and remove faulty nodes from the system promptly. Failure to address this can lead to data inconsistency and degraded system performance, undermining the reliability that the architecture aims to provide.</p><p>Finally, it is important to note that REPLICANT nodes are <strong>not fully synchronized</strong> with the CORE nodes. Their data is updated in batches sent by the CORE nodes, resulting in eventual synchronization/consistency rather than immediate consistency. This inherent delay means that data <strong>consistency across REPLICANT nodes cannot always be guaranteed at any given moment</strong>, potentially leading to discrepancies that could impact the user experience or the accuracy of operations dependent on real-time data.</p><p>In summary, while the separation of COREs and REPLICANTs in our architecture offers significant advantages in terms of maintenance, fault tolerance, and modularity, it also presents challenges that must be proactively managed to ensure system reliability and data consistency.</p><p>I hope this was useful to you.</p><p>Thanks for your time.</p><p>Amir Zadeh.</p><h3>References</h3><p>For more information, you can use following references.</p><ul><li><a href="https://docs.emqx.com/en/emqx/latest/">EMQX Overview | EMQX Docs</a></li><li><a href="https://docs.emqx.com/en/emqx/latest/deploy/cluster/introduction.html">Cluster | EMQX Docs</a></li><li><a href="https://docs.emqx.com/en/emqx/latest/design/clustering.html">Design for EMQX Clustering | EMQX Docs</a></li><li><a href="https://docs.emqx.com/en/emqx/latest/deploy/cluster/mria-introduction.html">Architecture | EMQX Docs</a></li><li><a href="https://github.com/emqx/mria">GitHub - emqx/mria: Asynchronously replicated Mnesia-like database for Erlang/Elixir</a></li><li><a href="https://dl.acm.org/doi/10.1145/3609022.3609416">Mria: An Eventually Consistent Mnesia | Proceedings of the 22nd ACM SIGPLAN International Workshop on Erlang</a></li><li><a href="https://github.com/emqx/ekka">GitHub - emqx/ekka: Autocluster and Autoheal for EMQX Broker</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4f6e0b8932" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking NATS JetStream Cluster: Hypothesis Testing for Enhancements]]></title>
            <link>https://amirhossein-najafizadeh.medium.com/benchmarking-nats-jetstream-cluster-hypothesis-testing-for-enhancements-4a500d11ce7b?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a500d11ce7b</guid>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[jetstream]]></category>
            <category><![CDATA[nats-streaming]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[benchmarking]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 09:29:22 GMT</pubDate>
            <atom:updated>2024-06-29T12:24:26.416Z</atom:updated>
            <content:encoded><![CDATA[<p>As a part of a cloud engineering team, among our services, we primarily manage multiple NATS clusters, which serves as the central message queues in our systems. The JetStream feature of NATS has been operational in many businesses. Utilizing multiple streams within a single cluster enhances ability to distribute events swiftly and reliably. Additionally, this setup allows retain messages temporarily to accommodate slow processing or disconnections among consumers.</p><p>A significant challenge we face is modifying the configurations of the cluster or streams. As our cluster processes millions of write/read operations per second, it is crucial to ensure that these changes do not reduce the cluster’s throughput. To verify this, we benchmark the cluster’s performance before and after any adjustments.</p><p>Benchmarking effectively assesses whether these changes impact throughput. However, it is difficult to draw definitive conclusions from this process alone. We are challenged by the need to determine the number of benchmarks required to ensure the results are neither random nor biased. Additionally, when a configuration change proves beneficial, we need to quantify the extent of this improvement. These issues have led us to employ hypothesis testing with our benchmarking results.</p><h3>Our case</h3><p>When we initially migrated our NATS cluster to JetStream, each stream had a single replication. A few months later, JetStream introduced an update that allowed multiple replications for streams, enhancing the robustness of our distributed NATS cluster. This feature is particularly valuable in failure scenarios, ensuring that our services continue to receive events even if one cluster node fails. Additionally, it helps distribute the load evenly across the cluster nodes, thus enhancing reliability under heavy loads.</p><p>However, adding replications to our streams can reduce the write speed due to the time required for replicas to synchronize. In a single-replica stream, there is no synchronization overhead. Therefore, before we scale our streams, we needed to know how it would affect our cluster’s throughput.</p><h3>Benchmarking a NATS cluster</h3><p>To benchmark a NATS cluster, we utilized a feature of the nats-cli called nats-bench. This command includes various functions for conducting benchmarks on both NATS and JetStream clusters. It offers several options to customize the benchmark, such as the number of publishers, consumers, and messages. Below, you will find a list of these options along with their descriptions.</p><pre>usage: nats bench [&lt;flags&gt;] &lt;subject&gt;<br><br>Benchmark utility<br><br>Core NATS publish and subscribe:<br><br>  nats bench benchsubject --pub 1 --sub 10<br><br>Request reply with queue group:<br><br>  nats bench benchsubject --sub 1 --reply<br><br>  nats bench benchsubject --pub 10 --request<br><br>JetStream publish:<br><br>  nats bench benchsubject --js --purge --pub 1<br><br>JetStream ordered ephemeral consumers:<br><br>  nats bench benchsubject --js --sub 10<br><br>JetStream durable pull and push consumers:<br><br>  nats bench benchsubject --js --sub 5 --pull<br><br>  nats bench benchsubject --js --sub 5 --push<br><br>JetStream KV put and get:<br><br>  nats bench benchsubject --kv --pub 1<br><br>  nats bench benchsubject --kv --sub 10<br><br>Remember to use --no-progress to measure performance more accurately<br><br>Args:<br>  &lt;subject&gt;  Subject to use for the benchmark<br><br>Flags:<br>  --pub=0                     Number of concurrent publishers<br>  --sub=0                     Number of concurrent subscribers<br>  --js                        Use JetStream<br>  --request                   Request-Reply mode: publishers send requests waits<br>                              for a reply<br>  --reply                     Request-Reply mode: subscribers send replies<br>  --kv                        KV mode, subscribers get from the bucket and<br>                              publishers put in the bucket<br>  --msgs=100000               Number of messages to publish<br>  --size=&quot;128&quot;                Size of the test messages<br>  --no-progress               Disable progress bar while publishing<br>  --csv=CSV                   Save benchmark data to CSV file<br>  --purge                     Purge the stream before running<br>  --storage=file              JetStream storage (memory/file) for the<br>                              &quot;benchstream&quot; stream<br>  --replicas=1                Number of stream replicas for the &quot;benchstream&quot;<br>                              stream<br>  --maxbytes=&quot;1GB&quot;            The maximum size of the stream or KV bucket in<br>                              bytes<br>  --stream=&quot;benchstream&quot;      When set to something else than &quot;benchstream&quot;:<br>                              use (and do not attempt to define) the specified<br>                              stream when creating durable subscribers.<br>                              Otherwise define and use the &quot;benchstream&quot; stream<br>  --bucket=&quot;benchbucket&quot;      When set to something else than &quot;benchbucket&quot;:<br>                              use (and do not attempt to define) the specified<br>                              bucket when in KV mode. Otherwise define and use<br>                              the &quot;benchbucket&quot; bucket<br>  --consumer=&quot;natscli-bench&quot;  Specify the durable consumer name to use<br>  --jstimeout=30s             Timeout for JS operations<br>  --syncpub                   Synchronously publish to the stream<br>  --pubbatch=100              Sets the batch size for JS asynchronous publishing<br>  --pull                      Use a shared durable explicitly acknowledged JS<br>                              pull consumer rather than individual ephemeral<br>                              consumers<br>  --push                      Use a shared durable explicitly acknowledged<br>                              JS push consumer with a queue group rather than<br>                              individual ephemeral consumers<br>  --consumerbatch=100         Sets the batch size for the JS durable pull<br>                              consumer, or the max ack pending value for the JS<br>                              durable push consumer<br>  --subsleep=0s               Sleep for the specified interval before sending<br>                              the subscriber acknowledgement back in --js mode,<br>                              or sending the reply back in --reply mode,<br>                              or doing the next get in --kv mode<br>  --pubsleep=0s               Sleep for the specified interval after publishing<br>                              each message<br>  --history=1                 History depth for the bucket in KV mode<br>  --multisubject              Multi-subject mode, each message is published on<br>                              a subject that includes the publisher&#39;s message<br>                              sequence number as a token<br>  --multisubjectmax=100000    The maximum number of subjects to use in<br>                              multi-subject mode (0 means no max)<br>  --retries=3                 The maximum number of retries in JS operations<br>  --dedup                     Sets a message id in the header to use JS Publish<br>                              de-duplication<br>  --dedupwindow=2m            Sets the duration of the stream&#39;s deduplication<br>                              functionality</pre><p>Also, you can read more about nats-cli and nats-bench through these links.</p><ul><li><a href="https://docs.nats.io/using-nats/nats-tools/nats_cli">https://docs.nats.io/using-nats/nats-tools/nats_cli</a></li><li><a href="https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench">https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench</a></li></ul><h4>Benchmark Runbook</h4><p>By using nats-bench, we aimed to execute its commands repeatedly at will. Additionally, we sought to include failure recovery in our benchmarks and automate the process as much as possible. To achieve this, we developed a runbook using Python. This runbook utilizes a cmd.json file, which contains the nats-bench commands and flags, and a context.json file, which provides the necessary details to connect to a NATS cluster. Examples of each file are provided below. First file is nats context, and the second file is benchmark commands.</p><pre>{<br>  &quot;description&quot;: &quot;Default NATS context&quot;,<br>  &quot;url&quot;: &quot;nats://0.0.0.0:4222&quot;,<br>  &quot;socks_proxy&quot;: &quot;&quot;,<br>  &quot;token&quot;: &quot;&quot;,<br>  &quot;user&quot;: &quot;admin&quot;,<br>  &quot;password&quot;: &quot;password&quot;,<br>  &quot;creds&quot;: &quot;&quot;,<br>  &quot;nkey&quot;: &quot;&quot;,<br>  &quot;cert&quot;: &quot;&quot;,<br>  &quot;key&quot;: &quot;&quot;,<br>  &quot;ca&quot;: &quot;&quot;,<br>  &quot;nsc&quot;: &quot;&quot;,<br>  &quot;jetstream_domain&quot;: &quot;&quot;,<br>  &quot;jetstream_api_prefix&quot;: &quot;&quot;,<br>  &quot;jetstream_event_prefix&quot;: &quot;&quot;,<br>  &quot;inbox_prefix&quot;: &quot;&quot;,<br>  &quot;user_jwt&quot;: &quot;&quot;,<br>  &quot;color_scheme&quot;: &quot;blue&quot;<br>}</pre><pre>[<br>    {<br>        &quot;name&quot;: &quot;clear-stream&quot;,<br>        &quot;command&quot;: &quot;nats stream delete benchstream --force -s nats://0.0.0.0:4222&quot;,<br>        &quot;syscall&quot;: true<br>    },<br>    {<br>        &quot;name&quot;: &quot;normal-stats&quot;,<br>        &quot;count&quot;: 20,<br>        &quot;command&quot;: &quot;rides --js --pub 5 --sub 15 -s nats://0.0.0.0:4222&quot;,<br>        &quot;pre-commands&quot;: [<br>            &quot;nats stream purge benchstream --force -s nats://0.0.0.0:4222&quot;<br>        ],<br>        &quot;timeout&quot;: 180,<br>        &quot;syscall&quot;: false<br>    }<br>]</pre><p>The commands in the cmd.json file first delete benchstream from our NATS cluster. Afterward, they run a benchmark on the rides topic with 5 publishers and 15 subscribers over a local JetStream server 20 times. A purge stream command is executed before each benchmark.</p><p>Upon completion, the runbook generates a CSV file that details the data for write, read, and overall throughput in megabytes per second. An example is provided below.</p><pre>pub-stats,sub-stats,overall-stats<br>40.4,606.89,646.21<br>34.96,524.86,559.25<br>33.96,510.61,543.1<br>27.47,412.89,439.56<br>32.0,480.52,511.7</pre><p>You can access our runbook via the following link.</p><ul><li><a href="https://github.com/amirhnajafiz/natsbench-runbook">https://github.com/amirhnajafiz/natsbench-runbook</a></li></ul><h3>Hypothesis Testing</h3><p>It is like trying to solve a mystery by gathering clues (data) and deciding if they strongly suggest that something happened or not. According to Wikipedia, hypotheses testing is a method used in statistics to determine if there is enough evidence to reject a null hypothesis (our base assumption). Overall, it helps make decisions based on data analysis.</p><h4>Key terms</h4><ul><li>Null Hypothesis (H₀): The default assumption that there is no effect or no difference.</li><li>Alternative Hypothesis (H₁): The statement we want to test against.</li><li>Significance Level (α): The probability of rejecting the null hypothesis when it is true, commonly set at 0.05.</li><li>P-value: The probability of obtaining test results at least as extreme as the observed results, assuming the null hypothesis is true.</li><li>Test Statistic: A standardized value used to decide whether to reject the null hypothesis.</li><li>Equal vars: If its false, it means that the variances of the two groups are assumed to be unequal, and different statistical procedures are used to accommodate this assumption. This assumption is important because it affects the calculation of test statistics and determines which formula or method is used to analyze the data.</li><li>Permutations: Refer to the different ways in which a set of elements can be arranged or ordered.</li></ul><h4>Types of Hypothesis Testing</h4><ul><li>t-test: Compares the means of two groups.</li><li>Chi-square test:Tests for association between categorical variables.</li><li>ANOVA (Analysis of Variance): Compares means among three or more groups.</li><li>Regression Analysis: Examines relationships between variables.</li></ul><p>As previously mentioned, we aimed to compare the cluster throughput before and after implementing our changes. To accomplish this, we utilized the t-test.</p><h4>t-test steps</h4><ol><li>State the Hypotheses</li><li>Choose the Significance Level (α). Commonly used values are 0.05, 0.01.</li><li>Collect Data and Compute Test Statistic. Depends on the type of test (e.g., t-test, chi-square test).</li><li>Determine the P-value</li><li>Compare the p-value with α.</li><li>Make a Decision. If p-value ≤ α, reject the null hypothesis. If p-value &gt; α, do not reject the null hypothesis.</li></ol><h3>Integrate Benchmark and t-test</h3><p>Now equipped with a runbook to conduct benchmarks, we employed the following code to read the CSV files and perform a t-test on our data. In the code, we initially load data from the CSV files into pandas dataframes. Subsequently, we use the scipy.stats library to execute the t-test.</p><pre>import pandas as pd<br>from scipy.stats import ttest_ind<br><br>GROUP_A=&quot;no-syncpub-3/dataset.csv&quot;<br>GROUP_B=&quot;no-syncpub-rep1/dataset.csv&quot;<br><br># ttest variables<br>P_VALUE_BOUND = 0.05<br>PERMUTATION_VALUE = 25<br><br># read csv to create groups datasets<br>dfA = pd.read_csv(f&#39;{GROUP_A}&#39;)<br>dfB = pd.read_csv(f&#39;{GROUP_B}&#39;)<br><br>t_statistic, p_value = ttest_ind(dfA, dfB, equal_var=True, permutations=PERMUTATION_VALUE)<br>if p_value &lt; P_VALUE_BOUND:<br>        print(&quot;the difference is statistically significant at 95% confidence level.&quot;)</pre><p>The output indicates which group performs better, by what percentage it improves, and the extent of the change in throughput.</p><pre>testing `pub-stats` field:<br> mean of `no-syncpub-3/dataset.csv`: 11.9496<br> mean of `no-syncpub-rep1/dataset.csv`: 20.551999999999992<br> t-statistic: -22.983042981964857<br> p-value: 0.0<br>the difference is statistically significant at 95% confidence level.<br>`no-syncpub-rep1/dataset.csv` is better by 41.85675360062279%.</pre><p>You can see an example in the following notebook.</p><ul><li><a href="https://github.com/amirhnajafiz/natsbench-runbook/tree/master/notebooks">https://github.com/amirhnajafiz/natsbench-runbook/tree/master/notebooks</a></li></ul><h3>Conclusion</h3><p>After conducting 100 benchmarks comparing different scenarios and using t-test with equal-vars and permutation 50 for our hypothesis testing, we found that migrating to streams with three replicas would result in a 45% reduction in throughput for synchronous publishers and a 28% reduction for asynchronous publishers. Nevertheless, our current throughput on the single-replica stream was utilizing less than 50% of its capacity. Therefore, we were confident that scaling up to three replicas would not adversely affect our operations.</p><p>You can see these stats and their results below.</p><pre>Comparing replication 1 and 3 for sync publishers:<br>testing `pub-stats` field:<br>mean of `syncpub-rep1/dataset.csv`: 1.0848698<br>mean of `syncpub-3/dataset.csv`: 0.8084258333333334<br>t-statistic: 20.831836518519147<br>p-value: 0.0<br>the difference is statistically significant at 95% confidence level.<br>`syncpub-rep1/dataset.csv` is better by 25.481764416952768%</pre><pre>Comparing replication 1 and 3 for async publishers:<br>testing `pub-stats` field:<br>mean of `no-syncpub-rep1/dataset.csv`: 20.551999999999992<br>mean of `no-syncpub-3/dataset.csv`: 11.9496<br>t-statistic: 22.983042981964857<br>p-value: 0.0<br>the difference is statistically significant at 95% confidence level.<br>`no-syncpub-rep1/dataset.csv` is better by 41.85675360062279%</pre><h3>References</h3><ul><li><a href="https://github.com/amirhnajafiz/natsbench-runbook/blob/master/notebooks/presentation.ipynb">https://github.com/amirhnajafiz/natsbench-runbook/blob/master/notebooks/presentation.ipynb</a></li><li><a href="https://github.com/amirhnajafiz/natsbench-runbook/blob/master/README.md">https://github.com/amirhnajafiz/natsbench-runbook/blob/master/README.md</a></li><li><a href="https://www.investopedia.com/terms/t/t-test.asp#:~:text=A%20t%2Dtest%20is%20an,flipping%20a%20coin%20100%20times">https://www.investopedia.com/terms/t/t-test.asp#:~:text=A%20t%2Dtest%20is%20an,flipping%20a%20coin%20100%20times</a>.</li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html</a></li><li><a href="https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench">https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a500d11ce7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minio shared objects operator]]></title>
            <link>https://amirhossein-najafizadeh.medium.com/minio-shared-objects-operator-d4a718f40a0?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a718f40a0</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[minio-operator]]></category>
            <category><![CDATA[minio]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 10:12:55 GMT</pubDate>
            <atom:updated>2023-08-22T10:12:55.822Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story I’m going to present an application called Minio URL Operator. I created this service in order to manage objects in Minio cluster that we want to share. This operator helps you to config and manage these urls.</p><h3>Problem</h3><p>Minio is an object storage server that implements the same public API as Amazon S3. This means that applications that can be configured to talk to Amazon S3 can also be configured to talk to Minio. MinIO optimizes storage of objects across available pools by writing new objects (that is, objects with no existing versions) to the server pool with the most free space compared total amount of free space on all available server pools.</p><p>MinIO Object Storage uses buckets to organize objects. A bucket is similar to a top-level drive, folder, or directory in a filesystem ( /mnt/data or C:\ ), where each bucket can hold an arbitrary number of objects. With the example structure, an administrator would create the /images , /videos and /articles buckets.</p><p>You can export these objects by creating a unique resource locator. This url will get you the requested object from the cluster. But this url is not accessible in outside of your cluster. And it’s not human readable at all. You can see an example of these urls below.</p><pre>https://min.io/docs/minio/linux/developers/javascript/API.html#presignedUrl:%7E:text=getObject(bucketName%2C%20objectName%2C%20getOpts%5B%2C%20callback%5D)</pre><p>Moreover, it’s not even permanent. Minio shared objects urls expire after 7 days and you need to regenerate them.</p><h4>Method</h4><p>In order to fix these problems, I created an operator to manage shared objects urls. I build a HTTP server using <strong>Flask</strong> and <strong>MySQL</strong> in order to control Minio urls. We map each object in a bucket to an address in this operator. When you want to access an object, this system acts like a proxy and redirects your request to Minio cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*3tjKTsMvkCqi_hh1qxBeYw.png" /><figcaption>Minio url operator schema</figcaption></figure><p>When you connect to Minio cluster, it will get objects metadata and generates a maped item in our MySQL database. After that it uses these data to manage and config urls. The system gets objects metadata from Minio using a python code like this:</p><pre>def get_objects_metadata(self, bucket, prefix=&quot;&quot;) -&gt; list:<br>        &quot;&quot;&quot;get objects of a bucket based on prefix<br><br>        :param bucket: minio bucket<br>        :param prefix: objects prefix<br>        :return: list of objects metadata<br>        &quot;&quot;&quot;<br>        client = self.minio_connection.get_connection()<br><br>        objects = client.list_objects(bucket, prefix=prefix)<br><br>        objects_list = []<br><br>        for item in objects:<br>            tmp = self.__get_object__(bucket, item.object_name)<br><br>            object_pack = {<br>                &#39;name&#39;: item.object_name,<br>                &#39;address&#39;: tmp.address,<br>                &#39;status&#39;: tmp.status,<br>                &#39;created_at&#39;: tmp.createdAt,<br>                &#39;updated_at&#39;: tmp.updatedAt,<br>                &#39;expires_at&#39;: tmp.expiresAt<br>            }<br><br>            objects_list.append(object_pack)<br><br>        return objects_list</pre><h4>Features</h4><p>System supports the following list of features:</p><ul><li>Generating HRU (human read URL) for objects</li><li>Set expire time (no 7 days limit)</li><li>Block object access when needed</li></ul><h3>Operator</h3><p>In this section we are going to talk about how you can use this operator in order to manage your objects.</p><h4>How to use?</h4><p>You can use docker image of MUP in order to setup the operator on Docker or Kubernetes.</p><pre>docker pull amirhossein21/muo:v0.4.0</pre><h4>Run</h4><p>In order to setup our container, you can use the following command:</p><pre>docker run -d -it \<br> -e HTTP_PORT=80 -e HTTP_DEBUG=0 -e MINIO_HOST=localhost:9000 \<br> -e MINIO_SECURE=0 -e MINIO_ACCESS=9iWKawYzq68iNMN7MsiU \<br> -e MINIO_SECRET=zWwZlmTX56Hr8NYBOpN4ga2zV8oO2ECIjjPHPF20 \<br> -e HTTP_HOST=localhost -e HTTP_PRIVATE=1 \<br> amirhossein21/muo:v0.4.0</pre><h4>Envs</h4><p>This operator has several environmental variables in order to manage your server.</p><ul><li>HTTP_PORT</li><li>HTTP_DEBUG</li><li>HTTP_HOST</li><li>HTTP_PRIVATE</li><li>MYSQL_HOST</li><li>MYSQL_PORT</li><li>MYSQL_USER</li><li>MYSQL_PASSWORD</li><li>MYSQL_DB</li><li>MYSQL_MIGRATE</li><li>MINIO_HOST</li><li>MINIO_SECURE</li><li>MINIO_ACCESS</li><li>MINIO_SECRET</li></ul><h3>Conclusion</h3><p>By using this operator for Minio shared objects links you can help yourself in managing urls. Since Minio object storage provides urls for sharing objects with a maximum 7 days limit, you can use this operator in order to have live urls for every object that you want. With this operator, you can create a persistent HRU for your objects in Minio.</p><p>More documents can be found in project <a href="https://github.com/amirhnajafiz/minio-url-operator">repository</a>.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a718f40a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Cron-jobs (Python)]]></title>
            <link>https://amirhossein-najafizadeh.medium.com/kubernetes-cron-jobs-python-6167135d5d8f?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/6167135d5d8f</guid>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Mon, 29 May 2023 08:11:15 GMT</pubDate>
            <atom:updated>2023-05-29T08:11:15.907Z</atom:updated>
            <content:encoded><![CDATA[<p>A CronJob creates Jobs on a repeating schedule. CronJob is meant for performing regular scheduled actions such as backups, report generation, and so on. One CronJob object is like one line of a crontab (cron table) file on a Unix system. It runs a job periodically on a given schedule, written in Cron format.</p><p>In Kubernetes cluster you can create a cron-job by using CronJob kind in batch/v1version. You need to generate a manifest like the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d8ea1a8c5e3285513790440b4833e0f/href">https://medium.com/media/2d8ea1a8c5e3285513790440b4833e0f/href</a></iframe><p>As you can see in the manifest, you have to set a container image in order to execute your job.</p><p>Now imagine that you want to execute a <em>Python</em> script on Kubernetes cluster as a cron-job. You have to write your code, create a <em>Dockerfile</em>, build an image, and deploy it to an image registry. If you want to edit your script, you need to do these stages over and over again. This process results in the amount of time for making a change, harder maintenance, and harder debugging process.</p><p>Me and my teammates in <strong>Snappline!</strong> came with an idea of building an image that gets some config variables and clones into a git repository, and executes the <em>Python</em> script in that repository. With this image, you only build one image and you use it in order to execute as many python scripts as you wish.</p><h3>Charlie</h3><p>The name of this image is Charlie. You can build your Charlie image by creating a requirements.txt file and generate your image. For example you want to use Flask and Pandas in your python script. You need to create a text file like this and put it in <em>lib</em> directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b48c57d89fa3c5bddff13c8fa39009/href">https://medium.com/media/48b48c57d89fa3c5bddff13c8fa39009/href</a></iframe><p>After that you can build your image with following command:</p><pre>docker buildx build --platform linux/amd64 . -t charlie:v0.1 -f build/Dockerfile</pre><p>Now you can execute the container with this command:</p><pre>docker run \<br>--env REPOSITORY=&#39;github.com/amirhnajafiz/charlie&#39; \<br>--env DIRECTORY=&#39;charlie&#39; \<br>--env SCRIPT_PATH=&#39;test&#39; \<br>--mount type=bind,source=&quot;$(pwd)/clone&quot;,target=/src/clone \<br>&lt;snapp-image-registery&gt;/charlie@v0.1.0</pre><p>At this moment, each time you run this container, it clones into REPOSITORY and executes the script in SCRIPT_PATH. No need to build a new image.</p><h3>CronJob</h3><p>Now let’s create a new cron-job manifest with Charlie.</p><pre>apiVersion: batch/v1<br>kind: CronJob<br>metadata:<br>  name: &#39;myjob&#39;<br>  labels:<br>    app: &#39;myjob&#39;<br>spec:<br>  schedule: &quot;30 2 * * *&quot;<br>  timeZone: &#39;Asia/Tehran&#39;<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          containers:<br>            - name: charlie<br>              image: image-registry.openshift-image-registry.svc:5000/snappline-app/charlie:v0.3.1<br>              volumeMounts:<br>                - mountPath: /src/clone<br>                  name: report-dir<br>              envFrom:<br>                - configMapRef:<br>                    name: job-configs<br>          restartPolicy: Never<br>          volumes:<br>            - name: report-dir<br>              emptyDir: { }</pre><p>You can find more information about env variables of Charlie and how to build your own image in the following link.</p><p><a href="https://github.com/snapp-incubator/charlie">GitHub - snapp-incubator/charlie: Docker image for executing python script directly from repository.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6167135d5d8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Containers in Golang (NATS)]]></title>
            <link>https://amirhossein-najafizadeh.medium.com/test-containers-in-golang-nats-1e1c60e7823f?source=rss-d0576542d783------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1c60e7823f</guid>
            <dc:creator><![CDATA[Amir Hossein Najafi Zadeh]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 11:09:37 GMT</pubDate>
            <atom:updated>2022-11-20T11:09:37.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Test-containers in Go is a Go package that makes it simple to create and clean up container-based dependencies for automated <em>integration/smoke</em> tests.</p><p>We use <em>test-containers</em> to run our dependent services like databases in a container hence we won’t need to mock them or use real external services. This makes our uint tests more efficient and more reliable.</p><p>The clean, easy-to-use API enables developers to programmatically define containers that should be run as part of a test and clean up those resources when the test is done.</p><h3>Nats example</h3><p>In the following example, we are going to create a Nats container and test it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58cdb5cd4b4dd5a96e1f4439fca57460/href">https://medium.com/media/58cdb5cd4b4dd5a96e1f4439fca57460/href</a></iframe><p>The testcontainers.ContainerRequest describes how the Docker container will look.</p><ul><li>Image is the Docker image the container starts from.</li><li>ExposedPorts lists the ports to be exposed from the container.</li><li>Cmd is the commands that will be executed when container is set.</li><li>WaitingFor is a field you can use to validate when a container is ready. It is important to get this set because it helps to know when the container is ready to receive any traffic. In this case, we check for the logs we know come from Nats, telling us that it is ready to accept requests.</li></ul><p>When you use <strong>ExposedPorts</strong> you have to imagine yourself using docker run -p &lt;port&gt;. When you do so, dockerd maps the selected &lt;port&gt; from inside the container to a random one available on your host.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/682eaf274c5d05cc8b34042a4b325721/href">https://medium.com/media/682eaf274c5d05cc8b34042a4b325721/href</a></iframe><p>testcontainers.GenericContainer creates the container. In this example we are using Started: true. It means that the container function will wait for the container to be up and running. If you set the Start value to false it won&#39;t start, leaving to you the decision about when to start it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc39dd6324e98f3e279d352423f25848/href">https://medium.com/media/fc39dd6324e98f3e279d352423f25848/href</a></iframe><p>All the containers must be removed at some point, otherwise they will run until the host is overloaded. One of the ways we have to clean up is by deferring the terminated function: defer container.Terminate(ctx).</p><p>See the source code at my <a href="https://github.com/amirhnajafiz/testcontainers">Github repository</a>.</p><p>Thank you<br>Amirhossein Najafizade</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1c60e7823f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>