<?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 Akshay Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Akshay Chauhan on Medium]]></description>
        <link>https://medium.com/@akschhn?source=rss-a86ebe36df3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TiXvJDXTRPMDwjJVVnDSIw.jpeg</url>
            <title>Stories by Akshay Chauhan on Medium</title>
            <link>https://medium.com/@akschhn?source=rss-a86ebe36df3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:00:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akschhn/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[Taming the Silent Drain: How We Slashed Inter-Zone Costs in GKE by 40%]]></title>
            <link>https://engg.glance.com/taming-the-silent-drain-how-we-slashed-inter-zone-costs-in-gke-by-40-c352247bcc46?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c352247bcc46</guid>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[endpointslices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 11:17:54 GMT</pubDate>
            <atom:updated>2025-12-29T02:57:30.947Z</atom:updated>
            <content:encoded><![CDATA[<p>When you’re operating a multi-cluster Kubernetes environment at enterprise scale,think hundreds of nodes distributed across multiple availability zones serving tens of thousands of requests per second with sub-100ms latency requirements, every misconfiguration starts to show up on your cloud bill. <br>That’s exactly what happened with one of our high-throughput feed services in our microservice driven architecture. It was fast, reliable, and efficient, until we looked closer at the network costs and spotted a red flag: inter-zone communication was bleeding money. <br>This article walks you through the root cause, what we did to fix it, and how you can apply the same principles to avoid unnecessary GKE costs in any large-scale distributed system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BfV1048fzHfLlQFlIAkhA.png" /><figcaption>Correcting the flow: Zone-aware routing keeps traffic local and costs down.</figcaption></figure><p>Spoiler: these are the practices you probably want to adopt sooner than later.</p><h3>tl;dr — Best Practices</h3><ul><li>Use BALANCED location policy in node pools</li><li>Make Services topology-aware via topology-mode</li><li>Use topologySpreadConstraints to spread pods evenly</li><li>Inspect EndpointSlices to validate zone-local routing</li><li>Apply these consistently across your service stack</li></ul><h3>Understanding the Terrain: Regions, Zones, and Node Pools</h3><p>In GCP, a <strong>region</strong> includes multiple <strong>zones, </strong>physically isolated locations designed for high availability. A <strong>regional GKE cluster</strong> automatically spreads your nodes across these zones. That’s great for resilience.</p><p>But it comes with a tradeoff: if your service-to-service traffic isn’t zone-aware, you’re likely paying a quiet, compounding tax.</p><p>In our case, several microservices — especially a high-throughput feed path, were making downstream calls without zone awareness. Multiply that by high QPS and you’ve got a surge of inter-zone data transfer. Costly.</p><h3>Debugging the Problem: EndpointSlices to the Rescue</h3><p>The turning point came when we inspected the EndpointSlice objects in our cluster namespaces. These Kubernetes resources offer deep insight into how traffic is being routed to different pod endpoints and more importantly, whether that routing is topology-aware.</p><p>This debugging step is crucial and often overlooked. If you’re seeing unexpected traffic patterns or costs, don’t underestimate what kubectl get endpointslice can tell you.</p><pre># 🔍 Step 1: Get overview of all EndpointSlices<br>kubectl get endpointslices -o wide --all-namespaces<br><br># 🔍 Step 2: Inspect specific EndpointSlice for zone mismatches  <br>kubectl get endpointslice web-service-abc123 -o yaml</pre><p>This is how a sample endpointslice yaml looks like :</p><pre>apiVersion: v1<br>items:<br>- addressType: IPv4<br>  apiVersion: discovery.k8s.io/v1<br>  endpoints:<br>  # Standard endpoint with matching forZones hint and actual zone<br>  - addresses:<br>    - 10.1.1.10<br>    conditions:<br>      ready: true<br>      serving: true<br>      terminating: false<br>    hints:<br>      forZones:<br>      - name: us-west1-a  # This hint suggests traffic should prefer this zone<br>    nodeName: node-pool-standard-abc123<br>    targetRef:<br>      kind: Pod<br>      name: web-server-deployment-xyz789<br>      namespace: production<br>      uid: 11111111-2222-3333-4444-555555555555<br>    zone: us-west1-a  # Actual zone matches the forZones hint - optimal routing<br><br>  # Endpoint with forZones/zone mismatch - cross-zone traffic routing<br>  - addresses:<br>    - 10.1.1.15<br>    conditions:<br>      ready: true<br>      serving: true<br>      terminating: false<br>    hints:<br>      forZones:<br>      - name: us-west1-b  # Hint suggests zone-b traffic should come here<br>    nodeName: node-pool-standard-def456<br>    targetRef:<br>      kind: Pod<br>      name: web-server-deployment-abc456<br>      namespace: production<br>      uid: 22222222-3333-4444-5555-666666666666<br>    zone: us-west1-c  # But pod is actually in zone-c - potential cross-zone routing<br>  <br><br>  # Endpoint without forZones hint - can receive traffic from any zone<br>  - addresses:<br>    - 10.1.3.20<br>    conditions:<br>      ready: true<br>      serving: true<br>      terminating: false<br>    # No hints section - this endpoint can receive traffic from any zone<br>    # Common scenarios: node zone issues, mixed deployments, or fallback endpoints<br>    nodeName: node-pool-spot-ghi789<br>    targetRef:<br>      kind: Pod<br>      name: web-server-deployment-def123<br>      namespace: production<br>      uid: 33333333-4444-5555-6666-777777777777<br>    zone: us-west1-a<br>  <br>  # Not ready endpoint - typically won&#39;t have forZones hints<br>  - addresses:<br>    - 10.1.1.25<br>    conditions:<br>      ready: false  # Not ready endpoints usually don&#39;t get forZones hints<br>      serving: false<br>      terminating: false<br>    # No hints - unready pods don&#39;t participate in zone-aware routing<br>    nodeName: node-pool-standard-jkl012<br>    targetRef:<br>      kind: Pod<br>      name: web-server-deployment-ghi789<br>      namespace: production<br>      uid: 44444444-5555-6666-7777-888888888888<br>    zone: us-west1-b<br>  <br>  kind: EndpointSlice<br>  metadata:<br>    creationTimestamp: &quot;2025-06-15T10:30:00Z&quot;<br>    generateName: web-server-<br>    generation: 42<br>    labels:<br>      app.kubernetes.io/name: web-server<br>      endpointslice.kubernetes.io/managed-by: endpointslice-controller.k8s.io<br>      kubernetes.io/service-name: web-server-service<br>    name: web-server-abc123<br>    namespace: production<br>    ownerReferences:<br>    - apiVersion: v1<br>      blockOwnerDeletion: true<br>      controller: true<br>      kind: Service<br>      name: web-server-service<br>      uid: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee<br>    resourceVersion: &quot;1234567890&quot;<br>    uid: 99999999-aaaa-bbbb-cccc-dddddddddddd<br>  ports:<br>  - name: http<br>    port: 8081<br>    protocol: TCP<br>  - name: metrics<br>    port: 9090<br>    protocol: TCP<br>kind: List<br>metadata:<br>  resourceVersion: &quot;&quot;</pre><p>We noticed mismatch between the actual pod zones and the values in the hints.forZones field for many endpoints within our EndpointSlices. This was a red flag: even though zone-local endpoints were available, they weren’t being prioritized for traffic within the same zone due to incorrect zone hints. <br>The hints.forZones field was pointing clients to endpoints in different zones than where the pods actually resided, causing kube-proxy to route traffic across zones instead of locally. This indicated our services weren’t fully topology-aware, silently triggering cross-zone data transfer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8URhQs212Pfl-V-5C4RDAQ.png" /><figcaption>EndpointSlice Zone Routing Behaviour</figcaption></figure><p>It’s important to understand a few nuances about EndpointSlice behaviour:</p><ul><li><strong>hints.forZones guide routing preferences but don&#39;t guarantee same-zone routing</strong>. The kube-proxy or equivalent consumer interprets these hints — they’re not hard constraints.</li><li><strong>Zone mismatches can happen</strong> due to natural events like pod rescheduling, node scaling/failures, or resource constraints during scheduling.</li><li>If forZones hints are <strong>missing or incomplete</strong>, it may be due to unready pods, misconfigured Services, or fallback behaviour when topology data isn’t available.</li><li>Also, <strong>EndpointSlices can appear with null endpoints</strong> — especially when a Service exists but no matching pods are ready. These empty slices are normal but can throw you off during debugging.</li></ul><p>While Kubernetes may co-locate endpoints from multiple zones in one slice for efficiency, in a healthy setup, <strong>the majority of endpoints (typically 90% or more)</strong> in a zone-specific slice should reference the local zone in their hints. Anything below that is worth a closer look.</p><blockquote>🛠️ <strong>Tip:</strong> Watch for low alignment between hints.forZones and endpoint zone. Less than ~90% is often a signal of scheduling or config drift.</blockquote><h3>Fixing the Leak: What We Did</h3><p>We took a multi-step approach to handle the problem. <br>Each fix chipped away at the cost while improving deployment hygiene.</p><h3>1. Use BALANCED Node Pool Location Policy</h3><p>Node distribution matters. If your node pool uses the ANY location policy, GKE can skew node allocation to certain zones. This can create imbalances where one zone is packed and others are underutilized, leading to inter-zone calls when local nodes/pods are overloaded.</p><p><strong>What we did:</strong><br> We switched the location policy to BALANCED for each node pool. This forced even distribution of nodes across all zones in the region.</p><pre>gcloud container node-pools update &lt;POOL_NAME&gt; \<br>  --cluster &lt;CLUSTER_NAME&gt; \<br>  --location &lt;REGION&gt; \<br>  --location-policy BALANCED</pre><h3>2. Make Services Topology-Aware</h3><p>By default, Kubernetes Services don’t care where your pods live. If a pod is available zone-a or zone-b it’s fair game. That means zone-a traffic can be routed to zone-b pods, even if there are healthy zone-a pods available.</p><p><strong>Fix:</strong> We added topology-mode to our service definitions to make them zone-aware.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: my-application-service<br>  labels:<br>    app.kubernetes.io/name: my-application<br>    app.kubernetes.io/instance: my-app-instance<br>    app.kubernetes.io/managed-by: Helm<br>  annotations:<br>    # CRITICAL: Topology Aware Traffic Routing to reduce cross-zone costs<br>    # This annotation enables traffic routing to endpoints in the same zone as the client<br>    # Available since Kubernetes 1.21+ and GKE 1.21+<br>    # Reduces cross-zone network egress charges by keeping traffic local to zones<br>    # <br>    # NOTE: Prior to Kubernetes 1.27, this behavior was controlled using the <br>    # service.kubernetes.io/topology-aware-hints annotation. The topology-mode<br>    # annotation is the newer, preferred approach.<br>    # <br>    # Reference: https://kubernetes.io/docs/concepts/services-networking/topology-aware-routing/<br>    service.kubernetes.io/topology-mode: &quot;Auto&quot;<br>spec:<br>  type: ClusterIP  # or LoadBalancer based on your needs<br>  ports:<br>    - port: 80<br>      targetPort: http<br>      protocol: TCP<br>      name: http<br>      appProtocol: http<br>  selector:<br>    app.kubernetes.io/name: my-application</pre><p>This instructs the Kubernetes service proxy to prioritize routing traffic within the same zone.</p><h3>3. Add topologySpreadConstraints to Deployments</h3><p>Even if services are zone-aware, your deployment needs to cooperate. If all your pods end up in one zone, intra-zone traffic isn’t possible.</p><p><strong>What we did:</strong><br> We updated our deployment YAML to include topologySpreadConstraints.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: my-application<br>spec:<br>  replicas: 12<br>  selector:<br>    matchLabels:<br>      app: my-application<br>  template:<br>    metadata:<br>      labels:<br>        app: my-application<br>    spec:<br>      topologySpreadConstraints:<br>        - maxSkew: 1<br>          topologyKey: topology.kubernetes.io/zone<br>          whenUnsatisfiable: ScheduleAnyway<br>          labelSelector:<br>            matchLabels:<br>              app: my-application<br>      containers:<br>        - name: my-application<br>          image: &lt;image&gt;</pre><p>This ensures even pod distribution across zones — so local traffic actually has local pods to talk to.</p><h3>Apply This End-to-End</h3><p>These fixes works best <strong>if applied consistently</strong> across all services in a call chain. Just one misconfigured service, an unbalanced deployment or missing annotation, can break the zone-local promise and trigger cross-zone traffic.</p><p>After rolling out these changes, we saw more than <strong>40% reduction in inter-zone data transfer costs</strong> without sacrificing performance or availability.</p><h3>Final Thoughts</h3><p>In distributed systems, the costs you don’t see are often the ones that hurt the most. Inter-zone traffic is one of them silent, invisible, but absolutely real.<br>By aligning how your nodes, pods, and services behave, you create a system that not only performs better but scales more economically.<br>Start small: pick one service, validate routing, and fix pod distribution. The rest will follow along with your savings.</p><h3>References:</h3><ol><li><a href="https://kubernetes.io/docs/concepts/services-networking/topology-aware-routing/">Kubernetes Topology Aware Routing</a></li><li><a href="https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/">Kubernetes Topology Spread Constraints</a></li><li><a href="https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/">Kubernetes EndpointSlices</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c352247bcc46" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/taming-the-silent-drain-how-we-slashed-inter-zone-costs-in-gke-by-40-c352247bcc46">Taming the Silent Drain: How We Slashed Inter-Zone Costs in GKE by 40%</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Lion and the Mouse Inside Us: A New Year’s Motto]]></title>
            <link>https://medium.com/@akschhn/the-lion-and-the-mouse-inside-us-a-new-years-motto-36d7a0643e1f?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d7a0643e1f</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[kindness-to-yourself]]></category>
            <category><![CDATA[courage]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[grace]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 08:06:34 GMT</pubDate>
            <atom:updated>2025-12-28T16:31:06.698Z</atom:updated>
            <content:encoded><![CDATA[<p>This Christmas, I gifted my niece <a href="https://www.goodreads.com/book/show/26257320-the-lion-inside"><em>The Lion Inside</em></a> by Rachel Bright. It’s a delightful short story about courage and self-confidence. Its profound message struck a chord with me, simple enough for children yet deeply meaningful for adults.</p><p>The final line resonated deeply:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMW1D6F6vxRTO7wnG5ijWg.jpeg" /></figure><p>It’s a reminder of something both profound and timeless: within each of us lies the duality of bravery and vulnerability. This balance, often overshadowed by life’s rush and expectations, is a truth worth cherishing as we embrace a new year.</p><h3>The Lion and the Mouse: A Balancing Act</h3><p>Life throws challenges our way, some we overcome, roaring with the courage of a lion, while others humble us, like the quiet vulnerability of a mouse. Both moments matter. The lion inspires bold steps, helps face fears, and drives perseverance. The mouse, in contrast, teaches grace , to accept failures, learn from them, and move forward with humility.</p><p>There are times to stand firm and take risks, embodying the lion’s strength. Equally, there are moments to pause, admit missteps, and draw strength from vulnerability. These experiences shape who we are, our strengths, and our character.</p><h3>Why Vulnerability Feels Harder</h3><p>Embracing vulnerability is often more challenging than summoning courage. One memory lingers deeply, when effort and ambition didn’t yield the result envisioned. Years ago, I worked tirelessly towards a goal, one that felt like everything at the time. Despite relentless preparation, I fell short. The sting of that perceived failure remained a whisper that occasionally suggests inadequacy.</p><p>This feeling isn’t uncommon, especially in a society where certain achievements are deeply celebrated and discussed. In moments of comparison, it’s easy to feel small. Yet, these are the very times to embrace vulnerability, to acknowledge the effort without letting the outcome define worth. It’s also a moment to celebrate others’ successes without diminishing oneself, a practice of grace and acceptance.</p><p>This sense of vulnerability is not a weakness. It’s a quieter strength that teaches us to navigate setbacks and find balance in our stories.</p><h3>A Resolution for the Year: Courage and Grace</h3><p>In the new year, the focus is on embodying courage and grace. Courage will guide bold decisions, inspire action, and sustain efforts in the face of uncertainty. Grace will allow acceptance of missteps, nurturing resilience and empathy. These qualities together create a fulfilling and meaningful journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaKgPQ2yaHZkr6KWdBLNIA.jpeg" /></figure><p>When self-doubt arises, it’s a reminder that feeling small at times is natural. What matters is the resolve to take even the smallest steps forward, blending the lion’s bravery with the mouse’s quiet strength.</p><h3>The Simplicity of Profound Lessons</h3><p>What makes <em>The Lion Inside</em> so powerful is its simplicity. A story intended for children, it carries profound truths that adults often need to revisit. Courage and self-assurance, values we commonly teach to children — are, in fact, essential guiding principles at every stage of life.</p><p>Here’s to embracing both the lion and the mouse in the year ahead. <br>May courage propel us through challenges, and vulnerability teach us humility. Together, they make us stronger, wiser, and more compassionate.</p><p>Here’s to a year of courage and grace.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d7a0643e1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Friendships Evolve: Embracing Change with Grace]]></title>
            <link>https://medium.com/@akschhn/when-friendships-evolve-embracing-change-with-grace-909d8eeb1bf7?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/909d8eeb1bf7</guid>
            <category><![CDATA[gratitude]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[friendship]]></category>
            <category><![CDATA[embracing-change]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 10:40:33 GMT</pubDate>
            <atom:updated>2025-12-29T02:59:14.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever looked back on a friendship and wondered when things started to change? Friendships are among the most meaningful connections we form, grounding us through life’s highs and lows. Yet, as time passes, even the closest bonds can shift, some grow deeper, while others quietly drift apart. It’s bittersweet to watch a once vibrant connection fade or to feel the weight of a one-sided relationship. But while not every friendship is meant to last a lifetime, each one leaves a unique imprint on our hearts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHeLQmqPrvqog-khit7V-Q.jpeg" /><figcaption>Embracing change and growth in every evolving friendship.</figcaption></figure><p>Changes in friendships can stir feelings of sadness or confusion, particularly when the reasons behind them aren’t clear. But these shifts often reflect our own evolving paths, reminding us that no connection remains the same forever. As people grow at different paces, life circumstances evolve, and priorities realign, it’s natural for relationships to change. While it’s normal to grieve the loss of how things once were, these moments also offer us a chance to pause, reflect, and rediscover what truly matters in our connections.</p><h3>The Fluid Nature of Friendship</h3><p>Friendships, much like seasons, go through their own cycles. Some friends remain constants in our lives, while others enter at specific moments, offering us exactly what we need at the time. These <em>seasonal</em> friendships are no less meaningful than lifelong ones; they shape our journey in unique ways, providing support and lessons when we need them most. Friendship’s true beauty lies not in how long it lasts, but in the profound impact it leaves behind.</p><p>When a friendship feels distant or transactional, it doesn’t always signal failure. Sometimes, it simply means the connection has shifted or run its course in its current form. This realisation doesn’t diminish the joy, growth, and memories the relationship once brought.</p><h3>Navigating Change with an Open Heart</h3><p>When we face shifts in our friendships, it’s important to approach them with understanding and self-compassion. Though challenging, these changes often offer valuable lessons. Here are a few ways to find balance and perspective:</p><ol><li><strong>Celebrate What Was Shared</strong><br>Every friendship has a unique story. Even if things feel different now, take time to appreciate the memories and lessons it brought into your life.</li><li><strong>Prioritise Authenticity</strong><br>Focus on relationships that are genuine and reciprocal. A few meaningful connections often bring more fulfillment than a large, shallow circle of acquaintances.</li><li><strong>Be Open to New Bonds</strong><br>Life constantly offers opportunities to meet new people. Whether through hobbies, communities, or conversations, you can form connections that reflect your current self.</li><li><strong>Invest in Personal Growth</strong><br>Changes in relationships can also be an invitation to reconnect with yourself. Take this opportunity to dive into your interests, learn something new, or savor moments of solitude.</li><li><strong>Accept Change as Growth</strong><br>As we grow, so do our relationships. Instead of perceiving these changes as setbacks, embrace them as a natural progression in your life.</li></ol><h3>Moving Forward with Gratitude and Hope</h3><p>Growth isn’t about holding on too tightly; it’s about knowing when to let go with gratitude.</p><p>While evolving friendships can be bittersweet, they also create space for new, more meaningful connections. <br>Each change creates room for stronger bonds whether with others or within yourself. Believe that as one chapter ends, new opportunities will emerge in unexpected ways.</p><p>Life revolves around connection, but not all connections are meant to last forever. What truly matters is the imprint friendships leave on our lives, the joy, lessons, and growth they bring along the way.</p><p>As relationships evolve, embrace the process with an open heart. Be thankful for what was, hopeful for what lies ahead, and confident in the resilience and strength you’ve gained through it all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909d8eeb1bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom Liveness Probe in Spark Applications on Kubernetes: A Journey to Automated…]]></title>
            <link>https://engg.glance.com/building-custom-liveness-probe-in-spark-applications-on-kubernetes-a-journey-to-automated-a90bd4dba3cf?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90bd4dba3cf</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[structured-streaming]]></category>
            <category><![CDATA[livenessprobe]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 09:58:21 GMT</pubDate>
            <atom:updated>2024-11-19T18:08:06.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Custom Liveness Probe in Spark Applications on Kubernetes: A Journey to Automated Self-Healing</h3><blockquote><strong>TL;DR</strong></blockquote><blockquote>Github-Gist <a href="https://gist.github.com/akschhn/57df3293b27eb0fbf38b090d87b8d862">Link</a></blockquote><blockquote>This article outlines how we tackled the problem of Spark driver pods entering a hung state in a Kubernetes environment. By monitoring logs for inactivity and embedding a custom self-healing script in driver pods, we automated recovery processes and reduced downtime. This solution integrates seamlessly with Kubernetes and scales effortlessly, making Spark workloads more reliable while minimising manual interventions.</blockquote><p>Modern machine learning (ML) infrastructure often requires juggling a myriad of moving parts — data pipelines, distributed processing, real-time analytics, and resource orchestration. When scaling these workloads, a failure at any point in the chain can lead to cascading impacts, including downtime, delayed insights, and increased manual interventions.</p><p><strong>Prologue: Why a Custom Liveness Probe?</strong></p><p>In our case, one of the weak links we encountered was with driver pods for structured Spark streaming applications running on Kubernetes (K8s) and orchestrated by Kubeflow’s Spark operator. <br>Although Kubernetes offers a liveness probe feature to automatically restart unresponsive pods, the version of the Spark operator we use does not support liveness probes out of the box. This limitation has been noted in various discussions and GitHub issues within the <a href="https://github.com/kubeflow/spark-operator/issues?q=is%3Aissue+liveness">community</a>. <br>As a result, our team needed to develop a custom solution to detect and handle these unresponsive driver pods automatically, ensuring that ML workflows remain stable and reliable.</p><p><strong>What are Driver Pods and Executor Pods?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*tkWi16Clt_6RjLJNmyLVkg.png" /><figcaption>Figure 1: <a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html">Running Spark on Kubernetes</a></figcaption></figure><p>a. <strong>Driver Pods</strong>: The driver pod is the main control process in a Spark application, responsible for converting the user program into tasks and scheduling them across the cluster.</p><p>b. <strong>Executor Pods</strong>: Executors are the worker nodes that perform the actual computation and store the data, each running inside its own pod.</p><p>Our team was tasked with solving the issue efficiently by automating the detection and recovery of unresponsive driver pods, minimising downtime and manual effort.<br>In this post, I’ll walk through the journey we took, from manual interventions to a robust self-healing architecture, that enabled us to eliminate service lag and improve the reliability of our ML workloads.</p><p><strong>Problem Statement: Driver Pods Entering Hung State</strong></p><p>In our Spark-driven ML workflows, a critical component was structured Spark streaming, managed by Kubernetes. When driver applications encountered issues, they could enter a hung state while the pod still appeared to be running.</p><p>This issue became apparent during operational downtimes, often necessitating manual intervention by on-call engineers to manage and refresh the deployment. This high-touch process was prone to delays.</p><p>Common Scenario of a Hung Driver Pod:</p><pre>kubectl get pods -n namespace</pre><pre>NAME              READY     STATUS    RESTARTS   AGE <br>spark-driver-pod   1/1     Running       0       12h</pre><p>From the Kubernetes perspective, everything looked normal, but the <strong>driver application was stuck </strong>and no new tasks were being processed. This false <em>Running</em> status led to delays in processing incoming data and eventually <strong>increased downtime </strong>as manual intervention was required to restart the pod.</p><p>We needed a <strong>self-healing mechanism </strong>that could automatically detect when the driver application was unresponsive and initiate recovery without manual intervention.</p><p><strong>Proposed Solution: </strong>Building<strong> </strong>Automated Hung State Detection &amp; Recovery</p><p><strong>Key Concept: </strong>Using<strong> </strong>Log Analysis as a Health Indicator</p><blockquote>At the heart of our solution is the <strong>log file</strong>, a natural and reliable health indicator for the driver application. When a driver pod is functioning normally, logs are consistently being written, reflecting active operations and task executions.</blockquote><blockquote>We designed a monitoring solution that works by checking the <strong>absence of log activity </strong>over a specified period. If no log entries are detected within a certain timeframe, the application is flagged as potentially hung, and an automated graceful shutdown of the pod is triggered, allowing <strong>Kubernetes’ Spark operator </strong>to restart it.</blockquote><p>This automatic recovery process adheres to the <strong>Kubernetes self-healing principle</strong>, ensuring minimal disruption and downtime.</p><p><strong>Core Components of the Solution:</strong></p><p><strong>a. Log Analysis</strong>: Application logs are continuously monitored. The absence of logs for a set interval indicates that the driver is in a hung state.</p><p><strong>b. Custom Monitoring Script</strong>: A lightweight Bash script monitors the log file’s last modification time, and if no recent activity is detected, initiates a graceful termination of the driver pod. Upon termination with an exit code 137 (indicating forced termination), Kubernetes automatically restarts the pod.</p><p><strong>c. Embedded File Log Handler</strong>: Logs are rotated every hour, ensuring the monitoring script always has access to fresh log data, thus maintaining accuracy in detecting inactivity.</p><p><strong>Explorations</strong>: The Path to Finding the Best Solution</p><p><strong>1. CRD Liveness Probe Integration</strong></p><p>Our first attempt involved adding a <strong>liveness probe </strong>to the Spark application’s <strong>Custom Resource Definition (CRD)</strong>. The idea was simple — if the liveness probe failed, Kubernetes would automatically restart the pod. However, we quickly discovered that the <strong>Spark operator CRD did not support liveness probes (for the version in use; </strong><a href="https://github.com/kubeflow/spark-operator/issues?q=is%3Aissue+liveness"><strong>Reference</strong></a><strong>)</strong>, making this approach unfeasible for our setup.</p><pre># Spark CRD (attempted Liveness Probe inclusion)<br>spec:<br>  driver:<br>    livenessProbe:<br>      # Liveness probe functionality not supported<br>      initialDelaySeconds: 300<br>      timeoutSeconds: 5</pre><p>Although this method was appealing in its simplicity, the lack of native support forced us to look for alternatives.</p><p><strong>2. Managing the Driver Application with Supervisord</strong></p><p>In our second attempt, we decided to manage both the Spark driver and the monitoring script using <strong>supervisord</strong>, a lightweight process control system.</p><pre># Supervisord configuration managing both Spark driver and monitoring script<br>[program:spark_driver]<br>command=spark-submit --class org.apache.spark.examples.SparkPi ...<br>autostart=true<br>autorestart=true<br><br>[program:monitor_script]<br>command=/app/monitor_log.sh<br>autostart=true<br>autorestart=true</pre><p>While this method let us manage the application’s lifecycle ourselves, it had a major drawback: it ignored the Spark operator’s control, which is responsible for managing Spark jobs in Kubernetes. <br>This was not in line with Kubernetes best practices, so we decided to not use this approach.</p><p><strong>3. Asynchronous Monitoring as a Subprocess (Chosen Solution)</strong></p><p>The third approach was the most promising: <strong>embedding the custom monitoring script directly within the Spark driver pod </strong>and launching it as an <strong>asynchronous subprocess </strong>from the Spark application itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*7j9Wfw31T6lbs5xHdBC2vg.jpeg" /><figcaption>Figure 2 : Monitoring Liveness For Driver Pods</figcaption></figure><p>This method provided two major benefits:</p><p><strong>a. Seamless Integration with Kubernetes and the Spark Operator</strong>: By embedding the script directly into the pod, we retained full compatibility with Kubernetes and Spark operator’s native mechanisms.</p><p><strong>b. Configurable via Helm</strong>: We could easily toggle the monitoring script on or off, and adjust its parameters using Helm charts.</p><p>Here’s a simplified Python implementation, demonstrating how we run the monitoring script as a <strong>background subprocess</strong>:</p><pre>import subprocess<br><br>def launch_monitoring_script():<br>  &quot;&quot;&quot;<br>  Launches the monitoring script in the background.<br>  &quot;&quot;&quot;<br>  monitoring_script_path = &quot;/app/path-to-monitoring-script.sh&quot;<br>  subprocess.Popen([&quot;/bin/bash&quot;, monitoring_script_path])</pre><p>This solution achieved what we had been aiming for: <strong>automated recovery </strong>from driver pod hung states without violating Kubernetes’ operational models.</p><p><em>Monitoring Script in Action:</em></p><p>The core of the solution is the <strong>monitoring script </strong>that checks the logs for inactivity (simplified form):</p><pre>#!/bin/bash<br><br># Path to the log file to be monitored<br>LOG_FILE_PATH=&quot;${LOG_FILE_PATH:-/tmp/logfile.log}&quot;<br><br># Time format to be used for date commands<br>TIME_FORMAT=&quot;%Y-%m-%d %H:%M:%S&quot;<br><br># Number of seconds to look back for recent logs, defaulting to 120 seconds if not set<br>SECONDS_AGO=${LIVENESS_SECONDS_AGO:-120}<br><br># Function to get the current time in the specified format<br>get_current_time() {<br>    date +&quot;$TIME_FORMAT&quot;<br>}<br><br># Function to get the time from SECONDS_AGO seconds ago in the specified format<br>get_time_ago() {<br>    if [[ &quot;$OSTYPE&quot; == &quot;darwin&quot;* ]]; then<br>        # For macOS<br>        date -v-&quot;${SECONDS_AGO}&quot;S +&quot;$TIME_FORMAT&quot;<br>    else<br>        # For Linux<br>        date --date=&quot;${SECONDS_AGO} seconds ago&quot; +&quot;$TIME_FORMAT&quot;<br>    fi<br>}<br><br># Function to check if the log file exists<br>check_log_file_exists() {<br>    if [ ! -f &quot;$LOG_FILE_PATH&quot; ]; then<br>        echo &quot;Log file $LOG_FILE_PATH does not exist.&quot;<br>        exit 1<br>    fi<br>}<br><br># Function to get logs from the log file between the specified start and end times<br>get_recent_logs() {<br>    local start=&quot;$1&quot;<br>    local end=&quot;$2&quot;<br>    awk -v start=&quot;$start&quot; -v end=&quot;$end&quot; -v format=&quot;$TIME_FORMAT&quot; &#39;<br>    {<br>        log_time = substr($0, 1, 19)  # Extract the timestamp from the log line<br>        if (log_time &gt;= start &amp;&amp; log_time &lt;= end) {<br>            print $0  # Print the log line if it falls within the time range<br>        }<br>    }&#39; &quot;$LOG_FILE_PATH&quot;<br>}<br><br># Function to restart the Spark application if it is running (but was stuck or not producing logs)<br>restart_spark_application() {<br>    local spark_pid<br>    local spark_command<br>    # Find the PID of the Spark application<br>    spark_pid=$(ps aux | grep &#39;org.apache.spark.deploy.SparkSubmit&#39; | grep -v grep | awk &#39;{print $2}&#39;)<br>    if [ -n &quot;$spark_pid&quot; ]; then<br>        # Capture the command used to start the Spark application<br>        spark_command=$(ps -p &quot;$spark_pid&quot; -o args=)<br>        echo &quot;Terminating Spark application with PID: $spark_pid&quot;<br>        kill -15 &quot;$spark_pid&quot;  # Send SIGTERM to allow graceful shutdown<br><br>         # Wait for the Spark application to terminate<br>        local wait_time=0<br>        local max_wait_time=30  # Maximum wait time in seconds<br>        while kill -0 &quot;$spark_pid&quot; 2&gt;/dev/null; do<br>            if [ &quot;$wait_time&quot; -ge &quot;$max_wait_time&quot; ]; then<br>                echo &quot;Spark application did not terminate gracefully. Forcefully killing it.&quot;<br>                kill -9 &quot;$spark_pid&quot;  # Forcefully kill the Spark application<br>                break<br>            fi<br>            echo &quot;Waiting for Spark application to terminate...&quot;<br>            sleep 1<br>            wait_time=$((wait_time + 1))<br>        done<br><br>        echo &quot;Restarting Spark application with command: $spark_command&quot;<br>        # Restart the Spark application<br>        nohup $spark_command &amp;<br>    else<br>        echo &quot;No Spark application found to restart.&quot;<br>    fi<br>}<br><br># Main function to perform the liveness check in a loop<br>main() {<br>    echo &quot;Starting liveness check for log file: $LOG_FILE_PATH in $SECONDS_AGO seconds&quot;<br>    sleep &quot;$SECONDS_AGO&quot;<br>    while true; do<br>        current_time=$(get_current_time)<br>        echo &quot;Current time: $current_time&quot;<br><br>        time_ago=$(get_time_ago)<br><br>        check_log_file_exists<br><br>        recent_logs=$(get_recent_logs &quot;$time_ago&quot; &quot;$current_time&quot;)<br><br>        if [ -z &quot;$recent_logs&quot; ]; then<br>            echo &quot;No recent logs found. Liveness check failed&quot;<br>            restart_spark_application<br>        else<br>            echo &quot;----------------------------------------&quot;<br>            echo &quot;Recent logs found. Liveness check passed&quot;<br>            echo &quot;$recent_logs&quot;<br>            echo &quot;----------------------------------------&quot;<br>        fi<br><br>        sleep &quot;$SECONDS_AGO&quot;  # Sleep for the specified number of seconds before the next check<br>    done<br>}<br><br># Start the main function<br>main</pre><p>This script checks for logs every few minutes. If no activity is detected, it triggers a shutdown by sending a <strong>SIGTERM </strong>to the driver process. Kubernetes then automatically restarts the pod based on its self-healing properties.</p><p><strong>Results &amp; Benefits</strong></p><ol><li><strong>Reduced Service Downtime</strong>: Recovery time from hung states has been reduced from hours to minutes.</li><li><strong>Operational Efficiency</strong>: On-call engineers no longer need to manually intervene for driver pod issues.</li><li><strong>Scalability</strong>: The solution scales with Kubernetes, requiring no additional configuration.</li><li><strong>Enhanced User Experience</strong>: Ensures timely delivery of data to end users, improving satisfaction.</li></ol><p><strong>Future Enhancements</strong></p><ul><li><strong>Multi-metric Analysis</strong>: We plan to incorporate CPU and memory usage metrics alongside log analysis for better detection of hung states.</li><li><strong>Idle Detection Improvements</strong>: To address unnecessary restarts due to inactivity during low input, we’re exploring enhancements that could help differentiate true hangs from idle states.</li></ul><p><strong>Conclusion</strong></p><p>Our journey to automated self-healing has transformed our Spark applications’ reliability on Kubernetes. By embedding a log-monitoring script, we ensured minimal downtime and service disruption while maintaining alignment with Kubernetes best practices. The current solution offers a robust foundation, and we look forward to further refining it with multi-metric monitoring and optimisations.</p><p>If you’re facing similar challenges in managing long-running Spark workloads on Kubernetes, I hope this article provides some insights and solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90bd4dba3cf" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/building-custom-liveness-probe-in-spark-applications-on-kubernetes-a-journey-to-automated-a90bd4dba3cf">Building Custom Liveness Probe in Spark Applications on Kubernetes: A Journey to Automated…</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Turning 30 ……]]></title>
            <link>https://medium.com/@akschhn/on-turning-30-f1bdd02ee65b?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1bdd02ee65b</guid>
            <category><![CDATA[lessons-in-life]]></category>
            <category><![CDATA[perspective]]></category>
            <category><![CDATA[embrace-yourself]]></category>
            <category><![CDATA[gratefulness]]></category>
            <category><![CDATA[thirtysomething]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 20:10:26 GMT</pubDate>
            <atom:updated>2025-01-01T07:23:05.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>On Turning 30 ……</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VjeGr87soDUGrbTP" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Panic, anxiety, and a little tear or two, that’s how I approached my 30th birthday last month. Although I believe, I have been a non-dramatic person all through my twenties but I couldn’t hold on to these emotions. There are so many negative or I should say non-young facts out there attached to turning 30, damn the society standards. I decided to acknowledge these emotions and try &amp; celebrate the day with my family.</p><p>All of us have our favorite nerve-calming habits, for me, it is driving &amp; music. I decided to go out for a drive and spend some time alone as I tried to make sense of these little depressing feelings. <br>An hour into the drive and some Spotify podcasts later I decided to reflect on the good things going on in my life. I went on to buy a journal, parked my car at a quiet place, and started writing down all the things I feel grateful for, these included the people in my life, incidents that helped shape my character, my work, and anything and everything that came to my mind. This simple little activity of 15–20 minutes made me feel lighter already, I was able to better enjoy my playlist, and I felt a little organized (this has been an OCD I developed in my twenties :) ). I decided to plan a nice time with my family for the rest of the day while going back home.</p><p>As I look back on the last decade I feel life has been kind to me in a lot of aspects. Most of the time I have been able to surround myself with people smarter than me, and have learned a lot as a part of this process.<br>I have been fortunate enough to be an acting mentor for a few folks and have tried to religiously pay my dues in this duty. I couldn’t ask for a more caring family and I dare not take them for granted.</p><p>Listing down my learnings here for the 30+-year-old me to get back to if any panic attack strikes again :) —</p><blockquote>1. Embrace your uniqueness, it’s ok if you feel different from others. Few things might come easier to others and visa-versa, it is perfectly normal.</blockquote><blockquote>2. Don’t let outside noise corrupt you. Acknowledge all feedbacks and work only on the relevant ones.</blockquote><blockquote>3. Friend’s circle changes a lot in your twenties. It is possible you may not be in touch with your school/college besties. It’s ok, that’s how some things ought to grow.</blockquote><blockquote>4. Find good mentors early in your career.</blockquote><blockquote>5. If given a chance be a good mentor (one which you always idolized or sought) for your juniors.</blockquote><blockquote>6. Between work, health and family; family and health should always be prioritized.</blockquote><blockquote>7. Do not take your close ones for granted. Be involved in their special occasions, the older you will thank you.</blockquote><blockquote>8. It is not easy to find true love, learn to respect the unconditional blessings bestowed on you by your family.</blockquote><blockquote>9. Amplify the things you are good at, be more of what good you have in person, and carve out a trajectory from this trait, one which could have a larger impact.</blockquote><blockquote>10. It’s ok if there are items still pending to be done; you will prioritize and sort it all out soon. Don’t lose sleep over this.</blockquote><p>Would like to end with a borrowed quote:</p><p><em>“Don’t worry about turning 30, you will get used to it. Of Course, you will be 40 by then :) ”</em></p><p>Regards<br>Akshay</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1bdd02ee65b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flirting with danger]]></title>
            <link>https://medium.com/@akschhn/flirting-with-danger-bc138c06f8f2?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc138c06f8f2</guid>
            <category><![CDATA[health]]></category>
            <category><![CDATA[trains]]></category>
            <category><![CDATA[accident]]></category>
            <category><![CDATA[family]]></category>
            <category><![CDATA[love]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Sun, 10 Dec 2017 12:39:52 GMT</pubDate>
            <atom:updated>2018-02-08T04:22:34.409Z</atom:updated>
            <content:encoded><![CDATA[<p>PS : This post has been in my draft for almost an year. I have been hesitant to hit the publish button but have finally decided to let it out of my system.</p><p>Last year in December, me and my sister had to go to a friend’s wedding at Kuchaman, Rajasthan. The tickets were booked, leaves applied and we were ready to go. I was super excited which was very unlike me, seriously. It was a three day trip and I even made plans to visit some places over there after the marriage.</p><p>We boarded the train around 9.30 pm on 6th Dec , it was a seven hour journey. We had third tier a/c seats and quite expectedly I got the middle berth. Needless to say I was awake most of the night. We were supposed to reach Kuchaman at 4.30 am. Around 4’o clock I went to the coach attendant to ask him about the expected arrival time at the station. Because of the fog the train was running late by an hour, anyways we were up and had our stuff in place and were ready to deboard. Train’s stoppage time at Kuchaman station was 3-4 minutes only so we knew we had to deboard fast.</p><p>Around 5.30 am when we saw that the train was about to reach the station, we went near exit and asked the attendant to open the door, it was either locked or was too rusty to be opened by either of us. He told us that our station is still half an hour away , maybe he was half asleep. But 2-3 minutes later he realised his mistake and opened the door , but by then the train had started moving.</p><p>In that sudden moment we didn’t think clearly and decided to deboard anyway. My sister deboarded first and lost balance while doing so. Because of the fog outside I was not able to see clearly but I heard her scream. The train was at a considerable speed by this time , to make matters worse I had a bagpack and a trolley bag too. The view outside was way too hazy, but leaving my sister over there was not an option and pulling the emergency chain didn’t cross my mind , damn!!</p><p>Recollecting all my high school physics, I made the leap into the dark and completely lost control , physics!! you betrayed me again. Next I remember I was skidding through something and was desperately trying to ensure that my legs don’t get under the train. All this continued for a few seconds and then I fell unconscious and was lying their on the track.</p><p>My sister was there on the platform trying hard to get up. She looked for help but no one was there except for a man who was busy robbing away our stuff, yes! rest in peace humanity. Luckily, she could muster enough strength to make a phone call to the people who were coming to pick us up. She let them know about our condition and eventually passed out.</p><p>Both of us were taken for first aid to a government hospital in Kuchaman. I gained little consciousness when the doctor was trying to stitch the wounds on my head. I was dizzy but wanted to know about my sister’s well being. I asked the doctor about her in whatever broken words I could gather. He promptly replied that she is fine and I fell back to sleep.</p><p>Around 8.00 in the morning I regained consciousness and immediately realized things were not right with my body. I was trying hard to recollect the events after the jump but was unable to so. My sister was crying seeing my state , but I was happy to see her. Moments like these makes you realise how much granted we take our life to be. I was really grateful for the lucky escape we had.</p><p>Although I was strongly against this but we had to call our parents and let them know about the accident. They were shocked to hear this news and immediately decided to come. But keeping in mind the time constraint for the treatment of a head injury and fracture, we decided to meet in Jaipur.</p><p>Our friend arranged the cab for us. During the three hour journey to Jaipur my sister was constantly worried about me. She was blaming herself for this which was completely wrong, we both were equal partners in this crime.</p><p>We checked into our hotel, the receptionist seemed concerned on seeing us which was understandable. Our parents arrived within an hour of our arrival. They had mixed emotions of worry, anger and concern. My father consulted our family doctor and sent him our reports. Although it was risky but we decided to get the treatment done in Delhi only.</p><p>We left for Delhi early morning next day. I and my sister slept through most of this period. We straightaway went to the hospital and were taken to the emergency ward. What followed was painful, I had to get the wounds dressing redone, on the top of this a strange sticky fluid was still coming out from my back, aah!! it was terrible.</p><p>Next we were taken to get our MRI done. My sister had internal fracture in her head and foot. I had compression fracture in my backbone, radial fracture in my right hand and a clot in my brain. Obviously all of this was too much for my parents to handle , thankfully my extended family members came pretty soon for the much needed support.</p><p>We were in the hospital for next 4 days. I had to undergo a surgery to get the fracture treated and was advised 6 weeks of bed rest. During the initial 2–3 weeks I was unable to get up from the bed without a support, which at times was frustrating. Although this was a tough period , but I have to say the selfless love bestowed on me by my family helped me bear the pain with a smile. My mother became my cook , my nurse ; my father became my dietitian , my story-teller and my sister , my partner in crime, became my companion. I was pampered with lots of love and care from extended family members and close friends as well.</p><p>I believe this incident made me a more emotional person. I developed great affection towards the people who were there for me (a big hug to you guys). At the same time there were a few people I was expecting too much from and they did disappoint. But this was also a blessing in disguise. It helped me understand who really matters in my life.</p><p>When I look back and think about the gravity of this event and how we got away with it , I feel a strong gratitude towards life. It has made me realise the important things in life , the important people in life and last but not the least it has helped me learn how we should never take anything or anyone for granted in our life.<br>If you wish to express love towards someone, don’t wait , don’t postpone it to tomorrow, go and just do it now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc138c06f8f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a security alarm using raspberry pi]]></title>
            <link>https://medium.com/hackernoon/building-a-security-alarm-using-raspberry-pi-725a18f42e84?source=rss-a86ebe36df3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/725a18f42e84</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <dc:creator><![CDATA[Akshay Chauhan]]></dc:creator>
            <pubDate>Sun, 04 Jun 2017 07:47:58 GMT</pubDate>
            <atom:updated>2019-05-15T07:10:17.695Z</atom:updated>
            <content:encoded><![CDATA[<p>Internet of things is a buzzword nowadays and if you are one of those people who have been itching to get started with it but were unable to do so, this is an attempt to help you understand the different pieces involved in setting up an IoT system. I had an opportunity to work on an IoT based project at workplace and would like to share my learnings over here.</p><p>Resources used :</p><ol><li>Raspberry Pi Model B</li><li>Grovepi Starter Kit</li><li>IP camera</li><li><a href="https://hackernoon.com/tagged/azure">Azure</a> Service Bus</li><li>Azure Mobile Services</li><li>Azure Blob Storage</li><li>Native Windows Mobile application</li></ol><p><strong>(I)</strong> In order to get started we booted our pi device with raspbian operating system which is a debian optimized for raspberry pi hardware(<a href="http://www.raspberrypi.org/documentation/installation/installing-images/windows.md">Installation</a>).</p><p>Each pi device has a row of general purpose input output (GPIO) pins which acts as an interface between the pi and the outside world. We can connect sensors to these pins and program them according to our requirements. In model A and B of raspberry the gpio pins look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*jChql6URdEQyFwnk." /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*R_fcGeEDuAwYopTC." /></figure><p>You have two options to connect sensors to raspberry :</p><ol><li>Use breadboard, resistors, wires to form the required circuit.</li><li>Use connectors to do the above job for you.</li></ol><p>We went with the second option and used a device named grove pi (now upgraded to grovepi +) which is a modular board <a href="https://hackernoon.com/tagged/designed">designed</a> specifically for raspberry pi. With this you just need to plug the board on the pi and then connect the required sensors with the board. Installation steps of grove pi on raspberry device can be seen over <a href="http://www.seeedstudio.com/depot/GrovePi-Starter-Kit-for-Raspberry-Pipreorder-p-2240.html">here</a>. Once this was done we were ready to start experimenting with the sensors.</p><p><strong>(II)</strong> <strong>Use Case</strong> : Setting up a Security Monitor to detect burglary alarm and send notification to the user with the pictures of the event</p><p>Here is a breakdown of the tasks for our use case:</p><ol><li>Connecting sound sensor to pi device.</li><li>Setting up azure cloud services.</li><li>Script to read sound input from surrounding using sound sensor and send a message to a queue when the sound level crosses a particular threshold value (This will be the frequency value at which the burglary alarm works)</li><li>Writing a consumer for the theft message sent.</li><li>Showing notification with the burglary pics on the app which will be used by the end user.</li></ol><h4><strong>Step 1: Connecting sound sensor to raspberry pi</strong></h4><p>(i) Grove Pi has separate slots for connecting analog and digital sensors. The analog sensor ports are labelled as A1 — An and digital ports are labelled as D1-Dm. Since sound sensor is an analog sensor we connected it to one of the analog ports.</p><p>(ii) In order to code on the raspberry pi we connected keyboard, mouse to the USB ports available on it. Also HDMI port was connected to the LCD monitor and LAN cable was connected to the LAN port. Once this was done our setup looked like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7o416owVHtQPXYFZ." /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dYg7L3DKTu2qxZR2." /><figcaption>Raspberry pi + grove pi + sensors setup</figcaption></figure><h4><strong>Step 2: Setup Azure cloud services</strong></h4><p>We needed to setup following cloud services on azure:</p><ol><li>Azure Blob Storage: A blob can be any type of text or binary data, such as a document, media file, or application installer.</li><li>Azure Service Bus Queue: Service bus queue supports brokered messaging model. When using service bus queue, components of distributed application do not interact directly they rather exchange messages via the queue which acts as intermediary (<a href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-java-how-to-use-queues">Reference</a>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*_DvHxRAAsXOAL2bX." /><figcaption>Azure Service bus queue architecture</figcaption></figure><p>3. Azure Mobile service (now mobile app service) : This is a mobile backend as a service which provides cloud storage, authentication and push notification services. It is based on RESTful programming interface to perform CRUD operations (using HTTP get/put/post/delete methods). We used mobile service for cloud storage and to provide push notification service in our mobile application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*FSRTHMdN4RqczC7c." /><figcaption>Our IOT system architecture</figcaption></figure><h4><strong>Step 3: Script for sound sensor</strong></h4><p>This step is further divided into following sub-steps:</p><ol><li>Code to read sound level from the external environment.</li><li>Whenever the sound level reaches beyond the threshold sound value (frequency at which burglary alarm works) we need to :</li></ol><blockquote>(i) Connect to the IP camera at our place and save the current frame image on raspberry.</blockquote><blockquote>(ii) Upload the saved image on azure blob storage.</blockquote><blockquote>(iii) Send a message on azure service bus queue with the image name and time-stamp.</blockquote><h4><strong>Step 4: Creating consumer for the service bus queue</strong></h4><p>We decided to use azure mobile service for this purpose as it provided us a feature of scheduler where we can schedule a task to be run continuously after some time interval. In our case we wanted our consumer to do 2 things:</p><ol><li>Read the image name from the message sent in the queue.</li><li>Store the image name and time-stamp in a table storage.</li></ol><h4><strong>Step 5: Create a mobile application</strong></h4><p>We needed a mobile application to do following things:</p><ol><li>Show instant notification whenever a theft alarm goes off</li><li>Show the theft picture on click of the notification.</li><li>Show the past history of theft pics.</li></ol><p>Our mobile application was connected with the azure mobile service to use it’s push notification feature and in order to get the names of the theft pictures from the cloud storage. Corresponding to each theft pic name in the table storage there was a picture stored in blob storage on azure from where the application finally fetched the image to display it to the user.</p><p>Once this was done we were able to connect the different pieces required in setting up our security system with a raspberry pi and basic sensor kit.We did this work about an year ago, now most of the cloud services like azure and amazon provides IoT frameworks which internally has the above mentioned services packaged together.</p><p>Thanks for taking the time to view this post, I hope it helped you in understanding the different components involved in setting up an IoT system.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=725a18f42e84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/building-a-security-alarm-using-raspberry-pi-725a18f42e84">Building a security alarm using raspberry pi</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>