<?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 Hareesh Pallathoor on Medium]]></title>
        <description><![CDATA[Stories by Hareesh Pallathoor on Medium]]></description>
        <link>https://medium.com/@hareesh.pallathoor?source=rss-af3ebe11be5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wmACynpcMmitwBh8q9Ke5A.jpeg</url>
            <title>Stories by Hareesh Pallathoor on Medium</title>
            <link>https://medium.com/@hareesh.pallathoor?source=rss-af3ebe11be5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:38:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hareesh.pallathoor/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[Stop Guessing at Deploy Time: Contracts, Preflight, and Policy-as-Code for Multi-Container Config]]></title>
            <link>https://medium.com/@hareesh.pallathoor/stop-guessing-at-deploy-time-contracts-preflight-and-policy-as-code-for-multi-container-config-a312f83ccba5?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a312f83ccba5</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[telecommunication]]></category>
            <category><![CDATA[cloud-development]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 02:17:44 GMT</pubDate>
            <atom:updated>2026-10-14T02:17:44.708Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Subtitle:</strong> How we moved from scattered scripts to a single configuration plane that verifies schemas, pins digests, and runs module-owned Rego before anything starts.</p><p><em>Estimated read time: 7 minutes</em></p><blockquote><em>Preflight is not a lint pass on YAML. It is the moment the platform commits to exact bytes of contract and policy — and refuses to start until that commitment checks out.</em></blockquote><h3>The problem we were tired of</h3><p>In many telecom and edge stacks, “configuration” still means a patchwork: bootstrap files, per-process stores, control-channel heartbeats, and validation rules copied into three different codebases. A parameter changes in one place; a downstream container never hears about it until something misbehaves on the air interface.</p><p>We wanted one <strong>configuration plane</strong>: a single writer, <strong>namespaced subscribers</strong> (one namespace per module instance), and <strong>revisioned snapshots</strong> so a module can tell “this notice applies to me” from “I need a full refresh.” That architecture is a story for another post. Here we focus on what makes bring-up trustworthy: <strong>preflight</strong> and <strong>policy-as-code</strong>.</p><p>If a workload starts with the wrong PLMN shape, an out-of-range physical cell ID, or a calculated field that no longer matches its inputs, you want to know <strong>before</strong> the process binds sockets — not after operators stare at a red cell on a map.</p><h3>Three layers of validation (and only one uses OPA)</h3><p>A common mistake is throwing every rule into Rego. We split validation by <strong>who owns the rule</strong> and <strong>what kind of check it is</strong>:</p><p><strong>Wire / API shape</strong> — guards JSON messages on the config line. Use JSON Schema on the protocol.</p><p><strong>Owner document shape</strong> — guards the module’s requirement schema (fields, bindings, types). Validate against a JSON Schema <strong>platform contract</strong> at preflight.</p><p><strong>Semantic / domain rules</strong> — guards PLMN consistency, cell parameters, cross-field logic, and similar domain truth. Use inline min/max/pattern <strong>or</strong> <strong>Rego</strong> via Open Policy Agent (OPA).</p><p>The central service does <strong>not</strong> use OPA to validate JSON syntax or to prove that an owner schema document is well-formed. Those stay in JSON Schema land — fast, familiar, and easy to test in CI.</p><p>OPA enters when a <strong>module owner</strong> attaches a policy block to a field (or constraint) in their requirement schema. The platform discovers the bundle, verifies digests, runs opa check, caches the bundle, and later calls opa eval with a stable JSON <strong>input</strong> document at validation time.</p><blockquote><em>JSON Schema answers “is this document structurally allowed?” Rego answers “given what we know about the network, is this value actually sane?”</em></blockquote><h3>What preflight actually does</h3><p><strong>Preflight</strong> is a single pipeline that runs <strong>before</strong> value resolution and <strong>before</strong> we allow a module instance to join the bring-up path. Any stage can <strong>fail closed</strong>: no snapshot, no deploy, no “start anyway and fix in prod.”</p><p>Rough flow:</p><pre>Discover schema pin (from workload manifest)<br>    → Fetch schema bytes → verify SHA-256<br>    → Validate document against platform contract<br>    → Collect policy bundle pins (manifest + schema references)<br>    → Verify bundle manifest + per-file digests → opa check → cache<br>    → Resolve field values into the module namespace</pre><p>If fetch, digest, contract validation, or policy load fails, bring-up stops with a concrete error — not a silent fallback.</p><h3>What we mean by “preflight data”</h3><p><strong>Preflight data</strong> is not a mysterious cache of cluster secrets. It is the set of <strong>pinned artifacts</strong> and the <strong>outcomes</strong> that only exist after preflight succeeds:</p><ol><li><strong>Pinned owner schema</strong> — immutable JSON identified by schema_id, version, HTTPS (or lab file://) URL, and SHA-256 of the exact body. The document’s internal identity must match the pin.</li><li><strong>Pinned policy bundles</strong> — bundle.manifest.json listing each .rego file and its digest; bundle id/version must match the pin.</li><li><strong>Resolved configuration snapshot</strong> — field values bound from authoritative network config, integration catalog entries, user inputs, and calculated formulas — materialized into the module’s namespace only after the steps above pass.</li></ol><p>Until preflight completes, the platform treats the module as <strong>not contractually ready</strong>. That is the shift from “hope the container starts” to “we proved which contract version we are running.”</p><h3>Immutable pins: trust the bytes, not the URL</h3><p>URLs lie. Redirects, stale CDNs, and mistaken tags happen. Our pattern is:</p><ul><li>Publish <strong>exact bytes</strong> (owner schema JSON, policy bundle directory).</li><li>Record <strong>lowercase SHA-256</strong> on the workload manifest (config-schema-digest, config-policy-bundle-digest, etc.).</li><li>At preflight, <strong>fetch → hash → compare</strong>. Mismatch aborts.</li><li>Verify <strong>identity</strong>: schema_id / schema_version inside the file match the pin; same for bundle_id / bundle_version in the policy manifest.</li></ul><p>In production, module teams <strong>co-publish</strong> the owner schema with the container image (OCI/ORAS attach is a common pattern): same release artifact, same digest story. The central service reads pins from generated workload manifests; it does not guess schema versions from image tags alone.</p><p>Lab demos often use read-only file:// roots constrained to packaged directories so engineers get deterministic offline runs. The trust model is the same—only the transport differs.</p><h3>Policy-as-code: module owners ship rules; the platform enforces</h3><p><strong>Who writes Rego?</strong> The team that owns the AMF, radio cell, or UE control module — not the platform team encoding every 3GPP edge case in Elixir.</p><p><strong>Who runs OPA?</strong> The configuration plane, at two moments:</p><ol><li><strong>Preflight</strong> — opa check on the bundle so broken policy never lands in cache.</li><li><strong>Runtime validation</strong> — opa eval when a field with a policy attachment needs checking, including after edits.</li></ol><p>A minimal attachment in the owner schema looks like:</p><pre>{<br>  &quot;policy&quot;: {<br>    &quot;bundle_id&quot;: &quot;module.amf.validation&quot;,<br>    &quot;bundle_version&quot;: &quot;1.0.0&quot;,<br>    &quot;file&quot;: &quot;plmn_shape.rego&quot;,<br>    &quot;query&quot;: &quot;data.module.amf.plmn.violations&quot;,<br>    &quot;severity&quot;: &quot;warning&quot;<br>  }<br>}</pre><p>When policy is set on a validation object, inline pattern / min / max on that same object are <strong>not</strong> used for that attachment—the Rego bundle owns semantics for that field.</p><h3>The OPA input contract</h3><p>The config line protocol is <strong>not</strong> sent to OPA. The platform builds one JSON document per evaluation:</p><ul><li>component — namespace id, e.g. amf/1</li><li>path — store path for the field under test</li><li>entries — map of path to { &quot;value&quot;, &quot;pending&quot; }</li><li>rule — the validation attachment (ids, severity, policy ref)</li><li>dependencies — logical inputs the resolver already computed (e.g. MCC/MNC), not raw store paths</li></ul><p>Pending entries are skipped inside Rego so half-filled forms do not false-positive.</p><h3>OPA output → operator-visible validation</h3><p>Each policy returns a set of <strong>violations</strong>. The platform flattens them into a validation snapshot:</p><ul><li>result: pass, warning, or fail</li><li>failures: [{ &quot;rule&quot;, &quot;path&quot;, &quot;value&quot;, &quot;severity&quot;, ... }]</li></ul><p>Any failure with severity: &quot;fail&quot; fails the snapshot; warnings surface without blocking unless your operations policy says otherwise. On config change, subscribers can receive a <strong>notify</strong> with the same failure list—so editing PCI, a global synchronization channel number, or a calculated PLMN re-runs policy without a pod restart.</p><h3>Worked example: PLMN shape and formula consistency</h3><p>Public Land Mobile Network identifiers often appear as a calculated mcc:mnc string. Two classes of bugs matter:</p><ol><li><strong>Shape</strong> — not matching ^\d{3}:\d{2,3}$.</li><li><strong>Consistency</strong> — string looks fine but does not match the MCC/MNC the resolver pulled from authoritative config.</li></ol><p>Module Rego should use input.path (supplied by the platform from the owner binding), not hard-coded store paths—so the same policy survives path layout changes.</p><pre>package module.amf.plmn</pre><pre>import rego.v1</pre><pre>violations contains v if {<br>    input.path<br>    entry := input.entries[input.path]<br>    object.get(entry, &quot;pending&quot;, false) == false<br>    not regex.match(`^\d{3}:\d{2,3}$`, sprintf(&quot;%v&quot;, [entry.value]))<br>    v := {<br>        &quot;rule&quot;: &quot;plmn-shape&quot;,<br>        &quot;path&quot;: input.path,<br>        &quot;value&quot;: entry.value,<br>        &quot;severity&quot;: object.get(input.rule, &quot;severity&quot;, &quot;warning&quot;),<br>    }<br>}</pre><pre>violations contains v if {<br>    input.path<br>    input.dependencies.mcc<br>    input.dependencies.mnc<br>    entry := input.entries[input.path]<br>    object.get(entry, &quot;pending&quot;, false) == false<br>    formatted := sprintf(&quot;%v&quot;, [entry.value])<br>    regex.match(`^\d{3}:\d{2,3}$`, formatted)<br>    expected := sprintf(&quot;%v:%v&quot;, [input.dependencies.mcc, input.dependencies.mnc])<br>    formatted != expected<br>    v := {<br>        &quot;rule&quot;: &quot;plmn-formula&quot;,<br>        &quot;path&quot;: input.path,<br>        &quot;value&quot;: entry.value,<br>        &quot;severity&quot;: object.get(input.rule, &quot;severity&quot;, &quot;warning&quot;),<br>        &quot;expected&quot;: expected,<br>    }<br>}</pre><p>The same pattern extends to other domains: OAM cell lists (GSCN range, subcarrier spacing sets), PCI for a physical cell ID, and so on — each bundle pinned and versioned independently.</p><p><strong>Pragmatic split:</strong> simple numeric bounds (e.g. a pointer 0–255) stay as minimum / maximum on the owner schema and inline checks on validation snapshots. Not every rule deserves a .rego file.</p><h3>Try it on your laptop</h3><p>You do not need a cluster to feel the policy loop:</p><pre># Install OPA from https://www.openpolicyagent.org/docs/latest/#running-opa</pre><pre>opa check ./my-bundle/   # preflight-style compile check</pre><pre>opa eval -f json \<br>  -d plmn_shape.rego \<br>  -i plmn-bad-input.json \<br>  data.module.amf.plmn.violations</pre><p>Example plmn-bad-input.json:</p><pre>{<br>  &quot;component&quot;: &quot;amf/1&quot;,<br>  &quot;path&quot;: &quot;/calculated/plmn&quot;,<br>  &quot;entries&quot;: {<br>    &quot;/calculated/plmn&quot;: { &quot;value&quot;: &quot;bad&quot;, &quot;pending&quot;: false }<br>  },<br>  &quot;dependencies&quot;: { &quot;mcc&quot;: &quot;311&quot;, &quot;mnc&quot;: &quot;489&quot; },<br>  &quot;rule&quot;: { &quot;severity&quot;: &quot;warning&quot; }<br>}</pre><p>You should see a plmn-shape violation. Fix the value to 311:489 and the set goes empty—what the platform maps to result: &quot;pass&quot;.</p><h3>Lessons we would repeat</h3><ol><li><strong>Separate shape from semantics</strong> — JSON Schema for documents and protocol; Rego for domain rules owned by modules.</li><li><strong>Pin everything that defines behavior</strong> — schema bytes, bundle manifest, per-policy file digests; hashes, not tags alone.</li><li><strong>Fail closed at preflight</strong> — missing required values, digest mismatch, or opa check failure blocks bring-up.</li><li><strong>Re-validate on change</strong> — policy is not only a gate at t=0; validation snapshots should move with edits.</li><li><strong>Keep the platform thin</strong> — central code orchestrates fetch, cache, and eval; module teams ship bundles and test them in CI with opa check.</li></ol><h3>Closing thought</h3><p>Configuration management at cluster scale is as much about <strong>governance</strong> as about key-value storage. Preflight turns “we think this module speaks v2.0.0” into “we hashed v2.0.0 and refused to lie about it.” Policy-as-code turns “the AMF team’s PLMN rules” into artifacts they version, publish, and stand behind — while the platform stays a consistent enforcement layer.</p><p>That combination — contracts, pinned data, and module-owned policy — is how we stopped guessing at deploy time.</p><p><em>If you implement something similar, start with one field, one bundle, and one digest pin. Expand when preflight is boringly reliable.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a312f83ccba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deciding on Your Compute Architecture: A Guide for Architects]]></title>
            <link>https://medium.com/@hareesh.pallathoor/deciding-on-your-compute-architecture-a-guide-for-architects-d43fb5410169?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d43fb5410169</guid>
            <category><![CDATA[grace-hopper-superchip]]></category>
            <category><![CDATA[superchip]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 08:54:33 GMT</pubDate>
            <atom:updated>2026-07-20T08:54:33.424Z</atom:updated>
            <content:encoded><![CDATA[<h4>How unified memory, NUMA topology, and interconnect bandwidth should shape your AI and HPC platform decisions tags: [software architecture, HPC, AI, GPU, NVIDIA, Grace Hopper, CUDA, superchip]</h4><p>As the demands of modern computing evolve, particularly in the realms of Artificial Intelligence (AI) and High-Performance Computing (HPC), architects face a critical decision: should you stick with the traditional, discrete CPU + GPU model, or embrace the newer, integrated “superchip” architecture?</p><p>This decision impacts far more than hardware procurement. It shapes system configuration, software development practices, performance management strategies, and long-term scalability. The sections below walk through both architectures, the trade-offs that matter most, and a framework for choosing the right path for your workloads.</p><h3>Understanding the Core Architectures</h3><p>Two dominant models define accelerated computing today. Understanding how they move data — and who is responsible for managing that movement — is the foundation for every decision that follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgQFPLrUj9RXwhn7g4IwSA.png" /></figure><h3>The Traditional Model: Discrete CPU + GPU</h3><p>For decades, the standard for accelerated computing has been a system featuring a Central Processing Unit (CPU) for general-purpose, serial tasks, and a separate, discrete Graphics Processing Unit (GPU) for massively parallel computations.</p><p><strong>Communication:</strong> The CPU and GPU are typically installed on a motherboard and communicate over the PCI Express (PCIe) bus. In multi-socket servers, CPUs communicate with each other over slower inter-socket interconnects like Intel’s QuickPath Interconnect (QPI) or Ultra Path Interconnect (UPI).</p><p><strong>Memory:</strong> This setup involves two distinct memory pools: the main system memory (RAM) used by the CPU, and the GPU’s dedicated high-bandwidth memory (HBM). Data must be explicitly copied between these two memory spaces for the GPU to work on it, and for the CPU to retrieve the results.</p><p><strong>Latency mitigation techniques:</strong> To overcome the inherent latency of the PCIe bus, developers must employ sophisticated software patterns like double-buffering. This involves using CUDA streams to overlap asynchronous data transfers (cudaMemcpyAsync) with kernel execution, effectively hiding the data movement time by keeping the GPU busy.</p><p>For distributed workloads, GPU Direct RDMA is a critical technology that allows a GPU to send and receive data directly from a Network Interface Card (NIC), bypassing the CPU and system memory to reduce latency and CPU overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WCI9u3oib8R0qg-swFitw.png" /></figure><h3>The Integrated Model: The Superchip</h3><p>A superchip, like the NVIDIA GH200 Grace Hopper Superchip, represents a paradigm shift by integrating a CPU and a GPU onto a single module. This design fundamentally rethinks the relationship between these two processors.</p><p><strong>Communication:</strong> Instead of a relatively slow PCIe bus, the CPU and GPU are connected by an ultra-fast, high-bandwidth, low-latency interconnect. NVIDIA’s NVLink-C2C (Chip-to-Chip) interconnect provides up to 900 GB/s of bidirectional bandwidth — 7 times faster than PCIe Gen5 — at a fraction of the power consumption.</p><p><strong>Memory:</strong> Superchips feature a unified, hardware-coherent memory architecture. Both the CPU and GPU share a single address space, and the hardware automatically ensures both processors have a consistent view of memory. The GPU can seamlessly access data regardless of its physical location, whether it’s in the CPU’s LPDDR5X memory or the GPU’s HBM. This allows them to access the same pool of memory without manual data copying, rendering latency-hiding patterns like double-buffering largely obsolete for on-chip communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*3UseO7aa9Z2EiyAo7aPWCA.png" /></figure><h3>Key Decision Factors for Architects</h3><p>The choice between these two architectures is not just about raw performance. It involves a trade-off across several critical factors.</p><h4>1. Performance, Bottlenecks, and Data Locality</h4><p>The primary performance constraint in this model is not just the PCIe bus, but the entire system’s Non-Uniform Memory Access (NUMA) topology. In a multi-socket server, each CPU and its local memory form a NUMA node. Accessing memory on a remote node is significantly slower.</p><p>Since GPUs are physically attached to a specific CPU’s PCIe root complex (PCIe affinity), a mismatch can be catastrophic for performance. If a CPU process on one socket tries to feed data to a GPU attached to another socket, the data must traverse the slow inter-socket link, creating a major bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ii3gFgIAn2U8NPT1Xj_vFQ.png" /></figure><p>To mitigate this, architects must perform meticulous, hands-on configuration:</p><ul><li><strong>Topology discovery:</strong> Use tools like lstopo-no-graphics and nvidia-smi topo -m to visualize the system topology and identify which NUMA node each GPU and NIC is attached to.</li><li><strong>Process and memory pinning:</strong> Employ the numactl utility to enforce data locality by pinning an application&#39;s CPU threads and memory allocations to the specific NUMA node that is physically connected to the target GPU.</li></ul><p><strong>Superchip: Eliminating the Bottleneck</strong></p><p>Superchips are engineered specifically to solve this problem. By fusing the CPU and GPU with a high-speed, cache-coherent interconnect like NVLink-C2C, the concept of remote CPU memory access is largely eliminated.</p><p>The NVIDIA Scalable Coherency Fabric (SCF), a mesh fabric and distributed cache, helps manage this data flow at extremely high bandwidths. This drastically reduces data transfer latency, making the architecture ideal for workloads where the CPU and GPU collaborate closely on the same data.</p><h4>2. Memory Architecture and Data Handling</h4><p>The separate memory pools necessitate a complex programming model where developers must explicitly manage memory. This involves allocating space on both the CPU and GPU, often using “pinned” memory (cudaMallocHost) to enable asynchronous transfers, and orchestrating data movement with cudaMemcpyAsync within a double-buffering pattern to hide latency.</p><p>The size of the GPU’s HBM is a hard limit, and exceeding it requires complex “out-of-core” computation that severely degrades performance.</p><p><strong>Superchip: Automated and Coherent Unified Memory</strong></p><p>The hardware-coherent unified memory model is a game-changer. It provides a single, large memory pool accessible to both processors, such as the up to 624 GB of fast-access memory available to the GPU in a GH200 Superchip. This allows for processing massive datasets that would be impossible to fit into discrete HBM by “oversubscribing” the GPU memory and spilling into the CPU’s larger LPDDR5X pool.</p><p><strong>Automated data migration:</strong> The CUDA runtime employs a “first-touch” policy, where data is initially placed in the memory of the processor that first accesses it. To optimize beyond that, Grace Hopper systems (with CUDA Toolkit 12.4 and later) use a sophisticated access-counter-based migration policy. This system uses hardware access counters to monitor the “hotness” of memory pages. When accesses from a processor to a page in remote memory exceed a certain threshold, the CUDA driver proactively migrates the “hot” page to the physical memory of the accessing processor, enhancing data locality automatically.</p><p><strong>Unified Virtual Addressing:</strong> Grace Hopper supports Address Translation Services (ATS), which allows the CPU and GPU to share a single page table. This means even memory allocated with standard system calls like malloc is accessible to the GPU, often eliminating the need for cudaMallocManaged and allowing third-party libraries to work seamlessly.</p><p><strong>Hardware-accelerated atomics:</strong> The NVLink-C2C interconnect enables hardware-coherent memory and provides native support for system-wide atomic operations. The Grace CPU’s Arm Large System Extensions (LSE) and the Hopper GPU’s enhanced capabilities are accelerated by the interconnect, enabling fine-grained, low-latency synchronization between CPU and GPU threads. This is critical for tightly-coupled algorithms that require efficient locking and data sharing.</p><p><strong>Architectural caveats:</strong> For automated migration to work with standard malloc calls, the system&#39;s page size must be configured to 64KiB. Furthermore, while the GPU&#39;s L1 cache is coherent with CPU memory, the GPU&#39;s L2 cache is not. Data residing in CPU memory can be cached in L1 but not L2—a critical consideration for performance tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd1Hrl4l_968YJW8jJh21Q.png" /></figure><h4>3. Development, Programming, and Performance Profiling</h4><h4><strong>Traditional CPU + GPU</strong></h4><p>This is a mature ecosystem, but it requires developers to be experts in memory management and system topology. They must be proficient with CUDA, implementing latency-hiding patterns like double-buffering, and using NUMA optimization tools to achieve peak performance.</p><h4>Superchip: Simplified Model with New Performance Challenges</h4><p>The unified memory architecture, enabled by the -gpu=unified compiler flag, significantly simplifies initial development by abstracting away manual memory copies. However, this abstraction introduces a new set of potential bottlenecks.</p><p><strong>New bottlenecks to monitor:</strong></p><ul><li><strong>Memory thrashing:</strong> The primary risk is “thrashing,” where the automated system repeatedly moves a page back and forth between CPU and GPU memory if both access it frequently, creating a “ping-pong” scenario.</li><li><strong>On-demand page faulting:</strong> Relying purely on page faults for migration can cause high latency, as pages are moved individually upon access.</li><li><strong>Poor GPU cache utilization:</strong> Data in CPU memory is not cached in the GPU’s L2, which can impact kernels that rely heavily on L2 for performance.</li><li><strong>NVLink-C2C interconnect contention:</strong> While the 900 GB/s bandwidth is massive, it is a finite resource that can become a bottleneck if an application generates extreme cross-chip traffic.</li></ul><p><strong>Essential profiling and debugging tools:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*FV_awLP-nhnexDIq1GZyDA.png" /></figure><p><strong>Expert overrides:</strong> When automated heuristics are suboptimal, developers can exert control:</p><ul><li>cudaMemAdvise<strong>:</strong> Provides hints to the runtime, such as setting a preferred location (cudaMemAdviseSetPreferredLocation) or advising that memory is read-only (cudaMemAdviseSetReadMostly) to help the system make better placement decisions.</li><li>cudaMemPrefetchAsync<strong>:</strong> The preferred method for bulk data migration on Grace Hopper. It allows a developer to explicitly and asynchronously move data to a processor&#39;s memory before it&#39;s needed, hiding latency and avoiding the high cost of on-demand page faulting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxQEsoSgSwzNPW8mPlfiaQ.png" /></figure><h3>4. Power Consumption and Energy Efficiency</h3><p><strong>Traditional CPU + GPU:</strong> A system with discrete components generally has a higher power draw. Each component requires its own power, and moving data across PCIe and inter-socket interconnects is an energy-intensive operation.</p><p><strong>Superchip:</strong> Integration leads to greater efficiency. The NVLink-C2C interconnect provides its massive bandwidth boost at a fraction of the power of PCIe Gen5. By minimizing data movement distance and using energy-efficient CPUs like the Arm-based NVIDIA Grace, superchips reduce overall energy consumption, making them a more efficient solution for large-scale deployments.</p><h3>5. Scalability</h3><h4>Traditional CPU + GPU</h4><p>Scaling within a server (scale-up) is limited by PCIe lanes and physical space. Scaling across servers (scale-out) relies on standard networking like InfiniBand, which requires technologies like GPU Direct RDMA to enable efficient node-to-node communication by bypassing system memory.</p><h4>Superchip</h4><p>Superchips are designed for massive, tightly-coupled scalability. The NVIDIA NVLink Switch System uses a two-level, non-blocking, fat-tree network topology to connect up to 256 Grace Hopper Superchips.</p><p><strong>A single, massive GPU:</strong> This architecture allows all 256 GPUs to function as a single entity with a shared, coherent memory space of up to 144 terabytes.</p><p><strong>Simplified programming:</strong> Developers can move away from complex Message Passing Interface (MPI) paradigms and adopt a simpler, shared-memory model, using basic pointer load, store, and atomic operations across the entire 256-GPU system. Communication libraries like NCCL and NVSHMEM can transparently leverage this fabric.</p><p><strong>Architectural consideration:</strong> The NVLink Switch System is a dedicated GPU network, separate from the standard Ethernet/InfiniBand network used for storage and external access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGpQ6oh7l2Av5WWqvoiOtw.png" /></figure><h3>6. Total Cost of Ownership (TCO)</h3><p><strong>Traditional CPU + GPU:</strong> The initial acquisition cost can be lower, and this model offers flexibility in component choice and incremental upgrades. This is attractive for projects with tighter initial budgets.</p><p><strong>Superchip:</strong> Superchips typically represent a higher upfront investment. However, their superior energy efficiency, density, and simplified management can lead to a lower Total Cost of Ownership (TCO) through reduced operational and software development costs.</p><ul><li><strong>Reduced development time:</strong> The abstraction of memory management reduces the cognitive load on developers, allowing them to focus on algorithms rather than data transfer mechanics. This accelerates development and simplifies porting of existing code.</li><li><strong>Simplified debugging and maintenance:</strong> With a single address space, common and difficult-to-debug memory management errors are largely eliminated. This results in cleaner, more readable, and more maintainable code that is more portable to future hardware generations.</li></ul><h3>Use Case Analysis: Which Architecture Is Right for You?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5Od-0Li1bWH_56hRnsHpQ.png" /></figure><h3>Choose a Traditional CPU + GPU Architecture when:</h3><ul><li><strong>Workloads are not bottlenecked by CPU-GPU communication.</strong> Applications where the GPU works on a dataset for a long time with minimal CPU interaction.</li><li><strong>You have deep optimization expertise.</strong> Your team is comfortable with the tools and techniques (numactl, double-buffering, GPU Direct RDMA) required to manage data locality and hide latency in discrete, distributed systems.</li><li><strong>Budget is constrained.</strong> The project requires a lower initial investment, and the ability to perform incremental upgrades is valuable.</li><li><strong>You are running legacy applications.</strong> Existing software is already heavily optimized for a discrete GPU and MPI-based environment, and rewriting it is not feasible.</li></ul><h3>Choose a Superchip Architecture when:</h3><ul><li><strong>You are running large-scale AI and HPC workloads.</strong> This includes training massive language models, complex scientific simulations, and graph analytics that benefit from tight CPU-GPU coupling and fine-grained synchronization.</li><li><strong>Your datasets are enormous.</strong> The application needs to handle datasets larger than the HBM available on even the biggest discrete GPUs, leveraging the massive unified memory.</li><li><strong>Developer productivity and a simplified programming model are key.</strong> You want to accelerate development by abstracting away the complexities of manual memory management, but are prepared to learn new profiling methodologies to optimize for the unified memory environment.</li><li><strong>Power efficiency and TCO are critical.</strong> You are designing for a large data center where power, cooling, and space are major cost drivers.</li><li><strong>You need to scale to hundreds of tightly-coupled GPUs.</strong> Your goal is to solve problems that require a massive, shared-memory programming model across a large number of GPUs, treating them as a single computational unit.</li></ul><h3>Summary</h3><p>The decision between a traditional CPU + GPU setup and a superchip is a strategic one that hinges on the specific demands of your workload, your team’s expertise, and your long-term goals.</p><p><strong>The traditional CPU + GPU architecture</strong> remains a viable and flexible option. However, achieving optimal performance requires significant architectural and developer effort. Architects must actively manage the system’s NUMA topology and PCIe affinity. Developers must implement complex software patterns to hide PCIe latency and leverage technologies like GPU Direct RDMA for efficient scaling. This approach places a heavy burden on the team to be topology-aware and expert optimizers.</p><p><strong>The superchip architecture</strong>, exemplified by NVIDIA’s Grace Hopper, represents the future for the most demanding AI and HPC tasks. By eliminating the PCIe bottleneck with a 900 GB/s, hardware-coherent NVLink-C2C interconnect, it unlocks new levels of performance. Its massive unified memory pool and automated, access-counter-based data migration dramatically simplify the programming model for large-dataset problems, reducing development time and TCO.</p><p>However, this simplification introduces new performance challenges. Architects and developers must shift their focus from managing cudaMemcpy to diagnosing issues like memory thrashing using a new suite of tools, including NVIDIA Nsight Systems and Linaro DDT/MAP. While the system is automated, peak performance may require expert overrides using APIs like cudaMemAdvise and cudaMemPrefetchAsync to guide the runtime.</p><p>When scaled with the NVLink Switch System, the superchip creates a single, massive GPU accessible via a simplified shared-memory programming model — a paradigm shift from traditional MPI-based coding. For the most challenging problems of today and tomorrow, the superchip offers a powerful, integrated, and efficient path forward that reduces management complexity while boosting performance and scalability, provided architects are prepared to embrace a new approach to performance analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43fb5410169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs. gRPC vs. WebSocket: Choosing the Right Protocol for a Distributed System]]></title>
            <link>https://medium.com/@hareesh.pallathoor/rest-vs-grpc-vs-websocket-choosing-the-right-protocol-for-a-distributed-system-4a32f5f013c9?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a32f5f013c9</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 03:22:57 GMT</pubDate>
            <atom:updated>2026-07-07T03:29:28.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*om7MBv3ZmLvvPhTkjpHfnA.png" /></figure><p><em>How to architect a scalable, performant system by combining three communication protocols strategically.</em></p><h3>The Problem: Too Many Choices</h3><p>Imagine you’re building a real-time monitoring platform that needs to:</p><ul><li>Display live dashboards in browsers (100+ concurrent users).</li><li>Stream telemetry from thousands of IoT sensors.</li><li>Coordinate between backend microservices (analytics, storage, alerting).</li><li>Handle sudden spikes in data volume without breaking a sweat.</li></ul><p>When you look at your protocol options, you’re faced with a dilemma:</p><ul><li>REST API: Simple and ubiquitous, but polling is inefficient.</li><li>WebSocket: Great for real-time, but connection-heavy for servers.</li><li>gRPC: Blazing fast and high-performance, but browsers can’t connect natively.</li></ul><p>Question: Should you just pick one and force it to work?<br>Answer: No. The hybrid approach wins. Here’s why and how to build it.</p><h3>The Architecture We’ll Build</h3><p>Instead of choosing a single protocol, we will assign each protocol the job it does best:</p><pre>┌──────────────────────┐<br>│   Browser Dashboard  │<br>│  (HTTP/JSON/WebSocket)<br>└──────────┬───────────┘<br>           │<br>      ┌────▼────────────┐<br>      │   FastAPI (REST)│  ← Northbound: UI-facing<br>      │   :8000         │      (stateless, scalable)<br>      └────┬────────────┘<br>           │ (gRPC clients)<br>      ┌────▼──────────────────────────┐<br>      │  gRPC Backend (HTTP/2)        │  ← East-West: Backend services<br>      │  :50051                       │      (high-performance)<br>      │  ┌─────────┬───────┬─────┐    │<br>      │  │Analytics│Storage│Alert│    │<br>      │  └─────────┴───────┴─────┘    │<br>      └───────────────────────────────┘</pre><ul><li>Northbound (UI → API): REST + WebSocket</li><li>East-West (Backend ↔ Backend): gRPC</li></ul><p>Result: A system that is 3–5x more efficient than relying on a single protocol everywhere.</p><h3>Why REST for User-Facing APIs?</h3><p>Your 100 browser users need to fetch current metrics, check system health, trigger alerts, and update configurations.</p><h4>Advantages</h4><ul><li>Stateless by Design: Each request is independent. Any server instance can handle any request, making horizontal scaling behind a load balancer trivial.</li><li>Browser Native: It just works out of the box.</li></ul><pre>// JavaScript: Native and simple<br>const data = await fetch(&#39;/api/metrics&#39;).then(r =&gt; r.json());</pre><ul><li>Caching is Built-in: Browser caches, CDNs, and corporate proxies natively understand HTTP headers like 304 Not Modified.</li><li>Standardized Tooling: OpenAPI/Swagger auto-generates docs, everyone understands HTTP status codes, and debugging via browser DevTools or Postman is seamless.</li></ul><h4>Disadvantages</h4><ul><li>Polling is Inefficient: If you use REST for live updates, you are wasting resources.</li></ul><pre># Browser-side polling (wasteful)<br>while True:<br>    metrics = await fetch(&#39;/api/metrics&#39;)  # HTTP request #1<br>    # 100 users × 10 requests/sec = 1,000 requests/sec <br>    await sleep(0.1)</pre><ul><li>High Overhead: Every request carries full HTTP overhead (headers, TCP handshake, TLS handshake).</li></ul><p>Verdict: REST is perfect for request/response cycles (control commands, config changes). For streaming updates, we need something else.</p><h3>Why gRPC for Backend Microservices?</h3><p>Your backend has a Metrics Processor, an Analytics Engine, and an Alert System. They must call each other simultaneously, push high-frequency updates (thousands of messages per second), and maintain strict API contracts.</p><h4>Advantages</h4><ul><li>Multiplexing over One Connection: Unlike standard HTTP/1.1 where multiple requests require multiple TCP connections, gRPC uses HTTP/2. All services communicate over a single, multiplexed connection.</li></ul><pre># gRPC: Multiple concurrent calls on 1 connection<br>async with grpc.aio.secure_channel(&#39;analytics:50051&#39;) as channel:<br>    stub = AnalyticsServiceStub(channel)<br>    <br>    # Overlapping calls multiplexed on the same connection<br>    trend = await stub.GetTrend(request1)        <br>    alert_config = await stub.GetAlertConfig()   <br>    metrics = stub.StreamMetrics(request3)</pre><ul><li>Binary Serialization (Protobuf): Protobufs are 6–7x smaller than JSON. At 10,000 sensor readings/sec, JSON takes ~1 MB/sec of bandwidth. Protobuf takes ~150 KB/sec. Furthermore, deserializing Protobuf uses a fraction of the CPU cycles compared to parsing JSON.</li><li>Schema Contracts Prevent Drift: If a service changes its message format, the code simply won’t compile until the consumer handles the new field. No more runtime errors due to missing JSON keys.</li><li>HTTP/2 Flow Control: Built-in flow control ensures that neither service gets starved under heavy load (no head-of-line blocking).</li></ul><h4>Disadvantages</h4><ul><li>Browsers Can’t Speak It Natively: Browsers don’t support HTTP/2 frame-level manipulation. You’d need gRPC-Web and an Envoy Proxy, adding complexity.</li><li>Steeper Learning Curve: .proto files, code generation, and async stream handling take time to learn.</li></ul><p>Verdict: gRPC is unmatched for the backend. High throughput, low latency, type-safe, and multiplexed.</p><h3>Why WebSocket for Real-Time Browser Updates?</h3><p>Your dashboard shows live telemetry that changes every second. Polling is out of the question. WebSocket keeps a persistent connection open, eliminating the overhead of establishing new connections.</p><h4>Advantages</h4><ul><li>Server Push (No Polling): The server pushes data to the UI only when it changes.</li></ul><pre>const ws = new WebSocket(&#39;wss://api.example.com/metrics&#39;);<br>ws.onmessage = (event) =&gt; {<br>    const metrics = JSON.parse(event.data);<br>    updateDashboard(metrics);  // React immediately<br>};</pre><ul><li>Bidirectional &amp; Low Latency: Updates arrive in &lt;10ms because the connection is already established, bypassing TCP/TLS handshakes.</li></ul><h4>Disadvantages</h4><ul><li>Connection Overhead: 10,000 concurrent users = 10,000 open connections in memory.</li><li>State Complexity: If a user disconnects or Server A goes down, handling reconnections and tracking session states becomes incredibly complex compared to stateless REST.</li></ul><p>Verdict: Use WebSocket strictly to push telemetry streams to the UI. Keep REST for control commands.</p><h3>The Comparison: Which Protocol Wins?</h3><p>Let’s look at a scenario: “Send 10,000 Sensor Readings to 3 Backend Services”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Mc91h01bHp_1SkrX4rFM3w.png" /></figure><h3>The Hybrid Architecture: REST + gRPC + WebSocket</h3><p>Here is how you wire them together gracefully.</p><h3>How It Works</h3><p>1. User updates a configuration (REST → gRPC → WebSocket)</p><ul><li>Browser sends POST /api/config (REST).</li><li>FastAPI receives the stateless request.</li><li>FastAPI calls Analytics.UpdateThreshold() (gRPC).</li><li>Analytics Service updates its state and triggers an alert stream (gRPC).</li><li>FastAPI broadcasts the new state to all connected browsers (WebSocket).</li></ul><p>2. High-volume sensor readings arrive (gRPC → WebSocket)</p><ul><li>Sensor hits the Metrics Service.</li><li>Metrics Service calls Analytics.RecordReading() and Storage.SaveReading() (gRPC, multiplexed).</li><li>If a threshold is crossed, the Alert Service notifies FastAPI (gRPC).</li><li>FastAPI pushes the alert to the browsers (WebSocket).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a32f5f013c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightweight IoT Configuration Planes with ZeroMQ]]></title>
            <link>https://medium.com/@hareesh.pallathoor/lightweight-iot-configuration-planes-with-zeromq-fb0f48671a6c?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb0f48671a6c</guid>
            <category><![CDATA[zeromq]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[telecommunication]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 04:10:35 GMT</pubDate>
            <atom:updated>2026-06-22T04:10:35.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Distributed Internet of Things (IoT) ecosystems require moving authoritative operational states from a centralized cloud controller to a fleet of thousands of edge gateways. This must happen under severe production constraints: constrained network bandwidth over cellular links, frequent connection drops, strict processing deadlines, and explicit delivery guarantees.</p><p>When architects encounter these requirements, the typical reflex is to introduce a heavyweight message broker cluster (e.g., Apache Kafka, RabbitMQ) or a consensus-driven configuration store (e.g., Consul, etcd). While robust, these platforms introduce substantial operational surface area, consume valuable runtime memory on small devices, and create highly complex network failure domains.</p><p>An alternative architectural strategy uses <strong>ZeroMQ</strong> — not as a broker server, but as a stateless, embeddable messaging engine. By driving network topologies directly inside application runtimes and pairing them with strict <strong>version-driven snapshot discipline</strong>, you can engineer a resilient, highly scalable configuration plane with zero external dependencies.</p><h3>The Core Problem: State Synchronization at the Edge</h3><p>Consider an IoT gateway fleet managing industrial telemetry sensors. Each edge machine’s active behavior is entirely driven by a configuration schema detailing hardware sampling frequencies, local anomaly detection thresholds, and sensor calibration metrics.</p><p>If an engineer updates a threshold in the cloud, that delta must propagate down to target devices immediately. If an edge device reboots or suffers a network partition during that moment, it must instantly recover the correct, uncorrupted, up-to-date state without missing intermediate mutations or processing duplicate messages.</p><p>Achieving this requires addressing the fundamental trade-offs between two primary message topologies:</p><h4>The Limitations of Pure Push (Publish/Subscribe)</h4><p>A broad broadcast channel is highly efficient for fan-out, allowing the controller to distribute configuration updates to thousands of nodes simultaneously. However, ZeroMQ PUB/SUB sockets act as a live pipe, not a historical database. Late-joining or reconnecting edge nodes suffer from the <strong>Slow Joiner Problem</strong>—they miss all configuration history emitted before their connection fully stabilized.</p><h4>The Limitations of Pure Pull (Request/Reply)</h4><p>A synchronous, lock-step query allows edge nodes to intentionally fetch the latest state on boot. However, relies purely on a polling schedule. If thousands of nodes simultaneously hammer the central server for large configuration payloads, the controller will saturate its network interfaces and compute resources.</p><h3>Architectural Foundations: Data Primitives</h3><p>Because ZeroMQ purposefully strips out server-side state tracking, the responsibility for data consistency shifts entirely to your application architecture. We enforce this consistency using three core primitives:</p><pre>┌──────────────────────────────────────────────────────────────────────────┐<br>│                           THE CONFIGURATION MATRIX                       │<br>├──────────────────────────────────────────────────────────────────────────┤<br>│ 1. Monotonic Version : [ V104 ] -&gt; Strict linear logical clock           │<br>├──────────────────────────────────────────────────────────────────────────┤<br>│ 2. State Snapshot    : { complete_materialized_schema_at_v104 }          │<br>├──────────────────────────────────────────────────────────────────────────┤<br>│ 3. Idempotent Delta  : { patch: V104 -&gt; V105, &quot;sampling_rate&quot;: 25 }      │<br>└──────────────────────────────────────────────────────────────────────────┘</pre><h4>1. The Monotonic Version</h4><p>Every single update made to the configuration plane must be stamped with a strictly increasing, linear sequence counter ($V_1, V_2, \dots V_n$). This integer functions as a logical clock. It allows resource-constrained edge processors to evaluate state changes using simple inequality operations. If a node is at version 45 and receives a message marked version 48, it immediately identifies that exactly two configuration steps were lost in transit.</p><h4>2. The State Snapshot</h4><p>A snapshot is the fully evaluated, complete materialized view of the entire configuration matrix at a precise version index. It contains everything needed for an edge device to execute a cold boot without reading past historical logs.</p><h4>3. The Idempotent Delta</h4><p>To prevent saturating cellular links with massive snapshot distributions, the controller broadcasts lightweight patches (e.g., JSON patches) for day-to-day changes. Crucially, these deltas must be structurally <strong>idempotent</strong>. Applying the exact same delta patch multiple times to a local state must yield the exact same resulting version, safeguarding the device against network-level retries and duplicate frame delivery.</p><h3>The Hybrid State Pattern: Mechanics of the Flow</h3><p>To build a flawless system, we fuse the strengths of both models: <strong>Request/Reply channels are isolated for structural snapshot synchronization, and Publish/Subscribe channels are dedicated to live delta propagation.</strong></p><p>The Step-by-Step Topology Flow</p><pre>                     +───────────────────────────────────────+<br>                     |         Central Control Plane         |<br>                     +───────────────────────────────────────+<br>                        ▲                            │<br>                        │ 1. REP Socket              │ 2. PUB Socket<br>                        │    (Snapshot Server)       │    (Delta Stream)<br>                        │                            │<br>      Phase 1: Pull     │                            │ Phase 2: Push<br>      Full Baseline     │                            │ Stream Live Deltas<br>      on Boot/Reconnect │                            │<br>                        │                            ▼<br>                     +──┴────────────────────────────┴───────+<br>                     |              Edge Gateway             |<br>                     +───────────────────────────────────────+</pre><p>When an IoT node goes live or recovers from an extended network partition, it executes a strict, two-phase synchronization lifecycle:</p><h4>Phase 1: Establish the Baseline (Synchronous Pull)</h4><ol><li>The client opens a ZeroMQ REQ socket and transmits a get_snapshot command to the central REP socket.</li><li>The server grabs the latest version from its thread-safe memory state and replies with the complete payload: [config_version: 104, snapshot: {...}].</li><li>The client writes this baseline configuration to its local engine and initializes its local tracking pointer to 104.</li><li>The client immediately closes or leaves the REQ socket dormant to eliminate connection overhead.</li></ol><h4>Phase 2: Consume the Stream (Asynchronous Push)</h4><ol><li>The client connects a ZeroMQ SUB socket to the live broadcast channel and subscribes to the configuration topic.</li><li>The live ingest loop begins evaluating incoming delta messages.</li><li><strong>Condition A (Stale Data):</strong> If an incoming message version is less than or equal to the local tracking pointer (inbound_version &lt;= 104), it is immediately discarded. This safely handles duplicate messages and overlapping streams.</li><li><strong>Condition B (Valid Progression):</strong> If the version matches the next expected increment (inbound_version == 105), the patch is applied atomically and the local pointer increments to 105.</li><li><strong>Condition C (Sequence Hole/Network Gap):</strong> If the incoming version skips a step (inbound_version == 108), the client recognizes a packet loss event. It immediately drops its live stream connection, opens its REQ socket, and triggers a full <strong>Phase 1 reset</strong> to re-baseline against the snapshot server.</li></ol><h3>System Resilience &amp; Edge Optimization Strategies</h3><p>To operate this hybrid architecture reliably at scale, the following system design patterns must be enforced:</p><ul><li><strong>Payload Decoupling:</strong> Do not route heavy binaries (like hardware firmware files or machine learning weights) directly over the ZeroMQ configuration wire. ZeroMQ should distribute small metadata manifests containing file signatures (SHA-256) and secure resource URLs (HTTPS/S3). The edge node then retrieves the asset out-of-band, preventing configuration stream blockages.</li><li><strong>Deadlock Mitigation via Non-Blocking Polling:</strong> ZeroMQ REQ sockets operate on a strict, lock-step state machine. If the central server suffers an outage right after an edge gateway sends a request, the client thread will block indefinitely. Architects must enforce aggressive receive and send timeouts (ZMQ_RCVTIMEO / ZMQ_SNDTIMEO) or encapsulate transactions inside an explicit non-blocking polling reactor (zmq.Poller) to maintain runtime control.</li><li><strong>Vertical Scaling with Stateless Intermediaries:</strong> When a fleet scales to tens of thousands of active nodes, managing raw TCP edge connections will overwhelm a centralized controller. Instead of adopting an enterprise broker, deploy stateless network intermediaries using ZeroMQ’s native zmq.proxy engine. These proxies run at the kernel level, shifting connection termination away from your core application logic without requiring complex, stateful cluster routing configuration.</li></ul><h3>Summary</h3><p>By taking responsibility for state versioning, payload idempotency, and snapshot reconciliation inside your application domain, ZeroMQ becomes a highly effective tool for distributed state architecture. Leveraging Request/Reply paths for structural baselines and Publish/Subscribe topologies for real-time adjustments delivers a highly resilient, low-latency configuration plane that easily outpaces the performance of typical enterprise messaging platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb0f48671a6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multihop SSH in Enterprise Automation: How Nested Reachability Is Built Without a Single Magic…]]></title>
            <link>https://medium.com/@hareesh.pallathoor/multihop-ssh-in-enterprise-automation-how-nested-reachability-is-built-without-a-single-magic-a3d3dca74a01?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3d3dca74a01</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openssh]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 04:17:57 GMT</pubDate>
            <atom:updated>2026-06-18T04:17:57.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multihop SSH in Enterprise Automation: How Nested Reachability Is Built Without a Single Magic Command</h3><p>In large-scale test labs, telco environments, and field deployments, embedded targets rarely offer a clean, routable path from an operator’s workstation. A radio unit might live deep within an isolated factory VLAN; a shelf controller might only speak to a specific rack gateway; or a second network hop might be mandatory just to get from a lab PC into a closed vendor shell.</p><p>Operations teams handle this manually every day using nested SSH: connect to jump host A, from A log into B, and from B finally access the target device.</p><p>But when you are building an automated testing or orchestration framework, you cannot rely on a human typing commands interactive-style. You have to implement this exact pattern <em>in-process</em>.</p><p>This article unpacks how enterprise automation stacks construct multi-tier reachability using explicit hop lists, TCP forwarding over existing SSH transports, and connection reuse. It is the exact same ingredient list OpenSSH uses for ProxyJump, but wired for programmatic, long-lived agents and dynamic discovery.</p><h3>Why “Multihop” Is Not One SSH Call</h3><p>Classical ssh user@target relies on a fundamental assumption: <strong>IP reachability and return routing</strong>. In embedded or secure lab environments, that assumption fails for three main reasons:</p><ul><li><strong>Invisible IP Space:</strong> The target device frequently holds a link-local or isolated private address completely invisible to the corporate network.</li><li><strong>Strict Firewalls:</strong> Security policies typically restrict incoming sessions, allowing only a designated lab gateway or jump box to initiate inward connections.</li><li><strong>Tiered Trust:</strong> Credentials and authentication methods vary wildly per tier — you might use corporate OAuth/SSO to hit the lab gateway, but require a static root password or local key on the target board.</li></ul><p>To bypass this, automation frameworks must implement a <strong>chain of transports</strong>. Instead of a single end-to-end network call, each hop is treated as a standard, independent SSH session. The TCP stream for the <em>next</em> hop is carried entirely inside the previous session as an encrypted byte tunnel.</p><p>After n hops, the outermost client holds an SSH channel whose raw payload is the innermost TCP connection to target:22. Only this final leg runs your actual shell commands or test scripts.</p><h3>The Portable Building Block: direct-tcpip over Paramiko</h3><p>While OpenSSH abstracts this complexity away using ProxyCommand or ProxyJump in a config file, programmatic automation requires interacting directly with the SSH subsystem. In Python, the standard library for this is <strong>Paramiko</strong>, which exposes the core primitive understood by any standard SSH daemon: direct-tcpip.</p><p>This channel type instructs the remote SSH server to dial a specific (host, port) from its own local network interface and stream those raw bytes back to the client over the encrypted tunnel.</p><h3>The Stacking Architecture</h3><ol><li><strong>Establish Hop 1:</strong> Connect client₁ to jump₁. This performs a full SSH handshake and creates an authenticated transport session.</li><li><strong>Open the Tunnel:</strong> On jump₁’s transport layer, call open_channel(&quot;direct-tcpip&quot;, dest_addr=(jump₂, 22), src_addr=(&quot;127.0.0.1&quot;, 0)).</li><li><strong>Encapsulate Hop 2:</strong> Pass the resulting socket-like channel object as the sock= argument into client₂.connect(...). client₂ behaves exactly as if it opened a standard TCP socket to jump₂—but every byte flows securely through jump₁.</li><li><strong>Repeat:</strong> Repeat this loop until the final client (clientₙ) targets the embedded leaf node.</li></ol><p>Each leg fully reuses the underlying SSH protocol end-to-end. You aren’t inventing a custom VPN; you are simply stacking standard SSH tunnels inside forwarded TCP channels.</p><blockquote><strong><em>Tip:</em></strong><em> The </em><em>open_channel step can block indefinitely if a downstream jump host attempts to connect to a black-hole or misconfigured address (such as scanning unassigned IPv6 slots). Production automation must enforce an explicit, aggressive timeout on </em><em>open_channel to ensure fleet-wide network discoveries fail fast rather than hanging on OS-level TCP timeouts.</em></blockquote><h3>Representing the Chain: Ordered Node Lists</h3><p>To manage this programmatically, modern automation stacks model every endpoint as an isolated Device object containing its IP, port, credentials, and key paths. Crucially, each target device includes a chain_node field: an ordered list of the intermediate Device instances required to reach it.</p><p>The connection loop is designed to be cleanly linear:</p><pre># Conceptual execution flow<br>tunnel = None<br>for proxy in device.chain_node:<br>    tunnel = connection_pool.connect(proxy, socket=tunnel)<br><br># The final client connects to the target through the completed tunnel<br>session = connection_pool.connect(<br>  target, <br>  socket=tunnel, <br>  scope_key=hop_signature<br>)</pre><p>If the chain_node list is empty, it defaults to a plain, direct network socket. If intermediate nodes exist, the loop iteratively accumulates tunnels, passing the output of the previous step as the transport layer for the next.</p><h3>Flattening Nested Topology to Avoid Recursion</h3><p>Real-world inventory systems are structural trees, not flat lists. For instance, a baseband unit might be reachable via [lab_pc, rack_gw]. If a testing engineer then wants to talk to a fronthaul optical module attached <em>to</em> that baseband, a naïve system might try to recursively resolve the parentage on the fly.</p><p>This introduces fragile, recursive code during network execution — a nightmare for debugging connection failures.</p><p>The more robust pattern is a <strong>flattening helper</strong>. When compiling inventory metadata, the system builds a fully expanded, left-to-right path for the leaf node before execution begins:</p><pre>chain_for_child = [ ...all proxies belonging to parent... , parent ]</pre><p>By ensuring that the child’s chain_node is a flat sequence, the network connector never has to dynamically figure out dependencies during a connection phase. It simply walks the array from left to right. This perfectly matches how network engineers reason about topology: <em>&quot;The same path we used yesterday, plus one more physical cable segment to the new board.&quot;</em></p><h3>Connection Pooling and Scope Keys</h3><p>Tearing down and spinning up full SSH sessions for every single command is incredibly expensive; key exchanges, authentication handshakes, and window size negotiations introduce massive latency. To make an automation runner viable at scale, a singleton connection pool is required.</p><p>The pool caches open transports using a unique lookup key composed of (user, host, port). However, in multihop setups, a standard key isn&#39;t enough. If two distinct target devices share an intermediate jump host, they cannot share the final channel.</p><p>To prevent cross-talk and collision, the framework generates a unique <strong>Scope Key</strong> derived from the exact path taken:</p><pre># Example Unique Scope Key<br>alice@10.0.0.1:22 -&gt; bob@192.168.5.2:22 -&gt; root@192.168.12.50:22</pre><p>This guarantees that while intermediate transport hops are shared and reused efficiently to save resources, the final-leg sockets remain securely isolated.</p><h3>Edge Cases and Operational Failures to Anticipate</h3><p>If you are building or maintaining an engine like this, expect to design around these common failure modes:</p><ul><li><strong>Half-Open Transports:</strong> SSH connections can silently drop due to aggressive firewalls or idle timeouts. Connection pools must validate transports using active keep-alive checks (like transport.is_active()) before handing them back to a worker thread, instantly recycling dead connections if the check fails.</li><li><strong>Channel Exhaustion:</strong> Smaller embedded jump boxes often have strict limits on maximum open channels (defined by MaxSessions or MaxStartups in sshd_config). Automation engines should cap maximum concurrency through a single jump box or execute commands sequentially across a single persistent channel.</li><li><strong>Asymmetric Routing Policies:</strong> Even if your SSH logic is perfect, corporate egress security policies may block an intermediate jump box from initiating an outbound TCP session to the next tier. Network infrastructure will always dictate what your software can actually reach.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3d3dca74a01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes RoCE Shared Memory: Architecting High-Throughput Inter-Process Communication]]></title>
            <link>https://medium.com/@hareesh.pallathoor/kubernetes-roce-shared-memory-architecting-high-throughput-inter-process-communication-21ed851a413a?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ed851a413a</guid>
            <category><![CDATA[roce]]></category>
            <category><![CDATA[rocev2]]></category>
            <category><![CDATA[rdma]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 08:35:36 GMT</pubDate>
            <atom:updated>2026-06-16T08:38:59.232Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Important note:</strong> This is an exploratory architecture article intended to discuss design patterns and implementation approaches. The concepts presented have not been validated through lab testing, benchmarking, or production deployment and should be treated as a technical exploration rather than performance guidance.</blockquote><p>For distributed workloads that require massive, tightly coupled state synchronization — such as distributed Machine Learning (LLM) training, real-time financial risk engines, and ultra-low-latency gRPC meshes — traditional Kubernetes networking introduces a significant performance bottleneck.</p><p>When data throughput scales to gigabytes per second, standard TCP/IP network layers spend excessive CPU cycles copying data between user and kernel spaces. To achieve bare-metal efficiency while maintaining the agility of cloud-native orchestration, system architects can leverage RDMA-backed remote memory architectures that expose memory across nodes with latency characteristics approaching local shared-memory access.</p><p>This article outlines how to implement a distributed memory-access fabric in Kubernetes using Remote Direct Memory Access over Converged Ethernet (RoCE v2), providing the foundational building blocks required to construct higher-level distributed shared-memory systems.</p><h3>The Root Problem: Why Standard Kubernetes Networking Fails High-Throughput Apps</h3><p>In a standard Kubernetes deployment, when Pod A communicates with Pod B over a standard CNI overlay network, data must traverse multiple layers:</p><ol><li><strong>User Space to Kernel Space:</strong> The application copies data to an OS socket buffer (sk_buff).</li><li><strong>Network Subsystem:</strong> The host OS processes the TCP/IP stack, adding protocol headers, managing window sizes, and handling routing.</li><li><strong>Virtual Interfaces:</strong> Packets travel through virtual ethernet pairs (veth), crossing the container network namespace boundary to the host bridge.</li><li><strong>Context Switching:</strong> Hardware interrupts force the CPU to switch context constantly to handle packet delivery.</li></ol><p>This process introduces microsecond-level serialization delays and severe CPU overhead. While negligible for standard microservices, it forms an invisible wall for high-throughput, low-latency architectures.</p><h3>Traditional Shared Memory Limitations</h3><p>To eliminate this network overhead within a single host, architects rely on <strong>POSIX Shared Memory (IPC)</strong>. By mapping a portion of the host’s RAM into the virtual address spaces of multiple containers, processes read and write to identical physical coordinates with zero copies and zero network overhead.</p><p>However, Kubernetes is inherently a distributed system. Standard shared-memory approaches fall short across multiple worker nodes:</p><ul><li><strong>Distributed Key-Value Stores (e.g., Redis):</strong> While excellent for state management, data must still be serialized (JSON/Protobuf), pushed over a network socket, and deserialized. The network stack remains a critical bottleneck.</li><li><strong>Host-Mapped POSIX Shared Memory (</strong><strong>/dev/shm via </strong><strong>hostPath):</strong> This is highly efficient if pods are co-located on the same host node. However, if the Kubernetes scheduler assigns pods to different physical nodes due to resource constraints, cross-node mapping is natively impossible.</li><li><strong>Network File Systems (NFS or NVMe-oF):</strong> Though storage area networks are highly optimized, they use file or block storage semantics. They add substantial filesystem layer overhead and are ill-suited to behave as high-speed, volatile IPC registers.</li></ul><h3>Resolving Cross-Node Latency with RoCE v2</h3><p><strong>RoCE v2 (RDMA over Converged Ethernet)</strong> extends the capabilities of local shared memory across distinct physical nodes. It allows a Network Interface Card (NIC) on Node 1 to directly access registered memory regions on Node 2 while bypassing the traditional kernel networking path and minimizing CPU involvement in data movement.</p><pre>+------------------------------------------------------------+<br>|                       RoCE v2 Fabric                       |<br>|                                                            |<br>|  +-----------------------+        +---------------------+  |<br>|  | Pod A (Worker Node 1) |        | Pod B (Worker Node 2|  |<br>|  +-----------+-----------+        +----------+----------+  |<br>|              |                               |             |<br>|        [User Space]                    [User Space]        |<br>|              |                               |             |<br>|       (Bypasses Kernel)               (Bypasses Kernel)    |<br>|              |                               |             |<br>|        +-----+-----+                    +----+-----+       |<br>|        | RoCE NIC  |=======(UDP/IP)====&gt;| RoCE NIC |       |<br>|        +-----------+                    +----------+       |<br>|              |                               |             |<br>|       [Direct Memory]                 [Direct Memory]      |<br>|              |                               |             |<br>|        +-----+-----+                    +----+-----+       |<br>|        | Host RAM  |                    | Host RAM |       |<br>|        +-----------+                    +----------+       |<br>+------------------------------------------------------------+</pre><p>By encapsulating standard RDMA transport packets into standard UDP/IP headers, RoCE v2 routes seamlessly across Layer 3 network boundaries at wire speed (e.g., 100Gbps to 400Gbps).</p><p>Because packetization and transport logic are largely offloaded to the NIC hardware, the CPU is removed from the critical data-transfer path after work requests are posted, significantly reducing CPU overhead compared with conventional TCP/IP communication. The application registers memory regions directly with the hardware, enabling low-latency remote memory operations that can be composed into higher-level distributed shared-memory abstractions.</p><h3>Architectural Implementation Plan in Kubernetes</h3><p>Deploying a RoCE v2 shared memory fabric inside a Kubernetes cluster requires deep integration across three structural layers: infrastructure, device orchestration, and application engineering.</p><h4>1. Underlying Network Topology</h4><p>RoCE v2 relies heavily on a <strong>Lossless Ethernet</strong> fabric. The physical spine-leaf network should be configured with RDMA-aware congestion-management mechanisms such as PFC, ECN, and vendor-specific controls (for example DCQCN in RoCE deployments) to minimize packet loss and maintain predictable RDMA performance.</p><h4>2. Device Plugin and Pod Provisioning</h4><p>To inject hardware-level RDMA capabilities directly into ephemeral containers, use the <strong>SR-IOV (Single Root I/O Virtualization) Network Device Plugin</strong> alongside <strong>Multus CNI</strong>. This permits a physical RoCE-enabled NIC to partition into several Virtual Functions (VFs), mapping a dedicated hardware interface straight into the pod’s namespace.</p><p>Furthermore, application memory must be pinned using Linux <strong>Hugepages</strong> to prevent the kernel from swapping out active RDMA-registered memory blocks.</p><p>Below is a production-grade manifest utilizing these configurations:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: roce-shared-memory-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: compute-engine<br>  template:<br>    metadata:<br>      labels:<br>        app: compute-engine<br>      annotations:<br>        k8s.v1.cni.cncf.io/networks: roce-sriov-network<br>    spec:<br>      containers:<br>      - name: compute-engine<br>        image: enterprise-mesh-app:latest<br>        resources:<br>          requests:<br>            intel.com/roce_sriov_vf: &quot;1&quot;<br>            hugepages-1Gi: &quot;4Gi&quot;<br>            memory: &quot;8Gi&quot;<br>            cpu: &quot;4&quot;<br>          limits:<br>            intel.com/roce_sriov_vf: &quot;1&quot;<br>            hugepages-1Gi: &quot;4Gi&quot;<br>            memory: &quot;8Gi&quot;<br>            cpu: &quot;4&quot;<br>        securityContext:<br>          capabilities:<br>            add: [&quot;IPC_LOCK&quot;] # Allows application to lock memory regions for RDMA</pre><h4>3. Application Execution Interface</h4><p>With the network fabric and hardware provisioned, the application interfaces with the physical NIC via user-space libraries like libibverbs or Unified Communication X (UCX):</p><ol><li><strong>Memory Registration (MR):</strong> The application allocates hugepage-backed memory segments and registers them with the local RoCE NIC.</li><li><strong>Control-Plane Exchange:</strong> Pod A and Pod B perform a lightweight, out-of-band handshake (via an internal gRPC service or etcd instance) to share their assigned memory keys (rkey) and base virtual addresses.</li><li><strong>RDMA Transactions:</strong> Using the exchanged security keys, Pod A initiates direct RDMA_WRITE or RDMA_READ operations directly across the cluster fabric.</li></ol><h3>Fault Tolerance and Pod Failure Handling</h3><p>In an ephemeral cloud-native ecosystem, pods fail frequently. Giving a pod direct memory access to a remote host introduces the risk of hardware hangs, dangling pointers, or data corruption if a target pod crashes during a memory write transaction.</p><p>Architecting a resilient recovery pattern requires mapping safety measures across the physical and logical layers:</p><h4>1. Hardware Isolation (Queue Pair Faults)</h4><p>RDMA connections communicate via isolated <strong>Queue Pairs (QP)</strong> containing Send and Receive queues.</p><p>If Pod B suffers a catastrophic failure, its container runtime environment instantly tears down its assigned Virtual Function (VF). The underlying local hardware interface immediately senses the drop in the connection status or the erasure of the virtual queue pair context. Following transport failure detection, the local NIC transitions the affected Queue Pair into an Error state (IBV_QPS_ERR), causing subsequent RDMA operations to fail safely and return completion errors to user space. Any subsequent memory writes issued by Pod A fail safely at the hardware layer, throwing an exception back to user space rather than polluting unmapped host RAM.</p><h4>2. State Flushing via Lifecycle Sidecars</h4><p>To bridge the time-gap between hardware state changes and Kubernetes control plane convergence, applications should utilize a highly privileged <strong>Resilience Sidecar</strong> within the pod.</p><pre>[ Pod Boundary ]<br>+-------------------------------------------------------+<br>|                                                       |<br>|  +------------------------+   Shared   +-----------+  |<br>|  |   Compute Container    |&lt;----------&gt;| Resilience|  |<br>|  |  (Active RDMA Engine)  |   Volume   |  Sidecar  |  |<br>|  +------------------------+            +-----+-----+  |<br>|                                              |        |<br>+----------------------------------------------|--------+<br>                                               v<br>                                      (Monitors Lifecycle)<br>                                               v<br>                                      +-----------------+<br>                                      | K8s API / etcd  |<br>                                      +-----------------+</pre><p>The sidecar shares an IPC namespace and volume with the main execution container, actively tracking its health parameters. When a termination event occurs, a Kubernetes preStop lifecycle hook is executed:</p><ol><li>The sidecar flags its regional memory blocks as <strong>Stale</strong> inside the central control plane registry.</li><li>The sidecar explicitly deregisters the memory blocks (ibv_dereg_mr) and closes active queue pairs cleanly, allowing remote nodes to gracefully pause ongoing data processing loops.</li><li>The sidecar does not replace application-level RDMA connection management. Instead, it serves as an orchestration bridge between Kubernetes lifecycle events and the application’s memory-control plane, allowing remote participants to discover stale registrations and initiate recovery workflows.</li></ol><h4>3. Application-Level Memory Transactions</h4><p>Architects should enforce transactional state models for memory operations, mimicking database design patterns.</p><p>Rather than writing directly into operational variables, Pod A writes into a designated staging buffer within the remote registered memory region. Once a chunk is delivered, Pod A executes an atomic operation (e.g., RDMA_ATOMIC_FETCH_AND_ADD) to adjust a completion tracking flag.</p><p>If a queue pair error triggers during the transaction, Pod A discards the uncommitted scratch memory area, reads the central control plane to discover Pod B’s newly rescheduled instance, binds to the new queue pair, and replays the interrupted transaction safely.</p><h3>Conclusion</h3><p>It is important to distinguish RDMA-based remote memory access from true distributed shared memory (DSM). RoCE v2 provides the transport mechanism that enables direct access to remote memory regions, but coherence, consistency, ownership, locking, and synchronization semantics must still be implemented at the application layer. In this architecture, RDMA serves as the foundational substrate upon which a distributed shared-memory system can be constructed.</p><p>Bypassing the standard kernel network layer in Kubernetes introduces structural infrastructure dependencies and highly precise application engineering practices.</p><p>However, for enterprise workloads bound by data throughput limitations, <strong>Kubernetes RoCE-backed Shared Memory</strong> successfully combines the operational flexibility of cloud-native scheduling with the low-latency capabilities of bare-metal computing hardware. By treating the network as a low-latency remote-memory fabric, architects can dramatically reduce kernel-networking overhead and CPU consumption while enabling distributed systems that behave similarly to shared-memory architectures at cluster scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ed851a413a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Function, Four Faces: How Decorators Helped Us Keep Module Units Clean]]></title>
            <link>https://medium.com/@hareesh.pallathoor/one-function-four-faces-how-decorators-helped-us-keep-module-units-clean-e8c99fa3d9b1?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c99fa3d9b1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-decorators]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 03:08:14 GMT</pubDate>
            <atom:updated>2026-06-15T03:08:14.811Z</atom:updated>
            <content:encoded><![CDATA[<p>We stopped duplicating HTTP handlers, MCP tools, and CLI commands. We annotate plain functions once and let thin adapters do the rest.</p><p>Most backend systems eventually outgrow their first delivery mechanism. What starts as a clean REST API eventually needs an interface for automated operations, a set of tools for LLM-driven agents, or a fast CLI utility for internal operators.</p><p>When your application exposes the same core business logic across multiple channels, you run into the problem of <strong>transport sprawl</strong>:</p><ul><li><strong>HTTP</strong> for services and web integrations.</li><li><strong>MCP</strong> (Model Context Protocol) or custom agent tools for LLM clients.</li><li><strong>CLI</strong> commands for infrastructure orchestration and manual automation.</li></ul><p>If each channel is implemented by hand, you end up writing parallel copies of the same foundational code. Routing tables, argument parsing, validation logic, error shaping, and documentation begin to drift apart. The actual domain logic gets buried under a mountain of transport-specific glue code, and exposing a single new endpoint requires touching three or four distinct architectural layers.</p><p>We wanted something different: <strong>one small, highly testable function per capability — a “module unit.”</strong> It should have strongly typed inputs, a clear name, and minimal ceremony. Everything about <em>how</em> that function is exposed to the outside world should be registered or derived, not rewritten for every transport.</p><h3>The Idea: Registration, Not Heavy Wrappers</h3><p>A common anti-pattern with Python decorators is building deep, nested runtime wrappers that manipulate arguments on the fly. This obscures stack traces, complicates debugging, and introduces hidden performance overhead.</p><p>Instead, we use <strong>stackable decorators</strong> that do almost nothing at import time except populate a centralized metadata registry. They note which transports apply (e.g., api, mcp, cli) and what metadata belongs to them.</p><p>Conceptually, the implementation looks like this:</p><pre>from pydantic import BaseModel, Field<br><br>class ReserveRequest(BaseModel):<br>    sku: str = Field(..., description=&quot;The stock keeping unit identifier&quot;)<br>    quantity: int = Field(..., gt=0, description=&quot;Number of items to reserve&quot;)<br><br>class ReserveResult(BaseModel):<br>    reservation_id: str<br>    status: str<br><br>@mcp_tool(operation_id=&quot;inventory.reserve&quot;)<br>@http_post(operation_id=&quot;inventory.reserve&quot;, path_suffix=&quot;/reserve&quot;)<br>@cli_command(operation_id=&quot;inventory.reserve&quot;, name=&quot;reserve&quot;)<br>def reserve(payload: ReserveRequest) -&gt; ReserveResult:<br>    &quot;&quot;&quot;Hold stock for an SKU until checkout completes.<br>    <br>    This ensures inventory parity across downstream fulfillment channels<br>    and prevents double-booking items during high-traffic windows.<br>    &quot;&quot;&quot;<br>    # Pure domain execution lives here<br></pre><h3>Under the Hood: The Registry Architecture</h3><p>When Python evaluates these decorators at startup, they return the <strong>exact same underlying function object</strong>. There is no complex runtime wrapping at the unit level. Instead, the decorators register an entry into a global registry dictionary:</p><pre>import inspect<br>from typing import Callable, Any, Dict, Optional, Type<br><br>class RegistryEntry:<br>    def __init__(self, operation_id: str, func: Callable[..., Any]):<br>        self.operation_id: str = operation_id<br>        self.func: Callable[..., Any] = func<br>        self.docstring: str = inspect.getdoc(func) or &quot;&quot;<br>        self.input_model: Optional[Type[BaseModel]] = None<br>        self.output_model: Optional[Type[BaseModel]] = None<br>        <br>        # Transport-specific metadata<br>        self.http_meta: Optional[Dict[str, Any]] = None<br>        self.mcp_meta: Optional[Dict[str, Any]] = None<br>        self.cli_meta: Optional[Dict[str, Any]] = None<br><br>class FunctionRegistry:<br>    def __init__(self):<br>        self._entries: Dict[str, RegistryEntry] = {}<br><br>    def register(self, operation_id: str, func: Callable[..., Any]) -&gt; RegistryEntry:<br>        if operation_id not in self._entries:<br>            self._entries[operation_id] = RegistryEntry(operation_id, func)<br>            <br>            # Introspect types once at startup<br>            sig = inspect.signature(func)<br>            for param in sig.parameters.values():<br>                if issubclass(getattr(param.annotation, &quot;__origin__&quot;, param.annotation), BaseModel) or isinstance(param.annotation, type) and issubclass(param.annotation, BaseModel):<br>                    self._entries[operation_id].input_model = param.annotation<br>                    break<br>            if issubclass(sig.return_annotation, BaseModel):<br>                self._entries[operation_id].output_model = sig.return_annotation<br>                <br>        return self._entries[operation_id]<br><br>registry = FunctionRegistry()</pre><p>The decorators themselves simply fetch or create the RegistryEntry and append their required transport metadata. This design makes the code clean and maintainable: the module stays strictly focused on data models and one function per operation. You don’t have to maintain separate route or command files that constantly risk falling out of sync with reality.</p><h3>Observability: A Single Choke Point</h3><p>Decorators are not the place to sprinkle logging boilerplate or open manual telemetry spans on every line. Execution does not happen directly inside the decorator’s registration phase. Instead, execution flows through a shared orchestration path inside each transport adapter (or a centralized execute helper).</p><pre>async def execute_operation(operation_id: str, transport: str, raw_payload: dict) -&gt; Any:<br>    entry = registry._entries.get(operation_id)<br>    if not entry:<br>        raise ValueError(f&quot;Unknown operation: {operation_id}&quot;)<br>        <br>    # Open a single unified tracing span<br>    with tracer.start_as_current_span(<br>        entry.operation_id, <br>        attributes={&quot;transport&quot;: transport}<br>    ) as span:<br>        try:<br>            # Centralized structural validation using Pydantic V2<br>            validated_input = entry.input_model.model_validate(raw_payload)<br>            <br>            # Execute the pure domain function<br>            result = await entry.func(validated_input) if inspect.iscoroutinefunction(entry.func) else entry.func(validated_input)<br>            <br>            # Centralized structured logging<br>            logger.info(&quot;Operation succeeded&quot;, extra={&quot;op&quot;: operation_id, &quot;transport&quot;: transport})<br>            return result<br>        except Exception as exc:<br>            # Unified error shaping and telemetry mapping<br>            span.record_exception(exc)<br>            logger.error(&quot;Operation failed&quot;, exc_info=True, extra={&quot;op&quot;: operation_id, &quot;transport&quot;: transport})<br>            raise map_to_transport_error(exc, transport)</pre><p>This single execution choke point provides distinct structural benefits:</p><ul><li><strong>Stable Operation Names:</strong> Every metric, log line, and OpenTelemetry span uses consistent operation_id and transport labels out of the box.</li><li><strong>Unified Policies:</strong> Cross-cutting concerns like sampling, request redaction, circuit breaking, and retries live in one place rather than across $N$ transport copies.</li><li><strong>Hyper-Focused Handlers:</strong> Business logic remains completely isolated from infrastructure concerns.</li></ul><h3>HTTP Without Duplicating Handlers</h3><p>The HTTP adapter loops through all registry entries tagged with HTTP metadata and automatically mounts routes to the underlying web framework (such as FastAPI or Starlette).</p><pre>from fastapi import FastAPI, APIRouter<br><br>def build_fastapi_router() -&gt; APIRouter:<br>    router = APIRouter()<br>    <br>    for op_id, entry in registry._entries.items():<br>        if not entry.http_meta:<br>            continue<br>            <br>        path = entry.http_meta[&quot;path_suffix&quot;]<br>        <br>        # Construct a dynamic path handler utilizing our centralized orchestrator<br>        def make_handler(operation_id=op_id):<br>            async def handler(payload: entry.input_model):<br>                # Pass the validated model straight to the orchestrator<br>                return await execute_operation(operation_id, transport=&quot;http&quot;, raw_payload=payload.model_dump())<br>            return handler<br><br>        router.add_api_route(<br>            path=path,<br>            endpoint=make_handler(),<br>            methods=[&quot;POST&quot;],<br>            response_model=entry.output_model,<br>            summary=entry.docstring.split(&quot;\n&quot;)[0]<br>        )<br>    return router</pre><p><strong>The Payoff:</strong> Exposing a core capability as a REST endpoint requires exactly <strong>one decorator line</strong> along with the input and output types you already need. You no longer need to write a separate controller class or re-implement standard parsing logic.</p><h3>MCP: Description and Schema Derived From Code</h3><p>Tool protocols like Anthropic’s Model Context Protocol (MCP) or OpenAI’s Function Calling require a strict manifest format: a machine-readable <strong>name</strong>, a <strong>human-readable description</strong>, and a <strong>structured input schema</strong>. We derive all three directly from the runtime codebase:</p><ul><li><strong>Name:</strong> The stable, immutable operation_id.</li><li><strong>Description:</strong> The first line (or full block) of the Python function’s native __doc__ string.</li><li><strong>Schema:</strong> Dynamically rendered using Pydantic’s native JSON schema generation utility (model_json_schema()).</li></ul><pre>def generate_mcp_tool_manifest() -&gt; list[dict]:<br>    tools = []<br>    for op_id, entry in registry._entries.items():<br>        if not entry.mcp_meta:<br>            continue<br>            <br>        tools.append({<br>            &quot;name&quot;: entry.operation_id,<br>            &quot;description&quot;: entry.docstring,<br>            &quot;input_schema&quot;: entry.input_model.model_json_schema() if entry.input_model else {}<br>        })<br>    return tools</pre><p>This establishes a reliable <strong>doc-to-module discipline</strong>: the Python codebase itself serves as your single source of truth and catalog tool. The docstring written for engineers is the exact text the AI agent reads to determine tool utility, and the codebase type definitions define the structural constraints the caller must satisfy. You never have to manually update a parallel OpenAPI or JSON schema file again.</p><h3>Core Design Rules for Maintainability</h3><p>Building a centralized registration system introduces a small layer of upfront structural abstraction. It is highly beneficial when:</p><ul><li>The exact same business capabilities are exposed simultaneously to <strong>HTTP consumers, LLM agent tools, and engineering CLI tooling</strong>.</li><li>You need strict <strong>schema, validation, and documentation parity</strong> across every user-facing channel.</li><li>You anticipate adding alternative network transports down the road without modifying existing domain engines.</li></ul><p>If your service exposes exactly one transport layer (e.g., a pure REST API) and you don’t face duplication friction, stick with your framework’s native router. Introduce a centralized registration engine only when a second communication channel would otherwise force you to rewrite the first.</p><h3>Summary</h3><p>Using decorators as a declarative registration engine eliminates runtime magic and avoids deep, hard-to-trace code nesting. The structural clarity comes from maintaining <strong>one module unit per behavior</strong>, relying on <strong>reflection for documentation and validation schemas</strong>, and routing execution through a <strong>unified, observable path</strong>. This approach keeps codebases highly legible and cleanly organized, allowing engineers to ship HTTP, MCP, and CLI utilities side by side without duplicating core business logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c99fa3d9b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed tracing in a polyglot stack: OpenTelemetry, Jaeger, and when ELK enters the story]]></title>
            <link>https://medium.com/@hareesh.pallathoor/distributed-tracing-in-a-polyglot-stack-opentelemetry-jaeger-and-when-elk-enters-the-story-481d782aba63?source=rss-af3ebe11be5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/481d782aba63</guid>
            <category><![CDATA[distributed-tracing]]></category>
            <dc:creator><![CDATA[Hareesh Pallathoor]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 05:38:57 GMT</pubDate>
            <atom:updated>2026-06-14T05:46:01.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-dHGF2CESi-RA67Y" /></figure><h3>How we connected a FastAPI edge service and an in-process Python library to Jaeger, avoided corporate proxy pitfalls, and kept a path open toward Elasticsearch-backed observability — without renaming the world every time the backend changes.</h3><h3>Why tracing matters</h3><p>When a client hits your API, one logical request often spans HTTP handlers, WebSockets, background tasks, an embedded computation package, and data stores such as PostgreSQL or a Redis-compatible cache. Logs give you a timeline at each sink; <strong>distributed tracing</strong> ties those moments together with a <strong>trace id</strong>, <strong>parent–child spans</strong>, and per-span latency so you can answer <em>“which hop was slow?”</em> without adding bespoke timers everywhere.</p><p><strong>OpenTelemetry (OTel)</strong> keeps that story portable: instrument once, then point exporters at <strong>Jaeger</strong> in development or at <strong>Elasticsearch / Kibana</strong> (common ELK components) or a managed collector when the organization demands it.</p><h3>Overview:</h3><ul><li><strong>Instrument</strong> with the OTel API and auto-instrumentation where available.</li><li><strong>Export</strong> spans over OTLP (gRPC or HTTP) to a collector or Jaeger.</li><li><strong>Query</strong> in Jaeger UI locally; later optionally dual-write or migrate to ELK via a collector.</li></ul><h3>Three layers (instrumentation, transport, backend)</h3><blockquote><strong><em>Architecture Overview:</em></strong><em> &gt; Application code emits spans through the OTel SDK (</em><strong><em>Instrumentation Layer</em></strong><em>). Exporters send </em><strong><em>OTLP</em></strong><em> (</em><strong><em>Transport Layer</em></strong><em>) to a receiver (</em><strong><em>Backend Layer</em></strong><em>) such as Jaeger all-in-one or an OpenTelemetry Collector. From there, traces may stay in Jaeger or be forwarded — for example, to Elasticsearch for long-term retention and Kibana dashboards.</em></blockquote><p><strong>1. Instrumentation:</strong> HTTP auto-instrumentation and manual spans. <strong>2. Transport:</strong> OTLP via gRPC or HTTP. <strong>3. Backend:</strong> Jaeger, an OTel Collector, or optional Elasticsearch.</p><h3>Typical deployment on a shared Docker network</h3><p>Place the trace backend on the <strong>same user-defined bridge</strong> as your databases and services so DNS names stay stable and you never hard-code collector IPs.</p><blockquote><strong><em>Network Topology:</em></strong><em> &gt; Inside the Docker bridge network, the API container and the library (same JVM/Python process or a sibling container) emit OTLP to </em><strong><em>Jaeger</em></strong><em> by hostname, e.g., </em><em>http://jaeger:4317 (gRPC) and </em><em>http://jaeger:4318 (HTTP). PostgreSQL and the cache are reached over ordinary TCP on the same network; they do not share OTLP ports but benefit from the same DNS and firewall rules.</em></blockquote><ul><li><strong>Inbound Traffic:</strong> External Clients ➔ API Service.</li><li><strong>Service Dependencies:</strong> API Service ➔ Internal Library, PostgreSQL, and Cache.</li><li><strong>Telemetry Data Flow:</strong> * API Service ➔ <em>OTLP gRPC (Port 4317)</em> ➔ Jaeger All-In-One</li><li>Internal Library ➔ <em>OTLP HTTP (Port 4318)</em> ➔ Jaeger All-In-One</li></ul><h3>OTLP: gRPC vs HTTP</h3><p>Jaeger all-in-one commonly listens on <strong>4317</strong> (OTLP gRPC) and <strong>4318</strong> (OTLP HTTP). Your dependency tree might favor one exporter package over the other, so it is normal for <strong>two binaries</strong> to use <strong>different OTLP transports</strong> as long as each matches an open receiver port.</p><blockquote><strong><em>Transport Protocol Split:</em></strong></blockquote><ul><li><strong>Service A:</strong> Emits data using the OTel gRPC exporter targeting <strong>port 4317</strong> on the Jaeger receiver.</li><li><strong>Service B:</strong> Emits data using the OTel HTTP exporter targeting <strong>port 4318</strong> on the same Jaeger receiver instance.</li></ul><h3>Corporate proxies and internal collectors</h3><p>HTTP_PROXY and HTTPS_PROXY are common on laptops and CI runners. <strong>Database drivers</strong> usually open raw TCP and ignore those variables for database hosts. <strong>HTTP-based OTLP</strong> and <strong>gRPC</strong> (which may use HTTP CONNECT through a proxy) <strong>do</strong> honor them — so &quot;internal&quot; Jaeger on a Docker DNS name can accidentally traverse the corporate proxy and fail with timeouts or HTTP <strong>504</strong> responses.</p><blockquote><strong><em>Decision Matrix for Proxy Routing:</em></strong></blockquote><ul><li><strong>Scenario A (Exporting traces through corporate proxy to central ELK/SaaS):</strong> Keep the proxy environment variables as-is for the OTLP exporters.</li><li><strong>Scenario B (Direct routing to internal local collector):</strong> Merge the local collector hostname into NO_PROXY and no_proxy environment variables ➔ Start OTLP exporters directly.</li></ul><p>If traces should go <strong>directly</strong> to Jaeger on the tooling Docker network, extend NO_PROXY / no_proxy with the OTLP hostname before creating exporters — after parsing the OTLP URL so hostnames are detected reliably. A <strong>single boolean or feature flag</strong> (whatever you name it in your repo) should flip between those two behaviors so operators are not editing shell profiles by hand.</p><p>Heuristics that often work for “internal” targets include: well-known local names (localhost, 127.0.0.1), private IP ranges, a fixed list of in-cluster collector service names, and <strong>single-label Docker DNS names</strong> when an environment variable such as DOCKER_NETWORK is set (meaning &quot;we are on the shared tools stack&quot;).</p><h3>Quiet logs when the collector is absent</h3><p>OTLP exporters <strong>retry</strong> and log <strong>UNAVAILABLE</strong> when the backend is down. In CI that creates noise unrelated to test failures. A <strong>verbosity flag</strong> (off by default, on when debugging export) keeps logs readable without hiding application errors.</p><h3>Shutdown and flush</h3><p>Call the SDK’s <strong>shutdown</strong> on process exit so BatchSpanProcessor flushes queued spans. That matters for serverless-style workers, tests that assert on exported data, and graceful container stops.</p><h3>Where ELK fits</h3><blockquote><strong><em>Evolution from Local to Enterprise Architecture:</em></strong></blockquote><ul><li><strong>The Common Starting Point:</strong> The OpenTelemetry SDK inside your applications sends OTLP data directly to a local Jaeger instance.</li><li><strong>The Enterprise Evolution:</strong> When you scale to require Elastic-backed retention or organizational ingestion paths, introduce an <strong>OpenTelemetry Collector</strong> in front. Applications still speak OTLP to the collector; the collector then fans out and balances the traffic to Jaeger, Elasticsearch, or both. <strong>ELK</strong> then holds logs, metrics, and traces, allowing you to keep a single, unchanged instrumentation codebase</li></ul><h3>Checklist</h3><ol><li>Document <strong>gRPC vs HTTP OTLP</strong> and <strong>ports</strong> per deployable unit.</li><li>Treat <strong>HTTP_PROXY / </strong><strong>HTTPS_PROXY / </strong><strong>NO_PROXY</strong> as part of the <strong>OTLP connectivity contract</strong>, not only for browser traffic.</li><li>Inject <strong>network context</strong> (for example the Docker network name) into containers when automation relies on “tools stack” layout.</li><li>Maintain one <strong>flag</strong> for “internal collector” vs “proxied export to ELK or SaaS.”</li><li><strong>Flush on shutdown</strong> in production and in tests.</li></ol><h3>Summary</h3><p>Tracing turns many correlated log tail sessions into <strong>one trace id</strong> and a span waterfall. Jaeger keeps that loop cheap on a shared Docker network; ELK — or a collector writing to Elasticsearch — remains the <strong>same instrumentation and different routing</strong> once policy requires it. OpenTelemetry is the stable seam between those worlds.</p><h3>Further reading:</h3><ul><li><a href="https://opentelemetry.io/docs/">OpenTelemetry Documentation</a></li><li><a href="https://www.jaegertracing.io/docs/">Jaeger Documentation</a></li><li><a href="https://opentelemetry.io/docs/collector/">OpenTelemetry Collector Guide</a></li><li><a href="https://www.elastic.co/observability">Elastic Observability</a> — <em>when traces and logs converge in one stack</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=481d782aba63" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>