<?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 Ahemad on Medium]]></title>
        <description><![CDATA[Stories by Ahemad on Medium]]></description>
        <link>https://medium.com/@ahemad01?source=rss-f5d0fa99d25f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GCtGtMr7KWMk_7We</url>
            <title>Stories by Ahemad on Medium</title>
            <link>https://medium.com/@ahemad01?source=rss-f5d0fa99d25f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:38:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahemad01/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[From Jenkins to GitHub Actions: A Practical Migration Guide (With SSH vs SSM Deployment Deep Dive)]]></title>
            <link>https://medium.com/@ahemad01/from-jenkins-to-github-actions-a-practical-migration-guide-with-ssh-vs-ssm-deployment-deep-dive-74ab1c9c08cb?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ab1c9c08cb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 05:01:55 GMT</pubDate>
            <atom:updated>2026-04-17T05:01:55.415Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By a DevOps engineer who has actually done this — not just read about it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P91mD5rdVJpW8kkvex1EOA.png" /></figure><h3>Why CI/CD Still Matters (And Why Your Tooling Choice Does Too)</h3><p>CI/CD isn’t a nice-to-have anymore. If your team is still manually SSHing into servers to deploy code, you’re one bad day away from a production incident you could have avoided. But here’s the thing — not all CI/CD pipelines are equal. The tool you pick shapes your developer experience, your security posture, and how much of your Friday night you spend babysitting a broken build server.</p><p>For years, Jenkins was the default answer. It was powerful, flexible, and had plugins for everything. If you could dream it, Jenkins could (probably) do it. But “powerful and flexible” often became “bloated and fragile,” and suddenly your Jenkins master was a snowflake server that nobody wanted to touch.</p><p>Enter GitHub Actions. Launched in 2018 and now battle-tested at scale, it has quietly eaten Jenkins’ lunch for most cloud-native teams. This post is for the mid-level dev or DevOps engineer staring at a 500-line Jenkinsfile thinking, <em>“there has to be a better way.”</em></p><p>There is.</p><h3>Jenkins vs GitHub Actions: The Real Comparison</h3><h3>Setup &amp; Maintenance</h3><p><strong>Jenkins</strong> requires you to provision a server, install Java, manage the Jenkins process, handle updates, install plugins, and then watch those plugins conflict with each other on a Tuesday morning. The initial setup alone can take a day. Ongoing maintenance is a hidden tax on your team.</p><p><strong>GitHub Actions</strong> is fully managed. You push a YAML file to .github/workflows/ and you&#39;re running pipelines. There&#39;s no server to babysit.</p><h3>Scalability</h3><p>With Jenkins, scaling means either buying more hardware or setting up a distributed master/agent architecture — both of which require manual configuration and ongoing management.</p><p>GitHub Actions auto-scales. Microsoft/GitHub handles the runner pool. You just pay for what you use (or use free minutes on public repos).</p><h3>Security</h3><p>This is where Jenkins shows its age most painfully. Credentials are stored in Jenkins’ internal credential store, your Jenkins URL is exposed to the internet, and rotating secrets means hunting through pipeline configs.</p><p>GitHub Actions supports <strong>OIDC (OpenID Connect)</strong> — which means you can authenticate to AWS, GCP, or Azure without storing long-lived credentials anywhere. No secrets. No rotation headaches. This alone is worth the migration for teams on AWS.</p><h3>Ecosystem</h3><p>Jenkins has 1,800+ plugins. That sounds impressive until three of them break simultaneously after an update.</p><p>GitHub Actions has a marketplace with 20,000+ actions. They’re versioned, composable, and you can pin them to a specific SHA. Much safer dependency model.</p><h3>Developer Experience</h3><p>Jenkins’ Blue Ocean UI was a step forward, but it still feels like a product from 2015. Logs are clunky. Debugging a failed step means scrolling through walls of text.</p><p>GitHub Actions lives inside GitHub. Your PR shows the workflow status inline. Logs are structured and searchable. Developers don’t need to context-switch to a separate tool.</p><h3>Cost</h3><p>Jenkins looks “free” until you factor in: EC2 instance costs, engineer time maintaining the server, plugin debugging hours, and the opportunity cost of not shipping features. For most teams, GitHub Actions ends up cheaper when you account for total cost of ownership.</p><h3>Comparison Table</h3><p>Factor Jenkins GitHub Actions Setup Time Hours to days Minutes Maintenance High (your problem) Low (managed) Scalability Manual Auto Security Credential-based OIDC-capable Debug Experience Painful Good Cost Model Infra + time Usage-based Plugin Ecosystem 1,800+ (fragile) 20,000+ (stable) GitHub Integration Plugin required Native</p><h3>When Should You Still Use Jenkins?</h3><p>Let’s be honest — Jenkins isn’t always wrong.</p><ul><li><strong>You’re fully on-premises</strong> with no plans to move to cloud. GitHub Actions requires outbound internet access; Jenkins can run completely air-gapped.</li><li><strong>You have complex, legacy pipelines</strong> with 5 years of accumulated logic that would take months to rewrite safely.</li><li><strong>Regulatory requirements</strong> mandate that your CI/CD infrastructure lives inside your own network.</li></ul><p>In these cases, stick with Jenkins. But if you don’t have one of these hard blockers, the migration is almost always worth it.</p><h3>Why Teams Are Migrating</h3><p>The real driver isn’t just features — it’s <strong>cognitive load</strong>. Every time your Jenkins instance goes down, someone has to drop what they’re doing and fix it. Every plugin update is a gamble. Every new developer onboarding asks “why does our CI/CD look like this?”</p><p>GitHub Actions removes that entire category of problem. OIDC removes credential sprawl. Native GitHub integration removes context-switching. The result is a team that ships faster with less friction.</p><h3>Migration Strategy: Jenkins → GitHub Actions</h3><h3>Step 1: Audit Your Jenkins Pipelines</h3><p>Before touching anything, inventory what you have. For each Jenkins job, document:</p><ul><li>What does it do? (build, test, deploy, notify)</li><li>What agents/labels does it use?</li><li>What credentials does it consume?</li><li>What downstream jobs does it trigger?</li><li>How often does it run, and what triggers it?</li></ul><p>Most teams discover jobs that haven’t run in months. Delete those first. They’re noise.</p><h3>Step 2: Decompose Your Jenkinsfile</h3><p>A Jenkins pipeline stage maps roughly to a GitHub Actions job or step. Here’s the mental model:</p><pre>Jenkins Stage  →  GitHub Actions Job (if parallelizable or isolated)<br>Jenkins Step   →  GitHub Actions Step (within a job)<br>Jenkins Agent  →  GitHub Actions Runner (runs-on)</pre><p>If your stages share a workspace and run sequentially, they become steps within a single job. If they can run in parallel, make them separate jobs.</p><h3>Step 3: Migrate Credentials</h3><p>This is the most important step to get right.</p><ul><li><strong>Simple secrets</strong> (API keys, tokens): Move to GitHub Secrets (Settings → Secrets and variables → Actions)</li><li><strong>AWS access</strong>: Set up OIDC instead of access keys. It’s 20 more minutes of setup and eliminates an entire class of security risk.</li></ul><p>Do not just copy your Jenkins credentials into GitHub Secrets and call it done. Use the migration as an opportunity to clean up and consolidate.</p><h3>Step 4: Write the Workflow YAML</h3><p>Here’s a real-world example of a Jenkins → GitHub Actions conversion.</p><p><strong>Jenkinsfile (before):</strong></p><pre>pipeline {<br>  agent any<br>  environment {<br>    APP_ENV = &#39;production&#39;<br>  }<br>  stages {<br>    stage(&#39;Install&#39;) {<br>      steps {<br>        sh &#39;npm ci&#39;<br>      }<br>    }<br>    stage(&#39;Test&#39;) {<br>      steps {<br>        sh &#39;npm test&#39;<br>      }<br>    }<br>    stage(&#39;Build&#39;) {<br>      steps {<br>        sh &#39;npm run build&#39;<br>      }<br>    }<br>    stage(&#39;Deploy&#39;) {<br>      steps {<br>        withCredentials([sshUserPrivateKey(credentialsId: &#39;deploy-key&#39;, keyFileVariable: &#39;SSH_KEY&#39;)]) {<br>          sh &#39;scp -i $SSH_KEY -r ./dist user@server:/var/www/app&#39;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>GitHub Actions Workflow (after):</strong></p><pre>name: Build and Deploy</pre><pre>on:<br>  push:<br>    branches: [main]</pre><pre>permissions:<br>  id-token: write   # Required for OIDC<br>  contents: read</pre><pre>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest</pre><pre>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4</pre><pre>      - name: Setup Node.js<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;20&#39;<br>          cache: &#39;npm&#39;</pre><pre>      - name: Install dependencies<br>        run: npm ci</pre><pre>      - name: Run tests<br>        run: npm test</pre><pre>      - name: Build<br>        run: npm run build</pre><pre>      - name: Configure AWS credentials via OIDC<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy<br>          aws-region: us-east-1</pre><pre>      - name: Deploy via SSM<br>        run: |<br>          aws ssm send-command \<br>            --instance-ids &quot;${{ secrets.EC2_INSTANCE_ID }}&quot; \<br>            --document-name &quot;AWS-RunShellScript&quot; \<br>            --parameters &#39;commands=[&quot;cd /var/www/app &amp;&amp; aws s3 cp s3://my-deploy-bucket/dist.tar.gz . &amp;&amp; tar -xzf dist.tar.gz &amp;&amp; pm2 restart app&quot;]&#39;</pre><p>Notice we went from SSH-based deployment to SSM. More on why in the next section.</p><h3>Step 5: Test and Gradual Rollout</h3><p>Don’t cut over all at once. Run both pipelines in parallel for 1–2 weeks:</p><ol><li>Jenkins remains the “official” pipeline</li><li>GitHub Actions runs on every push but failures don’t block anything</li><li>Compare outputs and deployment outcomes</li><li>Once confident, flip the switch and disable Jenkins jobs one by one</li></ol><h3>Deployment Strategies: SSH vs AWS SSM</h3><h3>SSH-Based Deployment</h3><p>The classic approach: open port 22, store an SSH private key as a secret, use scp to copy files, then ssh to run restart commands.</p><pre>GitHub Actions Runner<br>        |<br>     SSH (port 22)<br>        |<br>      EC2 Instance</pre><p><strong>It works.</strong> For small teams, POC projects, or non-production environments, there’s nothing wrong with this.</p><p><strong>The problems at scale:</strong></p><ul><li>You’re managing SSH keys across multiple instances and pipelines</li><li>Port 22 must be open (either to the world or to GitHub’s IP ranges, which change)</li><li>Key rotation is manual and error-prone</li><li>Every new EC2 instance needs the public key installed</li></ul><h3>SSM-Based Deployment (The Modern Way)</h3><p>AWS Systems Manager lets you run commands on EC2 instances without SSH. No open ports. No keys. Just IAM.</p><pre>GitHub Actions<br>      |<br>   OIDC Token<br>      |<br> AWS IAM Role (assumed)<br>      |<br>  SSM API Call<br>      |<br> SSM Agent (on EC2)<br>      |<br>  Command Executes</pre><p>The EC2 instance only needs:</p><ol><li>The SSM agent installed (comes pre-installed on Amazon Linux 2/2023 and recent Ubuntu AMIs)</li><li>An instance profile with AmazonSSMManagedInstanceCore policy attached</li></ol><p>Your security group can have <strong>zero inbound rules</strong>. No port 22. No exposure.</p><p><strong>The trade-off:</strong> Initial setup is more involved. You need to configure OIDC trust policies, IAM roles, and instance profiles correctly. Budget an hour for this the first time.</p><h3>SSH vs SSM: Which Should You Use?</h3><p>Factor SSH SSM Security ❌ Open ports required ✅ Zero inbound ports Initial Setup ✅ Simple ❌ IAM/OIDC config needed Key Management ❌ Manual, error-prone ✅ None required Scalability ❌ Per-instance key setup ✅ IAM role applies to all Auditability ❌ Limited ✅ Full CloudTrail logs AWS Dependency ✅ None ❌ AWS only</p><p><strong>Recommendation:</strong></p><ul><li><strong>POC / personal projects / non-AWS</strong>: SSH is fine. Don’t over-engineer it.</li><li><strong>Production / AWS / team environments</strong>: Use SSM. The setup cost is a one-time investment. The security and operational benefits compound forever.</li></ul><h3>The Modern Deployment Pipeline (What You Should Be Building)</h3><p>Here’s the full end-to-end flow for a production deployment in 2024:</p><pre>Developer pushes to main<br>          |<br>  GitHub Actions triggers<br>          |<br>  OIDC token requested from GitHub<br>          |<br>  AWS STS assumes IAM role<br>          |<br>  Build artifacts uploaded to S3 (or image pushed to ECR)<br>          |<br>  SSM send-command dispatched to EC2<br>          |<br>  EC2 pulls artifact from S3 (or pulls image from ECR)<br>          |<br>  Application restarts</pre><p><strong>A note on artifacts:</strong> Some teams still deploy by tarring up the build folder and SCP-ing it to the server. If you’re on AWS, stop doing this. Upload to S3, then pull from the instance. It’s faster, auditable, and you get versioning for free.</p><p>If you’re containerized, push to ECR and pull on the instance (or use ECS/EKS and skip SSM entirely). The tar-file-over-SSH pattern is a relic.</p><h3>Common Pitfalls During Migration</h3><p>These are mistakes I’ve seen (and made) in real migrations:</p><p><strong>1. Incorrect OIDC trust policy</strong> The trust policy on your IAM role must match GitHub’s OIDC provider URL exactly, including the sub claim format (repo:owner/repo:ref:refs/heads/main). One typo and you get a silent auth failure with a cryptic error.</p><p><strong>2. Forgetting </strong><strong>id-token: write permission</strong> GitHub Actions requires you to explicitly grant id-token: write permission in your workflow for OIDC to work. This trips up everyone the first time.</p><p><strong>3. SSM command never completes</strong> SSM commands run asynchronously. If you just fire send-command and exit, your workflow will succeed even if the deployment failed. Always poll for completion with aws ssm wait command-executed and check the exit code.</p><p><strong>4. Secrets scope confusion</strong> GitHub Secrets set at the organization level, repository level, and environment level can conflict. Be explicit about where secrets live and use environments for production-specific values.</p><p><strong>5. YAML indentation errors</strong> GitHub Actions YAML is unforgiving. Use a linter locally (actionlint is excellent) before pushing. A missing space can cost you 10 minutes of debugging.</p><h3>Closing Thoughts</h3><p>Jenkins is powerful, battle-tested, and still the right tool for specific situations. But for most teams building on the cloud today, it feels like driving a truck to pick up groceries. It’ll get the job done, but you’ll spend more time managing the truck than moving the groceries.</p><p>GitHub Actions with OIDC authentication and SSM-based deployment is the combination that makes your pipeline both simpler and more secure — not a trade-off you often get to make.</p><p>The migration isn’t trivial, but it’s absolutely manageable in a phased approach. Start with your simplest pipeline, get it working end-to-end in GitHub Actions, and build confidence before touching the critical paths.</p><p>The payoff: less maintenance overhead, better security, and developers who actually understand how your CI/CD works — because it’s just a YAML file sitting next to their code.</p><p><em>Have you migrated from Jenkins to GitHub Actions? I’d love to hear what surprised you — comment below.</em></p><p><em>#DevOps #CI/CD #GitHubActions #Jenkins #AWS #CloudNative #SSM #OIDC #SoftwareEngineering #Platform</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ab1c9c08cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 90% Heist: Reimagining the Foundation of the Cloud]]></title>
            <link>https://medium.com/@ahemad01/the-90-heist-reimagining-the-foundation-of-the-cloud-ffbe0894c8ba?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffbe0894c8ba</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[infrastructure-cost]]></category>
            <category><![CDATA[kubernetes-cost-saving]]></category>
            <category><![CDATA[spot-instances]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 08:58:30 GMT</pubDate>
            <atom:updated>2026-04-09T11:15:34.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RKsr2IoMQ9hmXiKLxEcQQ.png" /></figure><p><em>AWS Kubernetes · Karpenter · EventBridge · Spot Instances · Cost Engineering</em></p><h3>The Bill That Changed Everything</h3><p>It was a Tuesday morning when our infrastructure lead pulled up the AWS cost dashboard and went quiet for a long moment.</p><p>The number staring back at him wasn’t catastrophic. It wasn’t even unusual. That was the problem. Month after month, the same quiet drain: thousands of dollars flowing out to sustain development environments that sat mostly idle — running overnight, through weekends, through long meetings — burning money while no one was watching.</p><p>“We’re paying for uptime we don’t need,” he said, “to protect ourselves from an interruption that almost never comes.”</p><p>That sentence started everything.</p><h3>The Stability Tax — And Why You’re Probably Paying It</h3><p>Here is a pattern that plays out in almost every engineering organisation that runs on AWS.</p><p>You need a development environment. You need it to be reliable. Someone — quite reasonably — provisions On-Demand EC2 instances. They’re always available. They never disappear. They feel safe.</p><p>And then you get the bill.</p><p>On-Demand pricing is AWS’s full retail price. You pay it 24 hours a day, 7 days a week, whether your engineers are actively working or not. You pay it on bank holidays. You pay it at 3am. You pay it for the 14 hours between when your last engineer commits code on Friday evening and when the first one opens their laptop on Monday morning.</p><p>This is what we call the <strong>Stability Tax</strong> — the premium you pay not for performance, not for features, but purely for the psychological comfort of knowing the lights will stay on.</p><p>The cruel irony is that for development environments — which are, by design, places where things break, get rebuilt, and get tested — the premium is entirely unnecessary. You are paying for production-grade permanence in an environment whose entire purpose is impermanence.</p><p>There is a better way. But to understand it, you first need to understand what you’ve been avoiding.</p><h3>The Thing You’ve Been Afraid Of: Spot Instances</h3><p>AWS runs one of the largest computing fleets on the planet. At any given moment, enormous portions of that fleet sit unused — spare capacity waiting for on-demand requests that may or may not come.</p><p>Rather than let it idle, AWS sells this spare capacity as <strong>Spot Instances</strong> — the same hardware, the same network, the same performance as an On-Demand instance, at a discount that typically ranges from <strong>60% to 90% below the standard price</strong>.</p><p>The catch, the one that makes most architects nervous, is this: AWS can reclaim a Spot Instance at any time. When demand rises and that capacity is needed elsewhere, AWS issues a <strong>Rebalance Recommendation</strong> — a 120-second warning — and then reclaims the instance.</p><p>To the conventional architect, this sounds like a liability. An unpredictable interruption. A risk not worth taking.</p><p>To us, it sounded like an engineering problem worth solving.</p><p>Because here is the thing about a 120-second warning: <strong>120 seconds is a very long time in Kubernetes.</strong></p><h3>What You Need Before You Start</h3><p>Before we get into the architecture, let’s be honest about the prerequisites. This approach works cleanly for <strong>stateless workloads</strong> — APIs, microservices, build agents, test runners, background workers. If you have stateful workloads (databases, message queues, anything writing to local disk), you’ll need PodDisruptionBudgets, persistent volume strategies, and more care before Spot is safe for them.</p><p>To implement this yourself, you’ll need:</p><ul><li>An existing <strong>EKS cluster</strong> (or the ability to create one)</li><li><strong>Karpenter</strong> installed as your node autoscaler (replacing or alongside Cluster Autoscaler)</li><li><strong>Amazon EventBridge</strong> configured with a rule for EC2 Spot Rebalance events</li><li>Workloads designed with <strong>graceful shutdown hooks</strong> — the application must be able to stop cleanly when Kubernetes sends a SIGTERM</li></ul><p>If your applications crash rather than shut down gracefully when terminated, fix that first. Everything else follows.</p><h3>The Architecture: A System Built to Embrace Interruption</h3><p>The Spot-Vacuum Architecture has four core components working in concert. Understanding each one is essential before understanding how they fit together.</p><h3>Component 1 — AWS EC2 Spot Capacity</h3><p>Spot Instances are sourced from AWS’s live capacity pool. You request them through a <strong>NodePool</strong> in Karpenter, specifying instance families, sizes, and a capacity type of spot. Karpenter handles the bidding and provisioning transparently.</p><p>The most important thing to understand about Spot capacity is that interruptions are <strong>not random</strong> — they follow patterns tied to time of day, region, and instance family. Certain instance families (m5, m5a, m5d across multiple sizes) have very low interruption rates. Tools like the <a href="https://aws.amazon.com/ec2/spot/instance-advisor/">AWS Spot Instance Advisor</a> show you historical interruption frequency by type, and you should consult it when designing your NodePool.</p><h3>Component 2 — Amazon EventBridge: The Early Warning System</h3><p>AWS publishes two distinct signals before a Spot Instance is reclaimed:</p><ul><li><strong>EC2 Spot Instance Interruption Warning</strong> — published 2 minutes before termination, when AWS has definitively decided to reclaim the instance.</li><li><strong>EC2 Instance Rebalance Recommendation</strong> — published earlier and with no guaranteed timing, when AWS detects that an instance is at <em>elevated risk</em> of interruption.</li></ul><p>The Rebalance Recommendation is the one that matters most. It arrives before the final decision is made, giving you maximum lead time to act. An EventBridge rule with the following event pattern catches it:</p><pre>{<br>  &quot;source&quot;: [&quot;aws.ec2&quot;],<br>  &quot;detail-type&quot;: [&quot;EC2 Instance Rebalance Recommendation&quot;]<br>}</pre><p>When this event fires, EventBridge fans it out to two targets simultaneously: your notification system and Karpenter.</p><h3>Component 3 — Karpenter: The Node Conductor</h3><p>Karpenter is an open-source, CNCF-graduated Kubernetes node autoscaler originally developed at AWS. Unlike the older Cluster Autoscaler — which reacts to pending pods — Karpenter proactively manages the lifecycle of nodes in response to events.</p><p>When Karpenter receives the EventBridge signal, it doesn’t wait. It immediately provisions a <strong>new Spot node</strong> from your NodePool specification, scheduling it to be ready before the old node is expected to disappear. This is the key insight of the whole architecture: <strong>the new node comes up before the old one goes down</strong>.</p><p>A minimal Karpenter NodePool for this pattern looks like this:</p><pre>apiVersion: karpenter.sh/v1<br>kind: NodePool<br>metadata:<br>  name: spot-dev<br>spec:<br>  template:<br>    spec:<br>      requirements:<br>        - key: karpenter.sh/capacity-type<br>          operator: In<br>          values: [&quot;spot&quot;]<br>        - key: node.kubernetes.io/instance-type<br>          operator: In<br>          values: [&quot;m5.large&quot;, &quot;m5.xlarge&quot;, &quot;m5a.large&quot;, &quot;m5a.xlarge&quot;]<br>      nodeClassRef:<br>        apiVersion: karpenter.k8s.aws/v1<br>        kind: EC2NodeClass<br>        name: default<br>  disruption:<br>    consolidationPolicy: WhenEmptyOrUnderutilized<br>    consolidateAfter: 30s</pre><h3>Component 4 — The Vacuum Pattern: Cordon, Drain, Terminate</h3><p>This is the sequence that runs inside the cluster once the new node is ready. We call it the <strong>Vacuum</strong> because it pulls the workloads out of the old node cleanly, like air from a sealed chamber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sX7RkFOVx-2tY7ckVcnQYw.png" /></figure><p><strong>Cordon</strong> marks the node as unschedulable. No new pods will be placed there. Existing pods continue running.</p><p><strong>Drain</strong> evicts the pods using Kubernetes’ graceful termination protocol. Each pod receives a SIGTERM, waits for its terminationGracePeriodSeconds, and shuts down cleanly. The scheduler immediately places them on the new node. For applications with proper shutdown hooks, this is invisible to users.</p><p><strong>Terminate</strong> removes the old node from the cluster entirely. AWS reclaims the instance. The cluster is whole again — same workloads, new hardware, fraction of the cost.</p><h3>The Full Flow: A Sequence Diagram</h3><p>Here’s the complete lifecycle of a single Spot interruption event, from signal to resolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTqzA7_YStKENB4e11hs1Q.png" /></figure><p>The team receives an alert not because something broke — but because a <strong>migration of value</strong> is occurring. This reframing matters. Instead of a failure notification, it’s an operational heartbeat. Your engineers know the system is working exactly as designed.</p><h3>The Numbers: What This Actually Saves</h3><p>Let’s make the savings concrete. Consider a modest development environment: five m5.xlarge instances running a microservices platform.</p><p>Pricing Model Hourly Rate Monthly Cost (730 hrs) On-Demand $0.192/hr × 5 = $0.96/hr <strong>$700/month</strong> Spot (avg 70% discount) $0.058/hr × 5 = $0.29/hr <strong>$210/month</strong> Spot + scheduled scale-down (12hr/day) — <strong>~$105/month</strong></p><p>For a team running a larger environment — 10 nodes, bigger instance types — the differential grows quickly. At the $5,000/month On-Demand level, Spot brings you to $500–$1,500/month depending on the instance mix and region.</p><p>Across a full year, that’s the cost of an engineer’s salary returned to your budget.</p><h3>The Hidden Dividend: Resilience by Design</h3><p>Cost savings are the headline. But there’s a second return on this investment that is harder to put a number on.</p><p>When you build your system to survive a Spot interruption, you are forced to do things you should have been doing anyway:</p><p><strong>Graceful shutdown hooks</strong> — your applications must handle SIGTERM cleanly. This means they also handle deployments, scaling events, and rolling restarts cleanly. You fix subtle bugs you didn’t know you had.</p><p><strong>PodDisruptionBudgets</strong> — to ensure at least N replicas of a service survive a drain, you must define PDBs. This gives your cluster a documented contract for availability during any disruption, not just Spot reclamation.</p><p><strong>Stateless pod design</strong> — anything that writes critical data to a local volume will lose it on a Spot interruption. Addressing this forces proper persistent volume usage and external state management.</p><p><strong>Multi-AZ node placement</strong> — spreading your NodePool across availability zones reduces the blast radius of any single Spot capacity pool running dry.</p><p>Each of these is a best practice that most teams intend to implement eventually. Spot forces you to implement them now, in your development environment, where the cost of discovering failures is low. By the time a workload reaches production, it has already survived dozens of interruptions. It is hardened.</p><p>This is not frugality disguised as engineering. It is engineering that happens to be extremely frugal.</p><h3>What This Approach Does Not Cover</h3><p>Honesty matters here. The Spot-Vacuum pattern is not a universal solution.</p><p><strong>Stateful production databases</strong> running on Spot without careful planning are dangerous. A Spot reclamation mid-write, before proper flushing, can corrupt data. Use managed services (RDS, ElastiCache, DynamoDB) for stateful production data, and reserve Spot for the compute layer.</p><p><strong>Long-running batch jobs</strong> need checkpointing. If a two-hour ML training run is interrupted at the 110-minute mark and has no checkpoint strategy, you lose everything. Tools like AWS Batch with Spot support handle this natively, but it requires deliberate design.</p><p><strong>Extremely latency-sensitive services</strong> where even a graceful 30-second pod reschedule is unacceptable need On-Demand nodes or, better, a Karpenter mixed-capacity strategy — Spot for most nodes, On-Demand for a small baseline that holds your most critical, latency-sensitive pods.</p><p>Karpenter supports all of these configurations. The architecture scales to nuance.</p><h3>Getting Started: The Minimal Implementation</h3><p>If you have an EKS cluster and want to try this today, here is the minimum viable implementation:</p><p><strong>Step 1 — Install Karpenter</strong> following the <a href="https://karpenter.sh/docs/getting-started/">official guide</a>. Configure your EC2NodeClass with the appropriate subnet and security group selectors.</p><p><strong>Step 2 — Create a Spot NodePool</strong> using the YAML above. Start with a diverse set of instance families to maximise available capacity.</p><p><strong>Step 3 — Create an EventBridge rule</strong> that matches EC2 Instance Rebalance Recommendation events and targets an SNS topic or Lambda function that calls kubectl cordon and kubectl drain on the affected node.</p><p><strong>Step 4 — Add PodDisruptionBudgets</strong> to your critical workloads:</p><pre>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: api-pdb<br>spec:<br>  minAvailable: 1<br>  selector:<br>    matchLabels:<br>      app: api</pre><p><strong>Step 5 — Test it</strong>. Manually cordon and drain a node. Watch your pods reschedule. Fix anything that doesn’t recover cleanly. Then switch your NodePool to Spot and let it run for a week.</p><p>The first time a Spot interruption comes — and it will come — and your team gets an alert and looks at the dashboard and sees everything still green, still running, still serving — that is the moment the architecture proves itself.</p><h3>Architecture Stack</h3><pre>Kubernetes (EKS)<br>  └── Karpenter          — node lifecycle and Spot provisioning<br>  └── PodDisruptionBudgets — availability contracts during disruption</pre><pre>AWS<br>  └── EC2 Spot Instances — 60–90% below On-Demand pricing<br>  └── Amazon EventBridge — Rebalance Recommendation event routing<br>  └── SNS / SES          — alert delivery (Slack via webhook or email)</pre><h3>The New Standard</h3><p>The industry has spent years telling you that reliability requires permanence. That if you want something to stay up, you must pay for something that never goes away.</p><p>That framing was always a product of fear, not engineering.</p><p>The cloud is not a static thing. It is a living, shifting pool of capacity, and the engineers who learn to move <em>with</em> it — rather than against it — are the ones who build systems that are simultaneously cheaper and more robust than anything built on the fiction of permanence.</p><p>Stop paying the Stability Tax.</p><p>Build for the flow.</p><p><em>Architecture: AWS EKS + Karpenter + EventBridge + EC2 Spot + PodDisruptionBudgets</em></p><p><em>The Vacuum Pattern — interruption-driven node lifecycle management for cost-efficient, resilient Kubernetes infrastructure.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffbe0894c8ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foreign Data Wrapper (FDW) in PostgreSQL: A Beginner-Friendly Guide]]></title>
            <link>https://medium.com/@ahemad01/foreign-data-wrapper-fdw-in-postgresql-a-beginner-friendly-guide-d9da0c00877a?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9da0c00877a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[advance-sql]]></category>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 13:04:42 GMT</pubDate>
            <atom:updated>2025-12-17T13:04:42.595Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern applications, data is rarely stored in a single database. Often, teams need to read data from multiple databases, different PostgreSQL instances, or even other systems like MySQL, Oracle, or CSV files. Copying data between systems is one option — but it introduces complexity, duplication, and synchronization issues.</p><p>PostgreSQL solves this problem using <strong>Foreign Data Wrappers (FDW)</strong>.</p><p>This blog explains <strong>what FDW is</strong>, <strong>why it is useful</strong>, and <strong>how to use it step by step</strong>, in a beginner-friendly way.</p><h3>What Is a Foreign Data Wrapper (FDW)?</h3><p>A <strong>Foreign Data Wrapper (FDW)</strong> is a PostgreSQL feature that allows you to <strong>access external data sources as if they were local tables</strong>.</p><p>In simple terms:</p><blockquote><em>FDW lets PostgreSQL query data stored in another database or system without copying it.</em></blockquote><p>To PostgreSQL, foreign data looks just like a normal table — but the data actually lives somewhere else.</p><h3>Why Do We Need FDW?</h3><p>Without FDW, you usually have to:</p><ul><li>Export data from one database</li><li>Transfer it to another system</li><li>Import it into your database</li><li>Keep both systems in sync</li></ul><p>This approach is:</p><ul><li>Error-prone</li><li>Hard to maintain</li><li>Slow for real-time data access</li></ul><p>FDW removes this complexity by letting PostgreSQL query external data <strong>directly</strong>.</p><h3>Real-World Use Cases</h3><p>FDW is commonly used when:</p><ul><li>You need to read data from another PostgreSQL database</li><li>You want to join local tables with remote tables</li><li>You are migrating data gradually from one system to another</li><li>You want read-only access to external systems</li><li>You want to avoid duplicating data</li></ul><h3>Common Types of FDWs</h3><p>PostgreSQL supports many FDWs, including:</p><p>FDW NameData Sourcepostgres_fdwAnother PostgreSQL databasemysql_fdwMySQL / MariaDBoracle_fdwOraclefile_fdwCSV / flat filesmongo_fdwMongoDB</p><p>In this blog, we’ll focus on <strong>postgres_fdw</strong>, the most commonly used FDW.</p><h3>How FDW Works (High-Level Flow)</h3><ol><li>PostgreSQL loads an FDW extension</li><li>You define a <strong>foreign server</strong> (remote database)</li><li>You map a local user to a remote user</li><li>You create <strong>foreign tables</strong></li><li>You query them like normal tables</li></ol><p>PostgreSQL automatically fetches data from the remote source when queries are executed.</p><h3>Step-by-Step: Using postgres_fdw</h3><h3>Step 1: Enable the FDW extension</h3><pre>CREATE EXTENSION postgres_fdw;</pre><p>This command enables FDW support in your database.</p><h3>Step 2: Create a foreign server</h3><pre>CREATE SERVER remote_pg_server<br>FOREIGN DATA WRAPPER postgres_fdw<br>OPTIONS (<br>  host &#39;remote-db-host&#39;,<br>  dbname &#39;remote_database&#39;,<br>  port &#39;5432&#39;<br>);</pre><p>This tells PostgreSQL <strong>where the remote database is located</strong>.</p><h3>Step 3: Create a user mapping</h3><pre>CREATE USER MAPPING FOR local_user<br>SERVER remote_pg_server<br>OPTIONS (<br>  user &#39;remote_user&#39;,<br>  password &#39;remote_password&#39;<br>);</pre><p>This maps a local PostgreSQL user to a remote database user.</p><h3>Step 4: Create a foreign table</h3><pre>CREATE FOREIGN TABLE remote_employees (<br>  id INTEGER,<br>  name TEXT,<br>  department TEXT<br>)<br>SERVER remote_pg_server<br>OPTIONS (<br>  schema_name &#39;public&#39;,<br>  table_name &#39;employees&#39;<br>);</pre><p>This creates a table definition in your local database that points to a remote table.</p><h3>Step 5: Query the foreign table</h3><pre>SELECT * FROM remote_employees;</pre><p>To the user, this looks exactly like querying a local table.</p><h3>Joining Local and Foreign Tables</h3><p>One of FDW’s biggest advantages is the ability to join local and remote data.</p><pre>SELECT e.name, d.department_name<br>FROM remote_employees e<br>JOIN local_departments d<br>ON e.department = d.code;</pre><p>PostgreSQL handles data fetching automatically.</p><h3>Performance Considerations</h3><p>FDW is powerful, but it’s not magic. Keep these points in mind:</p><ul><li>Network latency affects performance</li><li>Large queries may be slower than local tables</li><li>Use filters (WHERE clause) to reduce data transfer</li><li>Indexes on remote tables still matter</li><li>Avoid SELECT * for large datasets</li></ul><p>PostgreSQL can push filters and joins to the remote server when possible (called <strong>pushdown</strong>).</p><h3>Read-Only vs Read-Write Access</h3><p>Depending on the FDW and configuration:</p><ul><li>Some FDWs are read-only</li><li>postgres_fdw supports INSERT, UPDATE, and DELETE</li><li>Permissions are controlled by the remote database</li></ul><p>Always verify access rights before using FDW for writes.</p><h3>Security Best Practices</h3><ul><li>Use dedicated read-only users for FDW access</li><li>Avoid using superuser credentials</li><li>Secure network connections (VPN, TLS)</li><li>Restrict access to foreign tables via roles</li></ul><h3>When Not to Use FDW</h3><p>FDW may not be ideal when:</p><ul><li>You need extremely low-latency queries</li><li>You frequently query very large datasets</li><li>You need complex transactions across databases</li><li>The remote system is unstable or slow</li></ul><p>In such cases, ETL or replication may be better options.</p><h3>FDW vs ETL vs Replication</h3><h3>Key Takeaways</h3><ul><li>FDW allows PostgreSQL to access external data as tables</li><li>Eliminates data duplication</li><li>Ideal for integrations and gradual migrations</li><li>Easy to set up and powerful when used correctly</li></ul><h3>One-Line Summary</h3><blockquote><strong><em>Foreign Data Wrapper allows PostgreSQL to query external data sources as if they were local tables.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9da0c00877a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Ansible Vault?]]></title>
            <link>https://medium.com/@ahemad01/what-is-ansible-vault-e1ba71d2fd32?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ba71d2fd32</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[devsecops-tool]]></category>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 12:52:56 GMT</pubDate>
            <atom:updated>2025-12-17T12:55:03.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HaN894N7GhuEFRBp.JPG" /></figure><p><strong>Ansible Vault</strong> is a built-in feature of Ansible that allows you to <strong>encrypt sensitive data</strong> within your Ansible files. It enables teams to securely store secrets while still benefiting from automation and version control.</p><p>Key characteristics of Ansible Vault include:</p><ul><li>Built directly into Ansible (no extra installation required)</li><li>Encrypts files or variables containing sensitive data</li><li>Allows encrypted files to be safely stored in Git repositories</li><li>Requires a password (or key) to decrypt secrets at runtime</li></ul><p>With Ansible Vault, sensitive information is protected without breaking your automation workflows.</p><h3>A Simple Analogy to Understand Ansible Vault</h3><p>Think of Ansible Vault as a <strong>locked suitcase</strong>:</p><ul><li>The encrypted file is the suitcase</li><li>The vault password is the key</li></ul><p>Anyone can see the suitcase (the encrypted file in Git), but only someone with the key (vault password) can open it and view the contents. Without the password, the secrets remain unreadable.</p><h3>How Ansible Vault Works</h3><p>At a high level, Ansible Vault follows this workflow:</p><ol><li>Create a file that contains sensitive information</li><li>Encrypt the file using Ansible Vault</li><li>Store the encrypted file securely in a Git repository</li><li>Provide the vault password when running the playbook</li><li>Ansible decrypts the secrets <strong>only in memory</strong> during execution</li></ol><p>The decrypted data is never written back to disk in plain text, which significantly reduces the risk of exposure.</p><h3>Basic Ansible Vault Commands</h3><p>Ansible Vault provides simple commands to manage encrypted files.</p><h3>Create an encrypted file</h3><pre>ansible-vault create secrets.yml</pre><h3>View an encrypted file</h3><pre>ansible-vault view secrets.yml</pre><h3>Edit an encrypted file</h3><pre>ansible-vault edit secrets.yml</pre><p>These commands ensure that sensitive data is always handled in an encrypted form.</p><h3>Using Ansible Vault in a Playbook</h3><p>Encrypted files can be easily included in Ansible playbooks using vars_files.</p><pre>- hosts: all<br>  vars_files:<br>    - secrets.yml<br>  tasks:<br>    - name: Example task<br>      debug:<br>        msg: &quot;DB password is {{ db_password }}&quot;</pre><p>Run the playbook by providing the vault password:</p><pre>ansible-playbook playbook.yml --ask-vault-pass</pre><p>At runtime, Ansible decrypts the secrets, uses them during execution, and then discards them from memory.</p><h3>Common Use Cases for Ansible Vault</h3><p>Ansible Vault is commonly used to secure:</p><ul><li>Database credentials</li><li>API tokens</li><li>SSH passwords</li><li>Cloud credentials (AWS, Azure, GCP)</li><li>Kubernetes secrets</li></ul><p>It is especially useful in CI/CD pipelines and infrastructure automation.</p><h3>Best Practices for Using Ansible Vault</h3><p>To use Ansible Vault effectively and securely, follow these best practices:</p><ul><li>Never commit the vault password to Git</li><li>Use a .vault_pass file locally and add it to .gitignore</li><li>Use separate vaults for different environments (Dev, QA, Prod)</li><li>Rotate secrets periodically</li><li>Limit access to vault passwords on a need-to-know basis</li></ul><p>These practices help minimize risk and improve overall security posture.</p><h3>What Ansible Vault Is Not</h3><p>While Ansible Vault is powerful, it is important to understand its limitations. It is <strong>not</strong>:</p><ul><li>A centralized secrets management system</li><li>A UI-based secret management tool</li><li>A solution for automatic secret rotation</li></ul><p>For large-scale or enterprise environments, tools such as <strong>HashiCorp Vault</strong>, <strong>AWS Secrets Manager</strong>, or <strong>Azure Key Vault</strong> may be more suitable.</p><h3>When Should You Use Ansible Vault?</h3><p>Ansible Vault is an excellent choice for:</p><ul><li>Small to medium-sized teams</li><li>Infrastructure automation projects</li><li>CI/CD pipelines</li><li>Configuration management use cases</li></ul><p>It provides a good balance between simplicity and security.</p><h3>Key Takeaways</h3><ul><li>Ansible Vault helps secure sensitive data in automation workflows</li><li>It is simple, built into Ansible, and easy to use</li><li>Encrypted files can safely be stored in Git repositories</li><li>It is ideal for many DevOps and automation scenarios</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ba71d2fd32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Django ORM: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ahemad01/mastering-django-orm-a-comprehensive-guide-ae894d845015?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae894d845015</guid>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 05:58:07 GMT</pubDate>
            <atom:updated>2025-02-11T05:58:07.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Django’s Object-Relational Mapping (ORM) system is a powerful tool that allows developers to interact with databases using Python code instead of writing raw SQL queries. This abstraction simplifies database operations and makes code more readable and maintainable. In this guide, we’ll explore the essentials of Django ORM, providing clear explanations and practical examples to help you master database interactions in your Django applications.</p><h3>1. Defining Models</h3><p>In Django, models are Python classes that represent database tables. Each attribute of the model corresponds to a database field. Defining models is the first step in setting up your database schema.</p><p><strong>Example:</strong></p><pre>from django.db import models<br><br>class Author(models.Model):<br>    first_name = models.CharField(max_length=50)<br>    last_name = models.CharField(max_length=50)<br>    birth_date = models.DateField()<br>class Book(models.Model):<br>    title = models.CharField(max_length=100)<br>    publication_date = models.DateField()<br>    author = models.ForeignKey(Author, on_delete=models.CASCADE)<br>    price = models.DecimalField(max_digits=5, decimal_places=2)</pre><h3>Explanation:</h3><ul><li>The Author model has fields for the author&#39;s first name, last name, and birth date.</li><li>The Book model includes a title, publication date, a foreign key linking to the Author model, and a price.</li></ul><h3>2. Basic QuerySet Operations</h3><p>A QuerySet is a collection of database queries that retrieve objects from your database. You can filter, order, and manipulate these queries to fetch the data you need.</p><h3>Retrieving All Records:</h3><pre>books = Book.objects.all()</pre><h3>Filtering Records:</h3><pre>django_books = Book.objects.filter(title__icontains=&#39;Django&#39;)</pre><h3>Ordering Records:</h3><pre>books_by_date = Book.objects.order_by(&#39;publication_date&#39;)<br>books_by_date_desc = Book.objects.order_by(&#39;-publication_date&#39;)</pre><h3>Limiting Query Results:</h3><pre>first_five_books = Book.objects.all()[:5]</pre><h3>Checking for Existence:</h3><pre>exists = Book.objects.filter(author__last_name=&#39;Smith&#39;).exists()</pre><h3>3. Creating and Updating Records</h3><h3>Creating a Record:</h3><pre>author = Author.objects.create(first_name=&#39;John&#39;, last_name=&#39;Doe&#39;, birth_date=&#39;1980-01-01&#39;)</pre><h3>Updating a Record:</h3><pre>author.last_name = &#39;Smith&#39;<br>author.save()</pre><h3>Bulk Create:</h3><pre>authors = [<br>    Author(first_name=&#39;Alice&#39;, last_name=&#39;Johnson&#39;, birth_date=&#39;1975-05-15&#39;),<br>    Author(first_name=&#39;Bob&#39;, last_name=&#39;Lee&#39;, birth_date=&#39;1982-09-23&#39;),<br>]<br>Author.objects.bulk_create(authors)</pre><h3>Bulk Update:</h3><pre>Book.objects.filter(title__icontains=&#39;Django&#39;).update(price=29.99)</pre><h3>4. Complex Queries with Q Objects</h3><p>For more complex queries involving AND, OR, or NOT conditions, Django provides the Q object.</p><h3>Using Q Objects:</h3><pre>from django.db.models import Q</pre><pre>books = Book.objects.filter(Q(title__icontains=&#39;Django&#39;) | Q(publication_date__year__gt=2020))<br>books = Book.objects.filter(Q(title__icontains=&#39;Django&#39;) &amp; Q(price__lt=30))<br>books = Book.objects.filter(~Q(author__first_name=&#39;John&#39;, author__last_name=&#39;Doe&#39;))</pre><h3>5. Handling Related Objects</h3><p>Django ORM makes it easy to work with related objects through foreign keys and other relationships.</p><h3>Accessing Related Objects:</h3><pre>author = Author.objects.get(first_name=&#39;John&#39;, last_name=&#39;Smith&#39;)<br>books_by_author = author.book_set.all()<br>book = Book.objects.get(title=&#39;Learning Django&#39;)<br>book_author = book.author</pre><h3>Creating Related Objects:</h3><pre>book = Book.objects.create(title=&#39;Advanced Django&#39;, publication_date=&#39;2025-01-15&#39;, author=author)</pre><h3>6. Aggregations and Annotations</h3><p>Django provides aggregation functions to perform calculations on your data, such as counting records or calculating averages.</p><h3>Aggregating Data:</h3><pre>from django.db.models import Count, Avg, Max, Min<br><br>book_count = Book.objects.count()<br>average_price = Book.objects.aggregate(Avg(&#39;price&#39;))<br>price_range = Book.objects.aggregate(max_price=Max(&#39;price&#39;), min_price=Min(&#39;price&#39;))</pre><h3>Annotating Data:</h3><pre>from django.db.models import Count<br><br>authors_with_books = Author.objects.annotate(num_books=Count(&#39;book&#39;))</pre><h3>7. Optimizing Queries with Select Related and Prefetch Related</h3><p>Django ORM provides optimization techniques to reduce database queries and improve performance.</p><h3>Using select_related (for ForeignKey relationships):</h3><pre>books_with_authors = Book.objects.select_related(&#39;author&#39;).all()</pre><h3>Using prefetch_related (for ManyToMany relationships):</h3><pre>authors_with_books = Author.objects.prefetch_related(&#39;book_set&#39;).all()</pre><h3>8. Performing Raw SQL Queries</h3><p>Sometimes, using raw SQL queries can be useful for complex queries that Django ORM does not easily support.</p><h3>Executing Raw SQL:</h3><pre>from django.db import connection<br>with connection.cursor() as cursor:<br>    cursor.execute(&quot;SELECT * FROM myapp_book WHERE price &gt; %s&quot;, [30])<br>    books = cursor.fetchall()</pre><h3>Using raw Method:</h3><pre>books = Book.objects.raw(&quot;SELECT * FROM myapp_book WHERE price &gt; %s&quot;, [30])</pre><h3>Conclusion</h3><p>Django ORM provides a robust and efficient way to interact with databases while keeping your code clean and readable. By mastering basic and advanced QuerySet operations, handling related objects, and optimizing queries, you can build powerful and scalable Django applications. Experiment with these queries in your Django projects to deepen your understanding and improve your efficiency as a developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae894d845015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Pass Messages in the Response Body or Rely on Status Codes? A Detailed Exploration]]></title>
            <link>https://medium.com/@ahemad01/should-you-pass-messages-in-the-response-body-or-rely-on-status-codes-a-detailed-exploration-1293660fe444?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1293660fe444</guid>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 07:11:39 GMT</pubDate>
            <atom:updated>2024-12-11T10:03:59.529Z</atom:updated>
            <content:encoded><![CDATA[<p>In web development, handling responses to client requests is a fundamental part of building robust APIs and web services. The way you structure these responses can significantly impact usability, clarity, and maintenance. Two common approaches are:</p><ol><li><strong>Passing messages in the response body</strong> (e.g., descriptive error or success messages).</li><li><strong>Relying solely on HTTP status codes</strong> (e.g., using 200, 400, 404, etc., to convey the outcome).</li></ol><p>Both approaches have their advantages and disadvantages. In this blog, we’ll explore these two methods, their pros and cons, and suitable use cases for each.</p><h3>What Are HTTP Status Codes?</h3><p>HTTP status codes are standardized three-digit codes used to indicate the outcome of a client’s request to a server. Some commonly used status codes are:</p><ul><li><strong>200 OK</strong>: The request was successful.</li><li><strong>400 Bad Request</strong>: The server could not understand the request due to invalid syntax.</li><li><strong>401 Unauthorized</strong>: Authentication is required or failed.</li><li><strong>404 Not Found</strong>: The server couldn’t find the requested resource.</li><li><strong>500 Internal Server Error</strong>: The server encountered an unexpected condition.</li></ul><p>Status codes provide a quick, machine-readable way of understanding the result of a request.</p><h3>Approach 1: Passing Messages in the Response Body</h3><p>In this approach, the server returns detailed messages in the response body alongside the status code. The message typically provides more context about the result.</p><h3>Example Response:</h3><pre>{<br>    &quot;status&quot;: 400,<br>    &quot;message&quot;: &quot;Invalid email format. Please provide a valid email address.&quot;<br>}</pre><h3>Advantages:</h3><ol><li><strong>Clarity for Users</strong>: Detailed messages give users (or developers consuming the API) a clear understanding of what went wrong and how to fix it.</li><li><strong>Flexibility</strong>: You can provide specific information tailored to the request, such as validation errors or custom error messages.</li><li><strong>Easier Debugging</strong>: Helpful for developers when troubleshooting issues in development or production.</li></ol><h3>Disadvantages:</h3><ol><li><strong>Increased Payload Size</strong>: Including messages increases the size of the response payload, which might be inefficient for high-throughput systems.</li><li><strong>Parsing Complexity</strong>: Clients need to parse the response body to understand the result, which adds complexity to the implementation.</li><li><strong>Consistency Issues</strong>: If not standardized, different endpoints might return different message formats, leading to inconsistency.</li></ol><h3>Use Case:</h3><p><strong>Form Validation in Web Applications</strong></p><p>When a user submits a form with errors, detailed messages help inform them of what needs correction.</p><p><strong>Example:</strong></p><pre>{<br>    &quot;status&quot;: 400,<br>    &quot;message&quot;: &quot;Password must be at least 8 characters long and include a number.&quot;<br>}</pre><h3>Approach 2: Relying Solely on Status Codes</h3><p>In this approach, the response body may be empty or contain minimal information, and the status code itself indicates the result.</p><h3>Example Response:</h3><p><strong>For a successful request:</strong></p><ul><li><strong>Status Code:</strong> 200 OK</li><li><strong>Body:</strong> {}</li></ul><p><strong>For a resource not found:</strong></p><ul><li><strong>Status Code:</strong> 404 Not Found</li><li><strong>Body:</strong> {}</li></ul><h3>Advantages:</h3><ol><li><strong>Simplicity</strong>: Easy to implement and understand. The client only needs to check the status code.</li><li><strong>Efficiency</strong>: Reduces response payload size, making it ideal for performance-critical systems.</li><li><strong>Standardized</strong>: HTTP status codes are well-documented and universally understood.</li></ol><h3>Disadvantages:</h3><ol><li><strong>Lack of Detail</strong>: Status codes alone don’t provide context or guidance on what went wrong or how to fix it.</li><li><strong>Poor User Experience</strong>: End users may see generic errors like “400 Bad Request” without knowing the specific issue.</li><li><strong>Debugging Challenges</strong>: Developers might struggle to debug issues without additional information.</li></ol><h3>Use Case:</h3><p><strong>High-Performance APIs</strong></p><p>In scenarios where performance is critical and the API is consumed by other services (rather than end-users), relying on status codes can be efficient.</p><p><strong>Example:</strong></p><ul><li>A microservice responding with 204 No Content to indicate a no data found.</li></ul><h3>Combining Both Approaches</h3><p>In many cases, a hybrid approach works best. You can rely on status codes for general outcome indications while including optional detailed messages for more complex scenarios.</p><h3>Example Hybrid Response:</h3><pre>{<br>    &quot;status&quot;: 400,<br>    &quot;message&quot;: &quot;Username already exists. Please choose a different username.&quot;<br>}</pre><p>This way, clients can check the status code for quick handling (e.g., retry logic) and optionally parse the message for more context.</p><h3>When to Choose Each Approach</h3><p>Passing Messages in the Response Body Use when detailed feedback is required for end-users, such as form validation errors or specific issue explanations in user-facing applications.</p><p>Relying Solely on Status Codes Use for performance-critical APIs or when communicating between services, where minimal payload and simplicity are more important than detailed messages.</p><p>Hybrid Approach Use when you need quick status checks with optional detailed context, combining the efficiency of status codes with the clarity of response messages.</p><h3>Conclusion</h3><p>Choosing between passing messages in the response body or relying on status codes depends on the context of your application. For user-facing applications, detailed messages improve clarity and user experience. For performance-critical APIs or machine-to-machine communication, status codes might be sufficient.</p><p>In practice, a combination of both approaches often offers the best of both worlds: quick status code checks for general outcomes and detailed messages when more context is needed. By carefully considering your use case, you can design API responses that are both efficient and user-friendly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1293660fe444" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Data Encryption in Django Using Custom Fields]]></title>
            <link>https://medium.com/@ahemad01/user-data-encryption-in-django-using-custom-fields-7ede73c43e65?source=rss-f5d0fa99d25f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ede73c43e65</guid>
            <dc:creator><![CDATA[Ahemad]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 06:55:30 GMT</pubDate>
            <atom:updated>2024-12-11T06:55:30.601Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital landscape, protecting sensitive user data is more critical than ever. Django, a popular web framework, offers robust security features out of the box. However, when it comes to encrypting specific user data fields in the database, developers may need to implement custom solutions. One effective approach is to use Django’s <strong>custom fields</strong> to handle data encryption and decryption seamlessly.</p><p>In this blog, we’ll explore how to implement user data encryption in Django by creating a custom field for encryption using AES encryption.</p><h3>Why Encrypt User Data?</h3><p>Storing sensitive data, such as email addresses, phone numbers, or personal identification information (PII), in plain text can make your application vulnerable to data breaches. Encrypting user data at rest (i.e., in the database) ensures that even if the database is compromised, the data remains protected and unreadable to unauthorized parties.</p><h3>Common Use Cases for Data Encryption</h3><ul><li><em>Email addresses</em></li><li><em>Phone numbers</em></li><li><em>Payment details</em></li></ul><h3>Creating a Custom Encrypted Field with AES Encryption</h3><p>To encrypt and decrypt data seamlessly in Django models, we can create a <strong>custom model field</strong>. This field will handle encryption when saving data to the database and decryption when retrieving data. We’ll use AES encryption from the cryptography library.</p><h3>Step 1: Install Dependencies</h3><p>We’ll use the cryptography library to handle the encryption and decryption process. If you haven&#39;t installed it yet, you can do so with pip:</p><pre>pip install cryptography</pre><h3>Step 2: Create a Common Function for Encryption and Decryption</h3><p>Create a new file called utils.py in your Django app directory. This file will contain functions to handle AES encryption and decryption.</p><p><strong>utils.py</strong>:</p><pre>from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes<br>from cryptography.hazmat.backends import default_backend<br>import base64<br>import os<br><br># Replace this with a securely generated key<br>SECRET_KEY = b&#39;my-super-secret-key-change-this-to-32-bytes&#39;  # AES-256 requires a 32-byte key<br><br><br>def encrypt_data(plain_text):<br>    &quot;&quot;&quot;<br>    Encrypt the plain text using AES encryption.<br>    &quot;&quot;&quot;<br>    if not plain_text:<br>        return None<br>    iv = os.urandom(16)  # AES block size is 16 bytes<br>    cipher = Cipher(algorithms.AES(SECRET_KEY), modes.CFB(iv), backend=default_backend())<br>    encryptor = cipher.encryptor()<br>    encrypted_data = encryptor.update(plain_text.encode()) + encryptor.finalize()<br>    return base64.urlsafe_b64encode(iv + encrypted_data).decode()<br><br><br>def decrypt_data(encrypted_text):<br>    &quot;&quot;&quot;<br>    Decrypt the encrypted text using AES encryption.<br>    &quot;&quot;&quot;<br>    if not encrypted_text:<br>        return None<br>    encrypted_text_bytes = base64.urlsafe_b64decode(encrypted_text)<br>    iv = encrypted_text_bytes[:16]<br>    cipher = Cipher(algorithms.AES(SECRET_KEY), modes.CFB(iv), backend=default_backend())<br>    decryptor = cipher.decryptor()<br>    decrypted_data = decryptor.update(encrypted_text_bytes[16:]) + decryptor.finalize()<br>    return decrypted_data.decode()</pre><h3>Step 3: Create an Encrypted Field</h3><p>Now, create a new file called fields.py in your Django app directory. This file will contain our custom EncryptedField class.</p><p><strong>fields.py</strong>:</p><pre>from django.db import models<br>from .utils import encrypt_data, decrypt_data<br><br>class EncryptedField(models.TextField):<br>    &quot;&quot;&quot;<br>    A custom Django model field for encrypting and decrypting data using AES.<br>    &quot;&quot;&quot;<br><br>    def from_db_value(self, value, expression, connection):<br>        &quot;&quot;&quot;<br>        Decrypt the value when reading from the database.<br>        &quot;&quot;&quot;<br>        if value is None:<br>            return value<br>        return decrypt_data(value)<br><br>    def get_prep_value(self, value):<br>        &quot;&quot;&quot;<br>        Encrypt the value before saving it to the database.<br>        &quot;&quot;&quot;<br>        if value is None:<br>            return value<br>        return encrypt_data(value)</pre><h3>Step 4: Use the Encrypted Field in a Model</h3><p>Now, let’s use our custom EncryptedField in a Django model.</p><p><strong>models.py</strong>:</p><pre>from django.db import models<br>from .fields import EncryptedField<br><br>class UserProfile(models.Model):<br>    name = models.CharField(max_length=255)<br>    email = EncryptedField()<br>    phone_number = EncryptedField()<br><br>    def __str__(self):<br>        return self.name</pre><h3>Step 5: Create and Apply Migrations</h3><p>After defining the model, run the following commands to create and apply the database migrations:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><h3>Step 6: Using the Encrypted Field</h3><p>You can now create and retrieve user profiles with encrypted fields. Here’s an example in the Django shell:</p><pre>python manage.py shell---Use that command in terminal<br><br>from myapp.models import UserProfile<br><br># Create a new user profile<br>profile = UserProfile.objects.create(name=&quot;John Doe&quot;, email=&quot;john@example.com&quot;, phone_number=&quot;1234567890&quot;)<br>profile.save()<br><br># Retrieve the profile<br>retrieved_profile = UserProfile.objects.get(name=&quot;John Doe&quot;)<br>print(retrieved_profile.email) </pre><h3>Security Considerations</h3><ol><li><strong>Key Management</strong>: Store the encryption key securely, such as in environment variables or a secrets management tool.</li><li><strong>Performance</strong>: Encrypting and decrypting data adds overhead, so use encrypted fields only for sensitive data.</li><li><strong>Data Backup</strong>: Ensure you have a secure backup strategy since encrypted data cannot be recovered without the key.</li></ol><h3>Conclusion</h3><p>By using Django’s custom fields and AES encryption, you can efficiently encrypt and decrypt sensitive user data. This approach helps ensure that even if your database is compromised, sensitive information remains protected. Always remember to handle encryption keys securely and carefully consider the performance implications of encrypting large amounts of data.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ede73c43e65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>