<?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"><channel><title><![CDATA[Devang Tomar Senior Software engineer at SAP]]></title><description><![CDATA[👨‍💻 Creative Software Engineer with 7 years of experience in domains including Software development, CI/CD, Networking, Cloud computing.]]></description><link>https://devangtomar.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1733662593386/a6b2788d-d518-466d-bf28-aefa0c619f2e.png</url><title>Devang Tomar Senior Software engineer at SAP</title><link>https://devangtomar.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 02:14:14 GMT</lastBuildDate><atom:link href="https://devangtomar.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The Secret Cost of Microservices: Why Your ‘Scalable’ Architecture is Draining Engineering Morale…]]></title><description><![CDATA[🔄 “We migrated to microservices for agility!”📈 “Our system scales infinitely now!”⚙️ “Every team owns their services independently!” Then why is your…]]></description><link>https://devangtomar.hashnode.dev/the-secret-cost-of-microservices-why-your-scalable-architecture-is-draining-engineering-morale</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/the-secret-cost-of-microservices-why-your-scalable-architecture-is-draining-engineering-morale</guid><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 06 Apr 2025 08:42:17 GMT</pubDate><content:encoded><![CDATA[<hr />
<h3 id="heading-the-hidden-human-toll-of-distributed-systems">The Hidden Human Toll of Distributed Systems</h3>
<p>🔄 <em>“We migrated to microservices for agility!”</em><br />📈 <em>“Our system scales infinitely now!”</em><br />⚙️ <em>“Every team owns their services independently!”</em></p>
<p>Then why is your engineering team burned out and your velocity slowing down?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743929114695/53042644-71f7-496e-b2b6-6bd64f5b2c3b.png" alt /></p>
<p>After working with dozens of companies that adopted microservices, I’ve discovered an uncomfortable truth: <strong>Most microservice implementations create more problems than they solve</strong>. Here’s how your “modern” architecture might be sabotaging your team.</p>
<h3 id="heading-1-the-myth-of-independent-development">1. The Myth of Independent Development</h3>
<h4 id="heading-the-promise-vs-reality">The Promise vs Reality</h4>
<p>Promised BenefitActual Outcome”Teams can deploy independently””We need 5 services to release one feature””No more coordination!””Daily cross-team syncs for API changes””Faster iteration!””Spend 80% time debugging distributed systems”</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743929116151/1c83cced-0dce-4027-88bc-b61b5fce5222.jpeg" alt /></p>
<p><strong>Case Study:</strong> A mid-sized company adopted microservices and saw:</p>
<ul>
<li><p>40% increase in deployment frequency…</p>
</li>
<li><p>But <strong>3x longer feature development cycles</strong> due to coordination overhead</p>
</li>
</ul>
<h3 id="heading-2-the-5-silent-productivity-killers">2. The 5 Silent Productivity Killers</h3>
<h4 id="heading-1-distributed-debugging-hell">🕳️ 1. Distributed Debugging Hell</h4>
<ul>
<li><p>Traces spread across 5 systems</p>
</li>
<li><p>“It works in test but fails in prod” becomes 10x harder</p>
</li>
<li><p>Engineers need to understand 15 services to fix one bug</p>
</li>
</ul>
<h4 id="heading-2-the-testing-illusion">📉 2. The Testing Illusion</h4>
<ul>
<li><p>100% test coverage on each service…</p>
</li>
<li><p>But zero tests for cross-service workflows</p>
</li>
<li><p>“We didn’t realize Service A would break Service B’s cache”</p>
</li>
</ul>
<h4 id="heading-3-deployment-synchronization">🔄 3. Deployment Synchronization</h4>
<ul>
<li><p>“Independent deployments” require careful orchestration</p>
</li>
<li><p>Feature flags become a distributed system themselves</p>
</li>
<li><p>Rollbacks now require coordinated multi-service efforts</p>
</li>
</ul>
<h4 id="heading-4-observability-overload">📊 4. Observability Overload</h4>
<ul>
<li><p>30 dashboards but no unified view</p>
</li>
<li><p>Alerts fire constantly from downstream services</p>
</li>
<li><p>“Is this our problem or someone else’s?”</p>
</li>
</ul>
<h4 id="heading-5-the-talent-tax">💸 5. The Talent Tax</h4>
<ul>
<li><p>New engineers take 6 months to become productive</p>
</li>
<li><p>Senior devs spend all time mentoring instead of coding</p>
</li>
<li><p>Constant context switching destroys deep work</p>
</li>
</ul>
<h3 id="heading-3-when-microservices-make-sense-and-when-they-dont">3. When Microservices Make Sense (And When They Don’t)</h3>
<h4 id="heading-good-candidates">✅ Good Candidates</h4>
<ul>
<li><p>Clear domain boundaries (payment vs inventory)</p>
</li>
<li><p>True scale needs (100k+ RPS)</p>
</li>
<li><p>Mature platform/SRE team</p>
</li>
</ul>
<h4 id="heading-bad-candidates">❌ Bad Candidates</h4>
<ul>
<li><p>Small teams (&lt; 15 engineers)</p>
</li>
<li><p>Rapidly evolving product</p>
</li>
<li><p>No existing monolith problems</p>
</li>
</ul>
<p><strong>Rule of Thumb:</strong> If you can’t draw your service boundaries on a napkin without ambiguity, you’re not ready.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743929117610/de26c9b2-bed0-458e-9e80-f864228f9b24.jpeg" alt /></p>
<h3 id="heading-4-the-modest-alternative-modular-monoliths">4. The Modest Alternative: Modular Monoliths</h3>
<h4 id="heading-the-architecture-everyone-forgot">The Architecture Everyone Forgot</h4>
<ul>
<li><p>Single deployable unit</p>
</li>
<li><p>Clear internal modules</p>
</li>
<li><p>Shared database with bounded contexts</p>
</li>
</ul>
<p><strong>Benefits:</strong></p>
<ul>
<li><p>90% of microservice advantages</p>
</li>
<li><p>10% of the complexity</p>
</li>
<li><p>Works beautifully for 80% of companies</p>
</li>
</ul>
<p><strong>Case Study:</strong> A team migrated from 22 microservices to a modular monolith and saw:</p>
<ul>
<li><p>60% reduction in production incidents</p>
</li>
<li><p>2x faster feature development</p>
</li>
<li><p>New engineers productive in days instead of months</p>
</li>
</ul>
<h3 id="heading-5-the-microservices-litmus-test">5. The Microservices Litmus Test</h3>
<p>Ask your team:</p>
<ol>
<li><p>Can most engineers name all our services and their purposes?</p>
</li>
<li><p>Do we regularly deploy services independently?</p>
</li>
<li><p>Is cross-service coordination &lt;10% of our time?</p>
</li>
<li><p>Can new hires ship to prod in their first week?</p>
</li>
</ol>
<p>If you answered “no” to any, you’re paying the microservices tax without getting the benefits.</p>
<h3 id="heading-final-thought-architecture-should-serve-people-not-vice-versa">Final Thought: Architecture Should Serve People, Not Vice Versa</h3>
<p>The best architecture is the <strong>simplest one that solves your actual problems</strong>  — not the one that looks best on an engineering blog.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743929118905/ba2b57f2-f25e-44ac-9804-6fa1e73866ea.jpeg" alt /></p>
<p>💬 <strong>Has your team fallen into the microservices trap? What architecture lessons have you learned the hard way?</strong> Let’s discuss!</p>
]]></content:encoded></item><item><title><![CDATA[How to Create Kubernetes CRDs Using Golang and Master Controller Programming ️]]></title><description><![CDATA[Kubernetes has revolutionized the way we manage containerized applications, but what happens when you need to extend its capabilities to fit your unique…]]></description><link>https://devangtomar.hashnode.dev/how-to-create-kubernetes-crds-using-golang-and-master-controller-programming</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/how-to-create-kubernetes-crds-using-golang-and-master-controller-programming</guid><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[#kubernetes #container ]]></category><category><![CDATA[kubernetes architecture]]></category><category><![CDATA[#GoLang #Kubernetes #AWS #EKS #Docker #CI/CD #Helm #ArgoCD #GitOps #DevOps #CloudComputing]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sat, 22 Feb 2025 11:15:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1740223469229/edc65720-e065-4339-9379-bcfa38580658.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>Kubernetes has revolutionized the way we manage containerized applications, but what happens when you need to extend its capabilities to fit your unique use case? Enter <strong>Custom Resource Definitions (CRDs)</strong> and <strong>Controllers</strong>! With these powerful tools, you can define your own resources and automate their management in Kubernetes. 🌟</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740223387261/e6d78ec0-96a1-4065-98c1-99422b44057f.jpeg" alt /></p>
<p>In this article, we’ll explore how to create Kubernetes CRDs using Golang and dive into the world of controller programming with the <strong>Watcher-Informer model</strong>. Whether you’re building a custom operator or extending Kubernetes for your organization, this guide will help you get started. Let’s dive in! 💻</p>
<h3 id="heading-why-create-custom-resources-and-controllers">🤔 Why Create Custom Resources and Controllers?</h3>
<p>Before we jump into the <em>how</em>, let’s talk about the <em>why</em>. Here are a few reasons you might want to create CRDs and controllers:</p>
<ol>
<li><p><strong>Custom Workflows</strong> : You need to manage resources that Kubernetes doesn’t natively support.</p>
</li>
<li><p><strong>Automation</strong> : You want to automate complex tasks like provisioning, scaling, or healing.</p>
</li>
<li><p><strong>Extending Kubernetes</strong> : You’re building a platform or tool that integrates deeply with Kubernetes.</p>
</li>
</ol>
<p>If any of these resonate with you, it’s time to roll up your sleeves and start building! 🛠️</p>
<h3 id="heading-what-youll-need">🧰 What You’ll Need</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740223389152/33162c1d-67c4-4adf-908f-53473d94a95f.jpeg" alt /></p>
<p>Before we begin, make sure you have the following tools installed:</p>
<ul>
<li><p><strong>Go (Golang)</strong>: We’ll use Go to write our CRD and controller. Install it from <a target="_blank" href="https://golang.org/">golang.org</a>.</p>
</li>
<li><p><strong>Kubebuilder or Operator SDK</strong> : These frameworks simplify the process of building Kubernetes operators. Install one of them.</p>
</li>
<li><p><strong>Kubernetes Cluster</strong> : You’ll need a cluster to test your CRD and controller. Minikube or Kind are great for local development.</p>
</li>
<li><p><strong>kubectl</strong> : The Kubernetes CLI tool for interacting with your cluster.</p>
</li>
</ul>
<h3 id="heading-step-1-define-your-custom-resource-crd">🚀 Step 1: Define Your Custom Resource (CRD)</h3>
<p>Let’s create a CRD for a “Widget” resource.</p>
<ol>
<li><strong>Scaffold Your Project</strong> :<br /> Use Kubebuilder to set up your project.</li>
</ol>
<pre><code class="lang-plaintext">kubebuilder init --domain mydomain.com --repo github.com/yourusername/widget-operator  
kubebuilder create api --group widgets --version v1 --kind Widget
</code></pre>
<p>This generates the files you need for your CRD and controller.</p>
<p><strong>2. Define the Widget Schema</strong> :<br />Open api/v1/widget_types.go and define your Widget resource.</p>
<pre><code class="lang-plaintext">package v1  

import (  
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"  
)  

// WidgetSpec defines the desired state of Widget  
type WidgetSpec struct {  
    Name string `json:"name"`  
    Description string `json:"description,omitempty"`  
    Replicas int32 `json:"replicas"`  
}  

// WidgetStatus defines the observed state of Widget  
type WidgetStatus struct {  
    AvailableReplicas int32 `json:"availableReplicas"`  
}  

//+kubebuilder:object:root=true  
//+kubebuilder:subresource:status  

// Widget is the Schema for the widgets API  
type Widget struct {  
    metav1.TypeMeta `json:",inline"`  
    metav1.ObjectMeta `json:"metadata,omitempty"`  

    Spec WidgetSpec `json:"spec,omitempty"`  
    Status WidgetStatus `json:"status,omitempty"`  
}  

//+kubebuilder:object:root=true  

// WidgetList contains a list of Widget  
type WidgetList struct {  
    metav1.TypeMeta `json:",inline"`  
    metav1.ListMeta `json:"metadata,omitempty"`  
    Items []Widget `json:"items"`  
}  

func init() {  
    SchemeBuilder.Register(&amp;Widget{}, &amp;WidgetList{})  
}
</code></pre>
<ol start="3">
<li><strong>Generate and Apply the CRD</strong> :<br /> Run these commands to generate and apply your CRD.</li>
</ol>
<pre><code class="lang-plaintext">make manifests  
kubectl apply -f config/crd/bases/
</code></pre>
<p>Boom! Your CRD is now live in the cluster. 🎉</p>
<h3 id="heading-step-2-build-the-controller">🛠️ Step 2: Build the Controller</h3>
<p>Now, let’s build the controller to manage your Widgets.</p>
<ol>
<li><strong>Understand the Watcher-Informer Model</strong> :</li>
</ol>
<ul>
<li><p><strong>Watcher</strong> : Watches for changes to resources. 👀</p>
</li>
<li><p><strong>Informer</strong> : Caches resource state and triggers events. 🤖</p>
</li>
</ul>
<p><strong>2. Implement the Reconcile Loop</strong> :<br />Open controllers/widget_controller.go and add your logic.</p>
<pre><code class="lang-plaintext">package controllers  

import (  
    "context"  
    "fmt"  

    "github.com/go-logr/logr"  
    "k8s.io/apimachinery/pkg/runtime"  
    ctrl "sigs.k8s.io/controller-runtime"  
    "sigs.k8s.io/controller-runtime/pkg/client"  

    widgetv1 "github.com/yourusername/widget-operator/api/v1"  
)  

// WidgetReconciler reconciles a Widget object  
type WidgetReconciler struct {  
    client.Client  
    Log logr.Logger  
    Scheme *runtime.Scheme  
}  

func (r *WidgetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {  
    log := r.Log.WithValues("widget", req.NamespacedName)  

    // Fetch the Widget  
    var widget widgetv1.Widget  
    if err := r.Get(ctx, req.NamespacedName, &amp;widget); err != nil {  
        return ctrl.Result{}, client.IgnoreNotFound(err)  
    }  

    // Your logic here  
    log.Info("Reconciling Widget", "name", widget.Name)  
    fmt.Printf("Widget Spec: %+v\n", widget.Spec)  

    // Update status  
    widget.Status.AvailableReplicas = widget.Spec.Replicas  
    if err := r.Status().Update(ctx, &amp;widget); err != nil {  
        return ctrl.Result{}, err  
    }  

    return ctrl.Result{}, nil  
}  

func (r *WidgetReconciler) SetupWithManager(mgr ctrl.Manager) error {  
    return ctrl.NewControllerManagedBy(mgr).  
        For(&amp;widgetv1.Widget{}).  
        Complete(r)  
}
</code></pre>
<ol start="3">
<li><strong>Run the Controller</strong> :<br /> Start your controller locally to test it.</li>
</ol>
<pre><code class="lang-plaintext">make run
</code></pre>
<h3 id="heading-step-3-test-your-crd-and-controller">🧪 Step 3: Test Your CRD and Controller</h3>
<ol>
<li><strong>Create a Widget Resource</strong> :<br /> Create a widget-example.yaml file:</li>
</ol>
<pre><code class="lang-plaintext">apiVersion: widgets.mydomain.com/v1  
kind: Widget  
metadata:  
  name: example-widget  
spec:  
  name: "example-widget"  
  description: "This is an example widget."  
  replicas: 3
</code></pre>
<ol start="2">
<li><strong>Apply the Resource</strong> :<br /> Use kubectl to apply it.</li>
</ol>
<pre><code class="lang-plaintext">kubectl apply -f widget-example.yaml
</code></pre>
<ol start="3">
<li><strong>Check the Logs</strong> :<br /> Watch your controller logs to see the magic happen! ✨</li>
</ol>
<h3 id="heading-step-4-deploy-your-controller">🚀 Step 4: Deploy Your Controller</h3>
<p>Once it works locally, deploy it to your cluster.</p>
<ol>
<li><strong>Build and Push the Docker Image</strong> :</li>
</ol>
<pre><code class="lang-plaintext">make docker-build docker-push IMG=&lt;your-docker-image&gt;
</code></pre>
<ol start="2">
<li>Deploy the Controller</li>
</ol>
<pre><code class="lang-plaintext">make deploy IMG=&lt;your-docker-image&gt;
</code></pre>
<h3 id="heading-you-did-it">🎉 You Did It!</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740223391004/09cbbe98-ec4b-4e32-b24c-74aeb9a4f565.png" alt /></p>
<p>You’ve just:<br />✅ Created a <strong>Custom Resource Definition (CRD)</strong><br />✅ Built a <strong>Controller</strong> using the Watcher-Informer model<br />✅ Automated your custom resources like a pro! 🚀</p>
<p>Now go forth and extend Kubernetes to fit YOUR needs! 🌟</p>
]]></content:encoded></item><item><title><![CDATA[How to Write Your Own Terraform Provider: A Step-by-Step Guide 🛠️ ️]]></title><description><![CDATA[Terraform has become the go-to tool for infrastructure as code (IaC), enabling developers to define and provision infrastructure using a declarative…]]></description><link>https://devangtomar.hashnode.dev/how-to-write-your-own-terraform-provider-a-step-by-step-guide</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/how-to-write-your-own-terraform-provider-a-step-by-step-guide</guid><category><![CDATA[custom providers]]></category><category><![CDATA[Terraform]]></category><category><![CDATA[terraform-cloud]]></category><category><![CDATA[terraform-state]]></category><category><![CDATA[terraform-module]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 31 Jan 2025 18:31:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739008076773/8e028d8f-72fb-42cf-987c-fbd01c675179.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>Terraform has become the go-to tool for infrastructure as code (IaC), enabling developers to define and provision infrastructure using a declarative configuration language. While Terraform supports a wide range of cloud providers and services out of the box, there may come a time when you need to manage a custom resource or integrate with a proprietary API. That’s where writing your own Terraform provider comes in! 🌟</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738348695560/acd7d13b-cfe9-4835-8a36-802b26acc7f5.png" alt /></p>
<p>In this article, we’ll walk through the process of creating your very own Terraform provider from scratch. Whether you’re managing a niche cloud service or an internal tool, this guide will help you get started. Let’s dive in! 💻</p>
<h4 id="heading-why-write-a-custom-terraform-provider">🤔 Why Write a Custom Terraform Provider?</h4>
<p>Before we jump into the *how*, let’s talk about the *why*. Here are a few reasons you might want to create your own Terraform provider:</p>
<ol>
<li><p><strong>Custom Resources</strong> : You have a unique service or tool that isn’t supported by existing providers.</p>
</li>
<li><p><strong>Proprietary APIs</strong> : Your organization uses internal APIs that need to be managed as infrastructure.</p>
</li>
<li><p><strong>Extending Terraform</strong> : You want to add functionality to Terraform that aligns with your specific workflows.</p>
</li>
</ol>
<p>If any of these resonate with you, it’s time to roll up your sleeves and start building! 🛠️</p>
<h4 id="heading-prerequisites">🧰 Prerequisites</h4>
<p>Before we begin, make sure you have the following tools installed:</p>
<ol>
<li><p><strong>Go (Golang)</strong>: Terraform providers are written in Go. Install it from <a target="_blank" href="%5Bhttps://golang.org/%5D\(https://golang.org/\)">golang.org</a>.</p>
</li>
<li><p><strong>Terraform</strong> : You’ll need Terraform installed to test your provider. Download it from <a target="_blank" href="%5Bhttps://www.terraform.io/%5D\(https://www.terraform.io/\)">terraform.io</a>.</p>
</li>
<li><p><strong>Git</strong> : For version control and managing your provider’s code.</p>
</li>
</ol>
<h4 id="heading-step-1-set-up-your-go-environment">🚀 Step 1: Set Up Your Go Environment</h4>
<p>First, let’s set up your Go workspace. Create a new directory for your provider and initialize a Go module:</p>
<pre><code class="lang-plaintext">mkdir terraform-provider-myprovider
cd terraform-provider-myprovider
go mod init github.com/yourusername/terraform-provider-myprovider
</code></pre>
<p>This will create a go.mod file, which manages your project’s dependencies.</p>
<h4 id="heading-step-2-create-the-provider-skeleton">🛠️ Step 2: Create the Provider Skeleton</h4>
<p>Terraform providers follow a specific structure. Start by creating the basic files and directories:</p>
<ol>
<li>Create the main.go file:<br /> This is the entry point for your provider.</li>
</ol>
<pre><code class="lang-plaintext">package main

import (
    "github.com/hashicorp/terraform-plugin-sdk/v2/plugin"
    "github.com/yourusername/terraform-provider-myprovider/myprovider"
)

func main() {
    plugin.Serve(&amp;plugin.ServeOpts{
        ProviderFunc: myprovider.Provider,
    })
}
</code></pre>
<ol start="2">
<li>Create the provider file:<br /> In a new directory called myprovider, create a file named provider.go.</li>
</ol>
<pre><code class="lang-plaintext">package myprovider

import (
    "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func Provider() *schema.Provider {
    return &amp;schema.Provider{
        ResourcesMap: map[string]*schema.Resource{},
        DataSourcesMap: map[string]*schema.Resource{},
    }
}
</code></pre>
<p>This sets up the basic structure of your provider. Right now, it doesn’t do much, but we’ll add resources and data sources soon.</p>
<h4 id="heading-step-3-define-your-first-resource">🔧 Step 3: Define Your First Resource</h4>
<p>A Terraform provider is useless without resources. Let’s define a simple resource. For example, let’s say we’re creating a provider to manage “widgets” in a fictional API.</p>
<ol>
<li>Create a resource file:<br /> In the myprovider directory, create a file named resource_widget.go.</li>
</ol>
<pre><code class="lang-plaintext">package myprovider

import (
    "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourceWidget() *schema.Resource {
    return &amp;schema.Resource{
        Create: resourceWidgetCreate,
        Read: resourceWidgetRead,
        Update: resourceWidgetUpdate,
        Delete: resourceWidgetDelete,

        Schema: map[string]*schema.Schema{
            "name": {
                Type: schema.TypeString,
                Required: true,
            },
            "description": {
                Type: schema.TypeString,
                Optional: true,
            },
        },
    }
}

func resourceWidgetCreate(d *schema.ResourceData, m interface{}) error {
    // Implement logic to create a widget.
    d.SetId("widget-id") // Set a dummy ID for now.
    return nil
}

func resourceWidgetRead(d *schema.ResourceData, m interface{}) error {
    // Implement logic to read a widget.
    return nil
}

func resourceWidgetUpdate(d *schema.ResourceData, m interface{}) error {
    // Implement logic to update a widget.
    return nil
}

func resourceWidgetDelete(d *schema.ResourceData, m interface{}) error {
    // Implement logic to delete a widget.
    return nil
}
</code></pre>
<ol start="2">
<li>Register the resource:<br /> Update the provider.go file to include the new resource.</li>
</ol>
<pre><code class="lang-plaintext">func Provider() *schema.Provider {
    return &amp;schema.Provider{
        ResourcesMap: map[string]*schema.Resource{
            "myprovider_widget": resourceWidget(),
        },
        DataSourcesMap: map[string]*schema.Resource{},
    }
}
</code></pre>
<h4 id="heading-step-4-test-your-provider">🧪 Step 4: Test Your Provider</h4>
<p>Now that you’ve defined a resource, it’s time to test your provider. First, build the provider:</p>
<pre><code class="lang-plaintext">go build -o terraform-provider-myprovider
</code></pre>
<p>Next, create a Terraform configuration file (main.tf) to test the provider:</p>
<pre><code class="lang-plaintext">provider "myprovider" {}

resource "myprovider_widget" "example" {
  name = "example-widget"
  description = "This is an example widget."
}
</code></pre>
<p>Finally, initialize and apply your Terraform configuration:</p>
<pre><code class="lang-plaintext">terraform init
terraform apply
</code></pre>
<h4 id="heading-step-5-publish-and-share-your-provider">🚀 Step 5: Publish and Share Your Provider</h4>
<p>Once your provider is working, you can publish it to the Terraform Registry or share it with your team. To publish it:</p>
<ol>
<li>Tag your release:<br /> Use Git to tag your release.</li>
</ol>
<pre><code class="lang-plaintext">git tag v1.0.0
git push origin v1.0.0
</code></pre>
<ol start="2">
<li>Submit to the Terraform Registry:<br /> Follow the <a target="_blank" href="https://www.terraform.io/docs/registry/providers/publishing.html">Terraform Registry documentation</a> to publish your provider.</li>
</ol>
<h4 id="heading-congratulations-youve-built-a-terraform-provider">🎉 Congratulations! You’ve Built a Terraform Provider!</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738348697100/77aa0a16-f05c-4469-bd2f-ae57862dc1eb.png" alt /></p>
<p>Writing a custom Terraform provider might seem daunting at first, but once you break it down into steps, it’s entirely manageable. By following this guide, you’ve learned how to:</p>
<ul>
<li><p>Set up a Go project for your provider.</p>
</li>
<li><p>Define resources and data sources.</p>
</li>
<li><p>Test and publish your provider.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How a Sneaky AI Hack Turned 5 Lines of Code into a $1M Search Engine Upgrade]]></title><description><![CDATA[Search engines power the world — whether it’s finding the perfect recipe, the latest tech gadget, or that obscure meme template you saw last week. But…]]></description><link>https://devangtomar.hashnode.dev/how-a-sneaky-ai-hack-turned-5-lines-of-code-into-a-1m-search-engine-upgrade</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/how-a-sneaky-ai-hack-turned-5-lines-of-code-into-a-1m-search-engine-upgrade</guid><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 20 Dec 2024 05:31:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739008137644/e7c9fcb1-a1d7-47b6-bc7e-94aac3aae9f5.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>Search engines power the world — whether it’s finding the perfect recipe, the latest tech gadget, or that obscure meme template you saw last week. But beneath their sleek search bars, many engines rely on outdated systems, leading to irrelevant results, frustrated users, and lost revenue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735126092193/19810147-0c43-46f4-ac4a-6ea09026366a.jpeg" alt /></p>
<p>What if I told you that with just <em>5 lines of code</em>, you could transform your search engine into a powerhouse, increasing its efficiency and even driving <strong>$1M+ in revenue</strong>?</p>
<p>Let’s dive into the <strong>sneaky AI hack</strong> that’s making it possible: <strong>embedding-based searches</strong> powered by Large Language Models (LLMs).</p>
<h4 id="heading-the-problem-with-traditional-search-engines"><strong>The Problem with Traditional Search Engines 😵</strong></h4>
<p>Legacy search engines typically use <strong>keyword-based search</strong>. This means they match user queries to documents by looking for literal matches. Sounds simple, right? But here’s the catch:</p>
<p>• <strong>Synonyms trip them up:</strong> Searching for “buy running shoes” might miss results for “purchase sneakers.”</p>
<p>• <strong>Context goes over their head:</strong> Searching for “python tutorial” could return snake-related content instead of programming resources.</p>
<p>• <strong>Rigid ranking:</strong> Results are ranked by keyword frequency rather than understanding the query’s intent.</p>
<p>These limitations hurt <strong>user satisfaction</strong> and <strong>conversion rates</strong>  — a big deal for e-commerce, content platforms, and SaaS tools.</p>
<h4 id="heading-the-sneaky-hack-embedding-based-searches"><strong>The Sneaky Hack: Embedding-Based Searches 🕵🏻‍♂️</strong></h4>
<p>Enter <strong>embeddings</strong> , the secret sauce that’s supercharging search engines.</p>
<p>An embedding is a numerical representation of text, capturing its <strong>semantic meaning</strong> rather than just the words. For example, embeddings for “buy running shoes” and “purchase sneakers” would be <strong>close together</strong> in vector space, ensuring they’re treated as similar queries.</p>
<p>Here’s the crazy part: with <strong>just 5 lines of code</strong> , you can integrate embeddings into your search engine. Here’s what they do:</p>
<ol>
<li><p><strong>Convert queries and documents into embeddings.</strong></p>
</li>
<li><p><strong>Use vector similarity</strong> (like cosine similarity) to find the closest match.</p>
</li>
<li><p><strong>Return results ranked by relevance</strong> , not just keywords.</p>
</li>
</ol>
<h4 id="heading-the-5-lines-of-code-that-changed-everything"><strong>The 5 Lines of Code That Changed Everything 🧑🏻‍💻</strong></h4>
<p>This is how simple it can be with tools like OpenAI’s API or Hugging Face:</p>
<pre><code class="lang-plaintext">from openai.embeddings_utils import get_embedding, cosine_similarity
query_embedding = get_embedding("buy running shoes")
results = [cosine_similarity(query_embedding, doc_embedding) for doc_embedding in documents]
sorted_results = sorted(zip(results, documents), reverse=True)
</code></pre>
<p>That’s it. These 5 lines connect your search query to the most relevant results based on meaning, not just keywords.</p>
<h4 id="heading-real-life-magic-embeddings-in-action"><strong>Real-Life Magic: Embeddings in Action 🪄</strong></h4>
<p>Here are some ways embedding-based searches are transforming industries:</p>
<p><strong>1. E-Commerce: Boosting Sales</strong></p>
<p>An online retailer implemented embeddings to improve product searches. Instead of relying on rigid keywords, their search engine understood user intent. For example:</p>
<p>• Query: “affordable wireless headphones”</p>
<p>• Results: Products with descriptions like “budget-friendly Bluetooth earphones.”</p>
<p>Result? <strong>25% increase in sales</strong> , translating to millions in revenue.</p>
<p><strong>2. Knowledge Management: Finding the Needle in the Haystack</strong></p>
<p>A SaaS company used embeddings to enhance its internal knowledge base. Employees could now find relevant documentation — even when they didn’t know the exact phrasing.</p>
<p>Result? <strong>50% reduction in search time</strong> , boosting productivity across teams.</p>
<p><strong>3. Content Platforms: Winning the Engagement Game</strong></p>
<p>A streaming platform used embeddings to deliver personalized content recommendations. If a user searched for “feel-good movies,” they’d get curated suggestions even if “feel-good” wasn’t a keyword.</p>
<p>Result? <strong>30% increase in user retention.</strong></p>
<h4 id="heading-the-cost-vs-impact-breakdown"><strong>The Cost vs. Impact Breakdown 💴</strong></h4>
<p>At this point, you’re probably wondering: how much does this cost?</p>
<p>Here’s the kicker: embedding-based searches are surprisingly affordable.</p>
<p>• <strong>Cost per query:</strong> APIs like OpenAI or Hugging Face charge a fraction of a cent for generating embeddings.</p>
<p>• <strong>Compute requirements:</strong> Vector search tools like <strong>Pinecone</strong> or <strong>Weaviate</strong> make integration seamless, even for large datasets.</p>
<p><strong>Impact:</strong> Businesses report ROI in the range of <strong>10x–100x</strong> , thanks to improved search accuracy, higher conversions, and better user retention.</p>
<h4 id="heading-why-this-hack-works-so-well"><strong>Why This Hack Works So Well 🙋🏻‍♂️</strong></h4>
<p>Here’s why embedding-based searches are a game-changer:</p>
<ol>
<li><p><strong>Contextual Understanding:</strong> They can match “cheap hotels near me” with “budget accommodations.”</p>
</li>
<li><p><strong>Scalability:</strong> Perfect for massive datasets with millions of entries.</p>
</li>
<li><p><strong>Future-Proof:</strong> As LLMs improve, embeddings become even more precise.</p>
</li>
</ol>
<h4 id="heading-your-1m-upgrade-starts-here"><strong>Your $1M Upgrade Starts Here 💰</strong></h4>
<p>Ready to transform your search engine? Start small:</p>
<p>• <strong>Step 1:</strong> Use an API like OpenAI to generate embeddings.</p>
<p>• <strong>Step 2:</strong> Plug them into a vector database like Pinecone or FAISS.</p>
<p>• <strong>Step 3:</strong> Test, refine, and watch your metrics soar.</p>
<p>With just a few lines of code and minimal upfront investment, you could unlock the full potential of your search engine — and, who knows, maybe even drive <strong>$1M+ in value</strong>.</p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on Social Media</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/@devangtomar">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[🔥 Hidden Gems 👀: 20 Lesser-Known VS Code Extensions to Boost Your Productivity 🚀]]></title><description><![CDATA[In this article, we uncover 20 hidden gems — VS Code extensions you’ve probably never heard of but absolutely need to try 👀 🚀 Photo by Chris Ried on…]]></description><link>https://devangtomar.hashnode.dev/hidden-gems-20-lesser-known-vs-code-extensions-to-boost-your-productivity</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/hidden-gems-20-lesser-known-vs-code-extensions-to-boost-your-productivity</guid><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 08 Dec 2024 12:01:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739008144989/dee0e755-749d-480a-80b2-6cbf4075657c.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>In this article, we uncover 20 hidden gems — VS Code extensions you’ve probably never heard of but absolutely need to try 👀 🚀</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661225971/061ed132-0087-4433-85c9-d400ab00ecbd.png" alt /></p>
<p><em>Photo by Chris Ried on Unsplash</em></p>
<p>Visual Studio Code (VS Code) is the go-to editor for developers worldwide, offering a treasure trove of extensions to customize and enhance your workflow. While popular tools like Prettier and Live Server often steal the spotlight, there’s a whole world of lesser-known extensions that can truly supercharge your productivity.</p>
<p><strong>1. Peacock</strong></p>
<p><strong>Description:</strong> Working with multiple VS Code instances? Peacock lets you color-code your editor windows for better context switching.</p>
<p><strong>Use Case:</strong> Easily identify your workspace when juggling multiple projects.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=johnpapa.vscode-peacock">Peacock</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661227566/534ebc9a-da20-4f9c-9002-93f166f52ae7.png" alt /></p>
<p><strong>2. Code Time</strong></p>
<p><strong>Description:</strong> Gain insights into your coding habits with this productivity tracker. It integrates seamlessly with your workflow without being intrusive.</p>
<p><strong>Use Case:</strong> Track your coding hours, focus time, and efficiency metrics.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=softwaredotcom.swdc-vscode">Code Time</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661228887/570f1ed3-39f3-463f-8131-b9fec0c0e815.png" alt /></p>
<p><strong>3. Todo Tree</strong></p>
<p><strong>Description:</strong> Automatically find and organize your TODO, FIXME, or other comments in your project.</p>
<p><strong>Use Case:</strong> Manage your tasks directly from the sidebar without losing track of them.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=Gruntfuggly.todo-tree">Todo Tree</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661230329/a9645312-9cff-437c-b427-bbda0d7f3435.png" alt /></p>
<p><strong>4. Polacode</strong></p>
<p><strong>Description:</strong> Need to share beautiful code snippets? Polacode generates picture-perfect images of your code in seconds.</p>
<p><strong>Use Case:</strong> Create polished visuals for documentation or social media.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=pnp.polacode">Polacode</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661231431/06a12a19-53e0-4103-899a-ce6cdbfdb8e9.png" alt /></p>
<p><strong>5. Error Lens</strong></p>
<p><strong>Description:</strong> Supercharge your debugging process by highlighting errors and warnings inline in your code.</p>
<p><strong>Use Case:</strong> Avoid flipping between the problems panel and your code.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens">Error Lens</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661232577/085d1c2f-7cb9-43ec-a165-2ff9ea119424.png" alt /></p>
<p><strong>6. GitLens</strong></p>
<p><strong>Description:</strong> A powerful extension for visualizing and navigating your Git repository.</p>
<p><strong>Use Case:</strong> Explore commit history, file blame annotations, and branch comparisons effortlessly.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens">GitLens</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661233989/46cec5f0-9eb9-49ee-b1ba-b85f6d7a57b5.png" alt /></p>
<p><strong>7. Better Comments</strong></p>
<p><strong>Description:</strong> Make your comments more readable and meaningful with color-coded categories like TODO, NOTE, and IMPORTANT.</p>
<p><strong>Use Case:</strong> Collaborate effectively with teammates using well-organized comments.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments">Better Comments</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661235358/d5b26807-a945-4f10-aacf-ac6b4dd6d6ba.png" alt /></p>
<p><strong>8. Quokka.js</strong></p>
<p><strong>Description:</strong> Get real-time feedback on your JavaScript and TypeScript code with this interactive playground.</p>
<p><strong>Use Case:</strong> Test and debug snippets quickly without leaving your editor.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=WallabyJs.quokka-vscode">Quokka.js</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661236742/ed54b81d-4451-47d9-9a1c-b697f78107ca.png" alt /></p>
<p><strong>9. CSS Peek</strong></p>
<p><strong>Description:</strong> Navigate directly to CSS definitions in your project.</p>
<p><strong>Use Case:</strong> Quickly jump between HTML elements and their corresponding CSS styles.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=pranaygp.vscode-css-peek">CSS Peek</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661237986/b48b90cf-8d8e-4638-9948-93690de328f9.png" alt /></p>
<p><strong>10. REST Client</strong></p>
<p><strong>Description:</strong> Test APIs without leaving VS Code. This extension is a lightweight alternative to Postman.</p>
<p><strong>Use Case:</strong> Make HTTP requests directly from your editor.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=humao.rest-client">REST Client</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661239323/f21fdce3-d7ef-4c8d-8741-1a966e7e21f9.png" alt /></p>
<p><strong>11. Git Graph</strong></p>
<p><strong>Description:</strong> Visualize your Git repository’s commit graph with a simple UI.</p>
<p><strong>Use Case:</strong> Understand your project’s history and branches at a glance.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph">Git Graph</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661240603/e5a7dae6-e23e-4bcd-87c7-34f7630d3e4a.png" alt /></p>
<p><strong>12. Bracket Pair Color DLW</strong></p>
<p><strong>Description:</strong> Assign colors to matching brackets for better readability in complex code.</p>
<p><strong>Use Case:</strong> Navigate deeply nested code structures without confusion.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=BracketPairColorDLW.bracket-pair-color-dlw">Bracket Pair Color DLW</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661241857/9f089ea8-f13f-49f0-9890-b0754afb0a16.png" alt /></p>
<p><strong>13. vscode-icons</strong></p>
<p><strong>Description:</strong> Add visually appealing file and folder icons to your workspace.</p>
<p><strong>Use Case:</strong> Quickly identify file types at a glance.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=vscode-icons-team.vscode-icons">vscode-icons</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661243179/132ebc60-2639-4805-8f1b-6f63891caa55.png" alt /></p>
<p><strong>14. Highlight Matching Tag</strong></p>
<p><strong>Description:</strong> Automatically highlight matching HTML and XML tags to ensure proper nesting.</p>
<p><strong>Use Case:</strong> Avoid syntax errors in web development.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=vincaslt.highlight-matching-tag">Highlight Matching Tag</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661244289/c93b9ca2-a845-4690-8268-6fe52b87eaaf.png" alt /></p>
<p><strong>15. Bookmarks</strong></p>
<p><strong>Description:</strong> Bookmark lines of code and jump between them effortlessly.</p>
<p><strong>Use Case:</strong> Navigate large codebases with ease.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks">Bookmarks</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661245417/9a341a88-fb49-44f7-995f-1bdc74fedee9.png" alt /></p>
<p><strong>16. Excel Viewer</strong></p>
<p><strong>Description:</strong> View and edit Excel files directly in VS Code.</p>
<p><strong>Use Case:</strong> Analyze data without switching to another tool.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=GrapeCity.gc-excelviewer">Excel Viewer</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661246666/427741b9-677d-49cc-84e8-845934bd1a37.png" alt /></p>
<p><strong>17. Path Intellisense</strong></p>
<p><strong>Description:</strong> Autocomplete file paths in your project.</p>
<p><strong>Use Case:</strong> Save time while importing or linking files.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense">Path Intellisense</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661247887/3c34d39a-4f56-487f-ace5-89a5f1261a2a.png" alt /></p>
<p><strong>18. SQLTools</strong></p>
<p><strong>Description:</strong> A database management extension that allows you to connect to SQL databases, execute queries, and explore schemas — all within VS Code.</p>
<p><strong>Use Case:</strong> Manage your backend databases without leaving your code editor.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=mtxr.sqltools">SQLTools</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661248953/e612903b-46c2-4a5d-89f7-e1e6aa114124.png" alt /></p>
<p><strong>19. Git Blame</strong></p>
<p><strong>Description:</strong> Provides a simple interface to view git blame information directly in the VS Code editor. It shows who last modified a line of code and when, without needing to open the terminal or command line.</p>
<p><strong>Use Case:</strong> Perfect for quickly tracking down the history of a specific line of code and understanding who to approach for questions regarding that section.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=waderyan.gitblame">Git Blame</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661250189/d7088228-5bd0-4d5b-b79c-3cfdd1b0f052.png" alt /></p>
<p><strong>20. WakaTime</strong></p>
<p><strong>Description:</strong> Track your coding activity across projects and languages.</p>
<p><strong>Use Case:</strong> Gain insights into your productivity over time.</p>
<p><strong>Install:</strong> <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=WakaTime.vscode-wakatime">WakaTime</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733661251694/267bc5b4-1f9f-46f7-b73b-3ab0de9bf4a4.png" alt /></p>
<h4 id="heading-final-thoughts"><strong>Final Thoughts</strong></h4>
<p>These hidden gems are powerful yet often overlooked. Integrating them into your workflow can save you time, simplify tasks, and even make coding more enjoyable. So, go ahead and give these underrated extensions a shot!</p>
<p>Do you know of any other lesser-known yet awesome extensions? Share your favorites in the comments below.</p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on Social Media</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/@devangtomar">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Setting Up a Mac for Development: A Comprehensive Guide 🧑🏻‍💻 ‍]]></title><description><![CDATA[Setting up a new Mac for development can be time-consuming, especially if you’re a developer who needs an efficient and tailored environment. Whether…]]></description><link>https://devangtomar.hashnode.dev/setting-up-a-mac-for-development-a-comprehensive-guide</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/setting-up-a-mac-for-development-a-comprehensive-guide</guid><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 24 Nov 2024 09:46:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732442533893/79bf03b5-a2e4-4854-9a15-1f6d82c29608.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732442373180/06f269d0-48db-4a8c-a892-5ae8275cd3a3.jpeg" alt /></p>
<p>Setting up a new Mac for development can be time-consuming, especially if you’re a developer who needs an efficient and tailored environment. Whether you’re setting up a work machine or a personal computer, having a checklist can save time and effort. Here’s a streamlined guide for getting your MacBook ready for development, optimized for macOS 15 (Sequoia).</p>
<h3 id="heading-getting-started"><strong>Getting Started 🎬</strong></h3>
<p>When you turn on your Mac, the setup assistant will guide you through basic configurations like selecting your language, time zone, and Apple ID. Once done, update macOS to ensure you have the latest security patches.</p>
<ul>
<li><p><a class="post-section-overview" href="#d1d0">Install Homebrew for App Management ☕️</a></p>
</li>
<li><p><a class="post-section-overview" href="#4345">Installing Essential Applications 📲</a></p>
</li>
<li><p><a class="post-section-overview" href="#6b89">Setting Up the Shell</a></p>
</li>
<li><p><a class="post-section-overview" href="#85a2">Custom Brew Packages and Zsh Configuration</a></p>
</li>
<li><p><a class="post-section-overview" href="#bacb">Configuring Git</a></p>
</li>
<li><p><a class="post-section-overview" href="#07bb">Generate SSH Keys</a></p>
</li>
<li><p><a class="post-section-overview" href="#0671">Tuning macOS Settings</a></p>
</li>
<li><p><a class="post-section-overview" href="#2cb2">Application-Specific Tips</a></p>
</li>
</ul>
<h3 id="heading-install-homebrew-for-app-management"><strong>Install Homebrew for App Management ☕️</strong></h3>
<p><a target="_blank" href="https://brew.sh/">Homebrew</a> is a must-have package manager for macOS, simplifying the installation of software.</p>
<p>Run the following command to install Homebrew:</p>
<pre><code class="lang-plaintext">/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
</code></pre>
<p>After installation, ensure it’s updated:</p>
<pre><code class="lang-plaintext">brew update
</code></pre>
<h3 id="heading-installing-essential-applications"><strong>Installing Essential Applications 📲</strong></h3>
<p>Here’s a list of CLI tools and GUI applications you’ll likely need:</p>
<h4 id="heading-command-line-tools"><strong>Command-Line Tools</strong></h4>
<p>Install these using Homebrew:</p>
<pre><code class="lang-plaintext">brew install git
</code></pre>
<h4 id="heading-graphical-applications"><strong>Graphical Applications</strong></h4>
<p>Install these with the — cask flag:</p>
<pre><code class="lang-plaintext">brew install - cask \
visual-studio-code \
google-chrome \
firefox \
rectangle \
iterm2 \
docker \
discord \
slack \
spotify \
postgres \
obsidian \
todoist
</code></pre>
<blockquote>
<p><strong>Note</strong> : Do not install Node.js via Homebrew. Use nvm for better version control (details below).</p>
</blockquote>
<h3 id="heading-setting-up-the-shell"><strong>Setting Up the Shell</strong></h3>
<p>macOS comes with zsh as the default shell. Enhance it with <strong>Oh My Zsh</strong> :</p>
<pre><code class="lang-plaintext">sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
</code></pre>
<h4 id="heading-add-shortcuts"><strong>Add Shortcuts</strong></h4>
<p>Edit your ~/.zshrc file to include aliases for convenience. For example:</p>
<pre><code class="lang-plaintext">alias x86="env /usr/bin/arch -x86_64 /bin/zsh - login"
alias arm="env /usr/bin/arch -arm64 /bin/zsh - login"
</code></pre>
<h3 id="heading-custom-brew-packages-and-zsh-configuration"><strong>Custom Brew Packages and Zsh Configuration</strong></h3>
<p>To further enhance your development environment, you can reference and use custom configurations from my personal repository.</p>
<p>This repository contains my curated list of <strong>brew packages</strong> , <strong>Zsh plugins</strong> , and <strong>shortcuts</strong> to optimize productivity.</p>
<h4 id="heading-access-the-repository"><strong>Access the Repository</strong></h4>
<p><a target="_blank" href="https://github.com/devangtomar/zsh-settings">GitHub - devangtomar/zsh-settings: This repository is dedicated to storing and managing my custom Zsh settings and configurations ⚙️</a></p>
<p>From the repository, you can:</p>
<ul>
<li><p>Get a list of Homebrew packages I frequently use.</p>
</li>
<li><p>Import my custom ~/.zshrc settings to streamline your shell experience.</p>
</li>
</ul>
<p>Clone the repository to your local machine:</p>
<pre><code class="lang-plaintext">git clone https://github.com/devangtomar/zsh-settings.git
</code></pre>
<p>Navigate to the directory and explore the setup:</p>
<pre><code class="lang-plaintext">cd zsh-settings
</code></pre>
<p>Feel free to fork or adapt the configurations to match your workflow!</p>
<h3 id="heading-configuring-git"><strong>Configuring Git</strong></h3>
<p>Set up your Git global configuration:</p>
<pre><code class="lang-plaintext">touch ~/.gitconfig
</code></pre>
<p>Add the following content to customize Git commands:</p>
<pre><code class="lang-plaintext">[user]
  name = Your Name
  email = your_email@example.com
[github]
  user = username
[alias]
  a = add
  cm = commit -m
  s = status
  p = push
  co = checkout
  fp = fetch --prune --all
  l = log --oneline --decorate --graph
[push]
 autoSetupRemote = true
</code></pre>
<p>With the above aliases, I can run git s instead of git status, for example. It will also automatically set up your remote, so you can do git push on a branch without specifying the upstream origin.</p>
<h3 id="heading-generate-ssh-keys"><strong>Generate SSH Keys</strong></h3>
<p>Create an SSH key for authentication, Start ssh-agent and adding the key:</p>
<pre><code class="lang-plaintext">ssh-keygen -t ed25519 -C "your_email@example.com"
eval "$(ssh-agent -s)"
ssh-add - apple-use-keychain ~/.ssh/id_ed25519
</code></pre>
<p>For easier management, create an SSH config file (~/.ssh/config):</p>
<pre><code class="lang-plaintext">Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_ed25519

Host myssh
  HostName example.com
  User user
  IdentityFile ~/.ssh/key.pem
</code></pre>
<p>Now just run the alias to connect.</p>
<pre><code class="lang-plaintext">ssh myssh
</code></pre>
<h3 id="heading-tuning-macos-settings"><strong>Tuning macOS Settings</strong></h3>
<p>To improve productivity, adjust these macOS settings:</p>
<h4 id="heading-sidebar">Sidebar</h4>
<p>To get the Home folder in the finder, press CMD + SHIFT + H and drag the home folder to the sidebar.</p>
<h4 id="heading-general">General</h4>
<ul>
<li>Make Google Chrome default browser</li>
</ul>
<h4 id="heading-dock">Dock</h4>
<ul>
<li><p>Automatically hide and show Dock</p>
</li>
<li><p>Show indicators for open applications</p>
</li>
</ul>
<h4 id="heading-keyboard">Keyboard</h4>
<ul>
<li><p>Key Repeat -&gt; Fast</p>
</li>
<li><p>Delay Until Repeat -&gt; Short</p>
</li>
<li><p>Disable “Correct spelling automatically”</p>
</li>
<li><p>Disable “Capitalize words automatically”</p>
</li>
<li><p>Disable “Add period with double-space”</p>
</li>
<li><p>Disable “Use smart quotes and dashes”</p>
</li>
</ul>
<h4 id="heading-security-and-privacy">Security and Privacy</h4>
<ul>
<li><p>Allow apps downloaded from App Store and identified developers</p>
</li>
<li><p>Turn FileVault On (makes sure SSD is securely encrypted)</p>
</li>
</ul>
<h4 id="heading-sharing">Sharing</h4>
<ul>
<li><p>Change computer name</p>
</li>
<li><p>Make sure all file sharing is disabled</p>
</li>
</ul>
<h4 id="heading-users-amp-groups">Users &amp; Groups</h4>
<ul>
<li>Add “Rectangle” to Login items</li>
</ul>
<h4 id="heading-defaults">Defaults</h4>
<p>A few more commands to change some defaults.</p>
<pre><code class="lang-plaintext"># Show Library folder
chflags nohidden ~/Library
# Show hidden files
defaults write com.apple.finder AppleShowAllFiles YES
# Show path bar
defaults write com.apple.finder ShowPathbar -bool true
# Show status bar
defaults write com.apple.finder ShowStatusBar -bool true
# Prevent left and right swipe through history in Chrome
defaults write com.google.Chrome AppleEnableSwipeNavigateWithScrolls -bool false
</code></pre>
<h3 id="heading-application-specific-tips">Application-Specific Tips</h3>
<h4 id="heading-chrome">Chrome</h4>
<ul>
<li><p>Install <a target="_blank" href="https://chromewebstore.google.com/detail/ublock-origin/cjpalhdlnbpafiamejdnhcphjbkeiagm">uBlock Origin</a></p>
</li>
<li><p>Install <a target="_blank" href="https://chromewebstore.google.com/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en">React DevTools</a></p>
</li>
<li><p>Install <a target="_blank" href="https://chromewebstore.google.com/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en">Redux DevTools</a></p>
</li>
<li><p>Install <a target="_blank" href="https://chromewebstore.google.com/detail/duplicate-tab-shortcut/klehggjefofgiajjfpoebdidnpjmljhb?hl=en">Duplicate Tab Shortcut</a></p>
</li>
<li><p>Settings -&gt; Set theme to “Dark”</p>
</li>
</ul>
<h4 id="heading-visual-studio-code">Visual Studio Code</h4>
<p>Press CMD + SHIFT + P and click "Install code command in PATH".</p>
<p>Now you can use code {file} to open any file in VSCode.</p>
<h4 id="heading-extensions">Extensions</h4>
<ul>
<li><p>Install <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=DevangTomar.vscode-diverse-dye">Diverse Dye</a></p>
</li>
<li><p>Install <a target="_blank" href="https://gitlens.amod.io/">GitLens</a></p>
</li>
<li><p>Install <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=vincaslt.highlight-matching-tag">Highlight Matching Tag</a></p>
</li>
<li><p>Install <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">ESLint</a></p>
</li>
<li><p>Install <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">Prettier</a></p>
</li>
</ul>
<h4 id="heading-rectangle">Rectangle</h4>
<ul>
<li><p>Full Screen: CMD + SHIFT + ' (prevents messing with other commands)</p>
</li>
<li><p>Left Half: CMD + OPTION + LEFT</p>
</li>
<li><p>Right Half: CMD + OPTION + RIGHT</p>
</li>
</ul>
<h4 id="heading-iterm2">iTerm2</h4>
<p>For some reason, iTerm2 does not let you use ⌥ + ← and → to tab through words in the terminal by default. I found this article to fix it: <a target="_blank" href="https://coderwall.com/p/h6yfda/use-and-to-jump-forwards-backwards-words-in-iterm-2-on-os-x">Use ⌥← and ⌥→ to jump forwards / backwards</a></p>
<ul>
<li><p>Go to Profiles -&gt; Keys:</p>
</li>
<li><p>Change ⌥← via "Send Escape Sequence" with b</p>
</li>
<li><p>Change ⌥→ via "Send Escape Sequence" with f</p>
</li>
</ul>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732442374382/125ea324-07a8-42d1-a4b6-64927ec2ede6.jpeg" alt class="image--center mx-auto" /></p>
<p>This guide is designed to provide a quick, repeatable process for setting up a Mac for development. By automating installations and configuring settings upfront, you can focus on coding and productivity rather than setup hassles.</p>
<h3 id="heading-connect-with-me-on-social-media">Connect with Me on Social Media</h3>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/@devangtomar">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[How one line of code caused a $60 million loss 📉😓]]></title><description><![CDATA[60,000 people lost full phone service, half of AT&T’s network was down, and 500 airline flights were delayed On January 15th, 1990, AT&T’s New Jersey…]]></description><link>https://devangtomar.hashnode.dev/how-one-line-of-code-caused-a-60-million-loss-6cab28f863c4</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/how-one-line-of-code-caused-a-60-million-loss-6cab28f863c4</guid><category><![CDATA[ Cost Of Bad Code]]></category><category><![CDATA[ Coding Code Review]]></category><category><![CDATA[bad code]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[horror]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Tue, 30 Jan 2024 18:32:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706935863893/8758352d-d0ae-46cf-8546-4bdaf100645a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>60,000 people lost full phone service, half of AT&amp;T’s network was down, and 500 airline flights were delayed</p>
<p>On January 15th, 1990, AT&amp;T’s New Jersey operations center detected a widespread system malfunction, shown by a plethora of red warnings on their network use display.</p>
<p><strong>Despite attempts to rectify the situation, the network remained compromised for 9 hours, leading to a 50% failure rate in call connections.</strong></p>
<p>AT&amp;T lost over <strong>$60 million</strong> as a result with <strong>over 60,000 of Americans left with fully disconnected phones</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706935855811/b8ddd066-9573-4334-a2ef-977b37b2ce4a.png" alt class="image--center mx-auto" /></p>
<p>Furthermore, <strong>500 airline flights were delayed, affecting 85,000 people.</strong></p>
<p>AT&amp;T’s long-distance network was supposedly a paragon of efficiency, handling a substantial portion of the nation’s calls with its advanced electronic switches and signaling system. This system usually completed call routing within seconds.</p>
<p>However, on this day, a fault originating in a New York switch cascaded through the network. <strong>This was due to a software bug in a recent update that contained a critical bug affecting the network’s 114 switches.</strong> When the New York switch reset itself and sent out signals, this bug caused a domino effect, leading to widespread network disruption.</p>
<p><strong>This software patch had already gone through layers of testing without being caught. This incident was especially surprising because AT&amp;T was known for their rigorous testing.</strong></p>
<h3 id="heading-the-problem">The Problem 😓</h3>
<p>The root cause was traced back to a coding error in a software update implemented across the network’s switches.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706935857691/d0c23dd7-16be-45d6-8b5b-20b244ddafd2.jpeg" alt /></p>
<p>The error, within a C program, involved a misplaced <em>break</em> statement within nested conditional statements, leading to data overwrites and system resets.</p>
<p>The pseudocode :</p>
<pre><code class="lang-python"><span class="hljs-keyword">while</span> (ring receive buffer <span class="hljs-keyword">not</span> empty 
          <span class="hljs-keyword">and</span> side buffer <span class="hljs-keyword">not</span> empty):

  Initialize pointer to first message <span class="hljs-keyword">in</span> side buffer
       <span class="hljs-keyword">or</span> ring receive buffer

  get copy of buffer

  switch (message):

    case (incoming_message):

      <span class="hljs-keyword">if</span> (sending switch <span class="hljs-keyword">is</span> out of service):

        <span class="hljs-keyword">if</span> (ring write buffer <span class="hljs-keyword">is</span> empty):

          send <span class="hljs-string">"in service"</span> to status map

        <span class="hljs-keyword">else</span>:

          <span class="hljs-keyword">break</span> // The error was here!

        END IF

      process incoming message, set up pointers to
               optional parameters

      <span class="hljs-keyword">break</span>
    END SWITCH


do optional parameter work
</code></pre>
<p>The problem:</p>
<ul>
<li><p>If the <em>ring write buffer is NOT empty</em>, then the `if` statement on line 7 is skipped and the <em>break</em> statement on line 10 is hit instead.</p>
</li>
<li><p>However, for the program to function properly, line 11 should have been hit instead.</p>
</li>
<li><p>When the <em>break</em> statement is hit instead of the incoming message being processed and pointers being set up to optional parameters, then data (the pointers that should’ve been held) is overwritten</p>
</li>
<li><p>The error correction software identified the data overwrite and initiated a shutdown of the switch for a reset. This issue was compounded because this flawed software was present in all switches across the network, leading to a chain reaction of resets that ultimately crippled the entire network system.</p>
</li>
</ul>
<p>Despite having a network designed for resilience, <strong>one line of code was able to bring down half the country’s main line of communication.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706935859038/d3967688-bb61-4c8d-824e-c346d2021a3c.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-the-fix">The Fix 🔨</h3>
<p>It took engineers 9 hours to get AT&amp;T’s system fully back online. They did so mostly by rolling back the switches to a previous, working version of code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706935860518/b44d2c91-c065-481c-b4c5-e12c8610aaba.jpeg" alt class="image--center mx-auto" /></p>
<p>It actually took software engineers two weeks of rigorous code reading, testing, and replication to actually understand where the bug was.</p>
<h3 id="heading-conclusion">Conclusion 💭</h3>
<p>For AT&amp;T, unfortunately, this wasn’t even their biggest system crash of the 90s. They encountered many more issues later in the decade.</p>
<p><strong>In reality, it wasn’t one line of code that brought down a system</strong>. It was a failure in processes.</p>
<p>Today’s companies have even better processes in place, and even then, bugs slip through. Google wrote a great retrospective on <a target="_blank" href="https://sre.google/resources/practices-and-processes/twenty-years-of-sre-lessons-learned/">20 years of Site Reliability Engineering</a>, where they reflect on YouTube’s first global outage in 2016.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706935862141/efa35110-ee79-4e30-8405-8480a68e4eed.jpeg" alt /></p>
<p>The scale of an outage for companies is huge and there are lessons to be learned from each outage. For most, however, outages come down to human error and gaps in processes.</p>
<h3 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h3>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[How Facebook Keeps Millions of Servers Synced 🕰️⏰]]></title><description><![CDATA[If you’re running a distributed system, it’s incredibly important to keep the system clocks of the machines synchronized. If the machines are off by a few…]]></description><link>https://devangtomar.hashnode.dev/how-facebook-keeps-millions-of-servers-synced-efb88f-6d6ebd519963</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/how-facebook-keeps-millions-of-servers-synced-efb88f-6d6ebd519963</guid><category><![CDATA[Facebook]]></category><category><![CDATA[synchronous]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[System Design]]></category><category><![CDATA[facebookads]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 26 Jan 2024 05:31:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706333484124/cbb9bc19-c6ba-4c04-b66b-47e62b5ac4b9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you’re running a distributed system, it’s <em>incredibly</em> important to keep the system clocks of the machines synchronized. If the machines are off by a few seconds, this will cause a huge variety of different issues.</p>
<p>You can probably imagine why unsynchronized clocks would be a big issue, but just to beat a dead horse…</p>
<p>Today, let’s dive into the intricate world of time synchronization at Meta. Buckle up, it’s not just about ticking clocks; it’s about the heartbeat of millions of servers! 💻🌐</p>
<h4 id="heading-why-sync-matters">⏳ Why Sync Matters</h4>
<p>Running a distributed system? Syncing system clocks is crucial! 🔄 Unsynchronized clocks? Brace yourself for data inconsistency, log chaos, security issues, and more! Facebook knows this too well.</p>
<h4 id="heading-meet-ntp-and-ptp">🌐 Meet NTP and PTP</h4>
<p>NTP: Old but gold. Syncs computers within milliseconds. How? Clients talk to NTP servers, adjusting internal time based on roundtrip delays.</p>
<p>PTP: The shiny new kid. Precision to nanoseconds or even picoseconds! It tackles network delays with hardware timestamping. But, watch out for the load it places on network hardware! 💽⚙️</p>
<h4 id="heading-facebooks-sync-symphony">🌟 Facebook’s Sync Symphony</h4>
<p>NTP Days: Facebook danced with Ntpd and Chrony. Chrony brought nanoseconds to the party, but the story doesn’t end there.</p>
<p>PTP Era: In 2022, Facebook waved goodbye to NTP, embracing Precision Time Protocol for superior precision and scalability. Say hello to nanosecond accuracy! 🚀</p>
<p>Absolutely, let’s break down the details of Meta’s pursuit of nanosecond accuracy using Precision Time Protocol (PTP) and the key components involved:</p>
<h4 id="heading-aim-nanoseconds">🏹 Aim: Nanoseconds! 🎯</h4>
<p>Meta’s shift to PTP comes with the ambitious goal of achieving nanosecond-level accuracy in time synchronization. This precision is crucial in the fast-paced world of distributed systems where every second matters.</p>
<h3 id="heading-components-leading-the-charge">🌐 Components Leading the Charge</h3>
<h4 id="heading-ptp-rack">PTP Rack</h4>
<p>The PTP Rack is the nerve center, housing the hardware and software responsible for serving time to clients. Here’s what makes it tick:</p>
<p>- <strong>GNSS Antenna</strong>: This critical component communicates with the Global Navigation Satellite System (GNSS). It ensures that the PTP system is in sync with the global positioning signals, enhancing accuracy.  </p>
<p>- <strong>Time Appliance:</strong> A dedicated piece of hardware residing in the PTP Rack. It combines a GNSS receiver and a miniaturized atomic clock. This combination ensures that even in scenarios where GNSS connectivity is lost, the Time Appliance can maintain accurate timekeeping independently.</p>
<p>The PTP Rack, with its GNSS synchronization and atomic clock precision, sets the stage for achieving the nanosecond goal.</p>
<h4 id="heading-the-network">The Network</h4>
<p>The network plays a pivotal role in transmitting PTP messages from the PTP Rack to clients. Meta employs unicast transmission, a communication method where information flows from one sender (PTP Rack) to a single recipient (PTP Client). This choice simplifies network design and enhances scalability.</p>
<p>Unicast transmission ensures that each client receives the necessary time synchronization information directly from the PTP Rack, reducing the complexity that could arise in a multicast setup.</p>
<h4 id="heading-ptp-client">PTP Client</h4>
<p>Running on individual machines, the PTP Client is the endpoint that actively communicates with the PTP network. Meta uses an open-source PTP client called ptp4l for this purpose. However, the implementation wasn’t without its challenges, especially when dealing with edge cases.</p>
<p>- <strong>Open Source Client:</strong> Ptp4l is an open-source implementation, reflecting Meta’s commitment to transparency and community collaboration. It’s a tool that facilitates communication between the PTP Rack and individual servers, allowing them to synchronize their clocks with nanosecond precision.</p>
<p>- <strong>Challenges with Edge Cases:</strong> While ptp4l is a robust tool, Meta acknowledges challenges faced in specific scenarios or with certain types of network cards. These edge cases required additional attention to ensure the seamless functioning of the PTP system.</p>
<h4 id="heading-benefits-of-the-ptp-system">🌟 Benefits of the PTP System</h4>
<p>- <strong>Higher Precision and Accuracy:</strong> The PTP system allows Meta to achieve precision within nanoseconds, a significant leap from the millisecond-level synchronization provided by traditional methods like NTP.</p>
<p>- <strong>Better Scalability:</strong> Unicast transmission reduces the frequency of check-ins required for synchronization, enabling smoother network operation as the system scales. A single source of truth for timing enhances overall scalability.</p>
<p>- <strong>Mitigation of Network Delays and Errors:</strong> PTP’s focus on hardware timestamping and transparent clocks helps reduce the impact of network delays and errors, contributing to a more robust and reliable synchronization process.</p>
<p>In essence, the PTP trio — PTP Rack, The Network, and PTP Client — embodies Meta’s commitment to precision, scalability, and overcoming challenges in the pursuit of nanosecond-level accuracy in time synchronization.</p>
<h3 id="heading-network-time-strata-explained">🌐 Network Time Strata Explained:</h3>
<p>NTP organizes computers into hierarchical layers called “strata” based on their proximity to highly accurate time sources, typically atomic clocks or GPS receivers. Each stratum represents a level in the hierarchy, and the lower the stratum number, the closer a device is to the primary time source.</p>
<p><strong>1. Stratum 0: Atomic Clock or GPS Receiver:</strong></p>
<ul>
<li><p>At the top of the hierarchy are devices with direct access to incredibly precise timekeeping mechanisms, such as atomic clocks or GPS receivers.</p>
</li>
<li><p>Stratum 0 devices serve as the primary time source for the entire synchronization network.</p>
</li>
</ul>
<p><strong>2. Stratum 1: Directly Synced with Stratum 0:</strong></p>
<ul>
<li><p>Stratum 1 devices are directly synchronized with Stratum 0 devices. These could be servers or systems that have a direct connection to the primary time source.</p>
</li>
<li><p>Stratum 1 devices act as secondary time sources for the next level of devices in the hierarchy.</p>
</li>
</ul>
<p><strong>3. Stratum 2: Syncs with Stratum 1:</strong></p>
<ul>
<li><p>Stratum 2 devices synchronize their clocks with Stratum 1 devices. These devices are one step further away from the primary time source.</p>
</li>
<li><p>Stratum 2 devices act as time sources for devices in the subsequent stratum.</p>
</li>
</ul>
<p><strong>4. … and so on, until Stratum 15: Indicating Unsynced Devices:</strong></p>
<ul>
<li><p>The strata continue in a cascading manner, with each stratum representing a level of hierarchy further away from the primary time source.</p>
</li>
<li><p>As the stratum number increases, the accuracy of time synchronization decreases.</p>
</li>
</ul>
<p><strong>5. Stratum 16: Unsynced Devices:</strong></p>
<ul>
<li>Stratum 16 is a special designation used to indicate devices that are not synchronized with any source. It represents the highest stratum number and signifies unsynchronization.</li>
</ul>
<h4 id="heading-how-synchronization-works">🔄 How Synchronization Works</h4>
<ul>
<li><p>Computers in lower strata synchronize their clocks with devices in higher strata. For example, Stratum 2 devices synchronize with Stratum 1 devices, and so on.</p>
</li>
<li><p>Multiple devices in the same stratum can be synchronized with different devices in a higher stratum, introducing redundancy and fault tolerance.</p>
</li>
</ul>
<h4 id="heading-why-the-hierarchy-matters">🔍 Why the Hierarchy Matters</h4>
<ul>
<li><p>The hierarchical structure ensures that not every device needs to directly synchronize with the most accurate time source. This arrangement prevents overloading a single time server with numerous synchronization requests.</p>
</li>
<li><p>The hierarchy allows for redundancy and fault tolerance. If a device in a lower stratum loses synchronization, it can quickly switch to another source in the same stratum or a higher one.</p>
</li>
</ul>
<h4 id="heading-benefits">🌟 Benefits</h4>
<ul>
<li><p>Efficient Synchronization: Devices in lower strata benefit from the accuracy of those in higher strata, optimizing the synchronization process.</p>
</li>
<li><p>Scalability: The hierarchical structure scales well, allowing for the expansion of the synchronization network without overwhelming primary time sources.</p>
</li>
</ul>
<p>Understanding Network Time Strata provides insights into how NTP organizes and maintains time synchronization across a distributed system, ensuring accuracy and efficiency in timekeeping.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706333482023/877df832-6bf7-4648-b972-7dfc0ce5befc.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-conclusion">🚀 Conclusion</h4>
<p>Syncing clocks isn’t just about ticking seconds; it’s the heartbeat of a well-functioning system. Facebook’s journey from NTP to PTP showcases the relentless pursuit of precision and scalability. Time, after all, waits for no server! ⏰💡</p>
<p>What are your thoughts on Meta’s clockwork precision? Share your views! 👇</p>
<p>Happy Syncing! 🌐🚀</p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[How Cloudflare Achieved 55 Million Requests per Second with Just 15 PostgreSQL Clusters! 💻]]></title><description><![CDATA[In the vast landscape of the internet, Cloudflare emerged in July 2009, founded by a group of visionaries with the goal of making the internet faster and…]]></description><link>https://devangtomar.hashnode.dev/how-cloudflare-achieved-55-million-requests-per-second-with-just-15-postgresql-clusters-2d8a28ffd100</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/how-cloudflare-achieved-55-million-requests-per-second-with-just-15-postgresql-clusters-2d8a28ffd100</guid><category><![CDATA[cloudflare]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[System Design]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[Devops articles]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 19 Jan 2024 05:32:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815795579/711faec2-4493-4d62-98e0-b51a91ae0d07.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the vast landscape of the internet, Cloudflare emerged in July 2009, founded by a group of visionaries with the goal of making the internet faster and more reliable. The challenges they faced were immense, but their growth was nothing short of spectacular. Fast forward to today, and Cloudflare serves a whopping 20% of the internet’s traffic, handling a staggering 55 million HTTP requests per second. The most incredible part? They achieved this feat with only 15 PostgreSQL clusters. Let’s dive into the magic behind this impressive system design!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815780808/9ccdc664-8351-433c-a14d-05f298cd47db.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-postgresql-scalability-the-core">PostgreSQL Scalability: The Core 🚀</h3>
<h4 id="heading-resource-usage-optimization-with-pgbouncer">Resource Usage Optimization with PgBouncer 🔄</h4>
<p>Handling Postgres connections efficiently is crucial, and Cloudflare uses PgBouncer as a TCP proxy to manage a pool of connections to Postgres.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815782364/f8939662-5362-43ac-8d61-a9ca0dc99e5e.jpeg" alt /></p>
<p>This not only prevents connection starvation but also tackles the challenge of diverse workloads from different tenants within a cluster.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815783954/562fa571-27c1-4509-b329-af0bc6a05d77.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-thundering-herd-problem-solved">Thundering Herd Problem Solved! 🐘</h4>
<p>The infamous Thundering Herd Problem, where many clients query a server concurrently, was addressed by Cloudflare using PgBouncer. It smartly throttles the number of Postgres connections created by a specific tenant, preventing degradation of database performance during high traffic.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815785847/c3b0c450-1155-4751-b7f1-92ac301bd756.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-performance-boost-with-bare-metal-servers-and-haproxy">Performance Boost with Bare Metal Servers and HAProxy ⚙️</h4>
<p>Cloudflare opts for bare metal servers without virtualization, ensuring high performance. They leverage HAProxy as an L4 load balancer, distributing traffic across primary and secondary database read replicas, providing a robust solution for performance enhancement.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815787098/63a0e739-2b9a-4ffd-90b8-e00c947e8464.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-congestion-avoidance-algorithm-for-concurrency">Congestion Avoidance Algorithm for Concurrency 🚧</h4>
<p>To manage concurrent queries and avoid performance degradation, Cloudflare employs the TCP Vegas congestion avoidance algorithm.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815788380/360ee687-27fb-4bb5-ade9-e661cc7d42f5.png" alt class="image--center mx-auto" /></p>
<p>This algorithm samples each tenant’s transaction round-trip time to Postgres, dynamically adjusting the connection pool size to throttle traffic before resource starvation occurs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815789952/22c812c3-a772-4e2b-a55a-0785d840b3ce.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-ordering-queries-strategically-with-priority-queues">Ordering Queries Strategically with Priority Queues 📊</h4>
<p>Cloudflare tackles query latency by ranking queries at the PgBouncer layer using queues based on historical resource consumption.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815791437/6f77b408-27bf-4f7a-8cc0-ecd49985fc2e.jpeg" alt class="image--center mx-auto" /></p>
<p>Enabling priority queuing only during peak traffic ensures that queries needing more resources are handled efficiently without causing resource starvation.</p>
<h4 id="heading-high-availability-with-stolon-cluster-manager">High Availability with Stolon Cluster Manager 🌐</h4>
<p>Ensuring high availability is a top priority for Cloudflare. They employ the Stolon cluster manager, replicating data across Postgres instances, and performing failovers seamlessly in peak traffic. With data replication across regions and proactive network testing, Cloudflare ensures a robust and resilient system.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815792842/1781a96a-6a8d-49d9-8318-97a20b8d12c8.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-conclusion">Conclusion 🌈</h4>
<p>Cloudflare’s journey to handling 55 million requests per second with just 15 PostgreSQL clusters is a testament to their ingenious system design. From smart connection pooling to tackling concurrency and ensuring high availability, they’ve navigated the complexities of scaling with finesse. Subscribe to our newsletter for more simplified case studies and unravel the secrets behind the tech giants’ success! 🚀🔍</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705815794188/8b0a6207-6a26-4c84-910e-7af1923a40d1.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[The World Depends on 60-Year-Old Code No One Knows Anymore 👴🏻🚀]]></title><description><![CDATA[In a digital era driven by cutting-edge technology, an unexpected hero emerges from the shadows: COBOL, a 64-year-old programming language quietly…]]></description><link>https://devangtomar.hashnode.dev/the-world-depends-on-60-year-old-code-no-one-knows-anymore-65b0d2a4a171</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/the-world-depends-on-60-year-old-code-no-one-knows-anymore-65b0d2a4a171</guid><category><![CDATA[COBOL]]></category><category><![CDATA[legacy]]></category><category><![CDATA[legacy-systems]]></category><category><![CDATA[coding]]></category><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sat, 13 Jan 2024 13:57:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705154231182/fdb6e1b2-82fa-4c9b-9b38-995f00166369.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In a digital era driven by cutting-edge technology, an unexpected hero emerges from the shadows: COBOL, a 64-year-old programming language quietly orchestrating 3 trillion dollars worth of transactions daily. But here’s the catch — hardly anyone knows it anymore. This article dives deep into the reliance on COBOL, the scarcity of skilled programmers, and IBM’s ambitious solution with Watsonx. 💻💸</p>
<p><img src="https://miro.medium.com/v2/resize:fit:758/1*txzZkQMsZXgmbhzBOGHpgg.png" alt class="image--center mx-auto" /></p>
<p><strong>🕰️ A Legacy Language Still in Control</strong></p>
<p>Despite being neglected by educational institutions, COBOL thrives in critical industries like banking, automotive, insurance, government, healthcare, and finance. A staggering 43 percent of banking systems still rely on COBOL, managing $3 trillion daily transactions, including a whopping 95 percent of all US ATM activity and 80 percent of in-person credit card transactions. The problem? Few are eager to learn the language, and those who can handle it are aging out of the workforce.</p>
<h4 id="heading-the-conundrum-code-maintenance-vs-skill-shortage"><strong>🤔 The Conundrum: Code Maintenance vs. Skill Shortage</strong></h4>
<p>Maintaining and modernizing COBOL is crucial, but the shortage of skilled workers poses a significant challenge. The dwindling tribe of “COBOL cowboys” is facing retirement, and the quest for replacements yields slim pickings. The stage is set for a conundrum: how do we keep the wheels turning without the skilled hands needed to maintain the code?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705154226588/b8c94af0-4616-497b-ab07-c3a47ea2fd8b.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-enter-watsonx-ai-to-the-rescue"><strong>🤖 Enter Watsonx: AI to the Rescue</strong></h4>
<p>IBM steps into the arena with a bold proposition — Watsonx, an AI-powered code assistant designed to bridge the gap. The concept is simple yet groundbreaking: Watsonx transforms aging COBOL code into a more modern language, sparing programmers countless hours of reprogramming. It’s akin to ChatGPT translating English into Esperanto, but for coding.</p>
<h4 id="heading-ibms-vision-an-ai-powered-coding-revolution"><strong>🚀 IBM’s Vision: An AI-Powered Coding Revolution</strong></h4>
<p>Keri Olson, IBM’s Vice President of Product Management, IT Automation, unveils the magic behind Watsonx. It’s an end-to-end solution involving a multi-step process. Once the application landscape, data flow, and dependencies are understood, applications are refactored. Developers then selectively choose smaller pieces for modernization. But here’s the catch — Watsonx is not a developer replacement; it’s a productivity enhancement. The partnership between humans and AI remains essential.</p>
<h4 id="heading-hurdles-on-the-horizon-skepticism-and-uncertainty"><strong>🌌 Hurdles on the Horizon: Skepticism and Uncertainty</strong></h4>
<p>While Watsonx holds the promise of a coding revolution, skepticism looms. The ghosts of IBM’s past, notably the Watson Health project, make some wary. Arun Chandrasekara, Gartner Distinguished Vice President and Analyst, raises concerns, stating, “IBM has no case studies, at this time, to validate its claims.” The cautionary ‘wait and see’ approach prevails, as the AI generation is still in its early stages.</p>
<h4 id="heading-the-future-bright-or-uncertain"><strong>🔮 The Future: Bright or Uncertain?</strong></h4>
<p>As Watsonx takes its first steps, the industry watches with bated breath. IBM acknowledges the newness and unproven nature of the technology but remains optimistic about its potential. The journey is just beginning, and the intersection of Z computing, mainframe experience, and AI might pave the way for a revolutionary AI experience.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705154228203/2c35cfc0-08a6-4cde-ac31-00450cf0a9c2.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-conclusion-navigating-the-future-with-watsonx"><strong>🌈 Conclusion: Navigating the Future with Watsonx</strong></h4>
<p>In a world where 60-year-old code dictates financial ecosystems, Watsonx emerges as a beacon of hope. Will it be the silver bullet to the COBOL conundrum, or will skepticism prevail? Only time will tell. As we stand on the precipice of a coding revolution, the collaboration between human ingenuity and AI innovation holds the key to steering the course of our digital future. 💡🤖</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705154229664/6ea4f263-b8ff-451a-b76c-df3e0979d2f5.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-connect-with-me-on-social-media"><strong>Connect with Me on social media 📲</strong></h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Pinterest’s Epic Journey from 10K to 22M Users with Just 6 Engineers 🚀🤯]]></title><description><![CDATA[Once upon a digital epoch, Pinterest, the image-centric social network, defied all odds by skyrocketing to 11 million users with a team of only 6 engineers]]></description><link>https://devangtomar.hashnode.dev/navigating-the-digital-landscape-pinterests-epic-journey-from-10k-to-22m-users-with-just-6-71273d90bf34</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/navigating-the-digital-landscape-pinterests-epic-journey-from-10k-to-22m-users-with-just-6-71273d90bf34</guid><category><![CDATA[pinterest]]></category><category><![CDATA[software development]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 07 Jan 2024 19:16:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654838568/fabebf9c-df2c-44a3-bd8f-c20cc76a0790.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Once upon a digital epoch, Pinterest, the image-centric social network, defied all odds by skyrocketing to 11 million users with a lean team of only 6 engineers. Fasten your seat belts as we unravel the enthralling saga of how Pinterest triumphed over scaling challenges, embracing both triumphs and stumbles in its quest for digital dominance.</p>
<h3 id="heading-the-pinterest-odyssey-unveiled">The Pinterest Odyssey Unveiled 🌌</h3>
<p>In the enigmatic year of 2012, Pinterest proudly flaunted its 11 million monthly active users, achieving this feat with a mere half-dozen engineers. This saga began in March 2010, where the pioneers launched with a single engineer and a small MySQL database. The journey was fraught with lessons, a mix of innovation and simplicity.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654828586/ca105241-f9a2-41ab-91f6-cd747cc6dd84.png" alt /></p>
<h3 id="heading-the-art-of-scaling-lessons-learned"><strong>The Art of Scaling - Lessons Learned 🧠</strong></h3>
<p><strong>1. Proven Technologies Rule 🛠️</strong> : Pinterest adhered to the wisdom of using known technologies, steering clear of the pitfalls of diving into uncharted waters.  </p>
<p><strong>2. Simplicity Triumphs 🏰 :</strong> A recurring theme in their journey - keeping it simple. Complexity was the villain they vanquished at every turn.</p>
<p><strong>3. Scaling Wisdom 🚀 :</strong> Pinterest's decision to add more of the same nodes to scale, avoiding unnecessary creativity, was a pivotal move in their playbook.</p>
<p><strong>4. Database Dances 💽 :</strong> Sharding databases took precedence over clustering, optimizing data transfer and steering clear of potential pitfalls.</p>
<p><strong>5. The Joy of Engineering 🎉 :</strong> Engineers at Pinterest weren't just coders; they were contributors from day one, infusing the spirit of innovation into the company's DNA.</p>
<h3 id="heading-pinterests-architectural-evolution"><strong>Pinterest's Architectural Evolution 🛠️</strong></h3>
<p>As the months rolled by, Pinterest's architecture evolved. From a basic web server stack to embracing Django for their backend, they navigated the maze of growth with agility.</p>
<h3 id="heading-the-misstep-in-over-complication"><strong>The Misstep in Over-Complication 🤯</strong></h3>
<p>In the race to accommodate their rapidly growing user base, Pinterest hit a snag. Their architecture became an intricate tapestry woven with five different database technologies, causing chaos.</p>
<ul>
<li><p>Membase (Now Couchbase)</p>
</li>
<li><p>Cassandra</p>
</li>
<li><p>Elasticsearch</p>
</li>
<li><p>MongoDB</p>
</li>
<li><p>NGINX</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654829858/51dcf1a0-5a5c-4a58-89f0-b4ac00d2e880.png" alt /></p>
<p><strong>⚠️ Cluster Management Nightmare :</strong> Clustering complexities led to data corruption and unfixable problems. Pinterest's solution? A bold move to stick with the proven: MySQL and Memcached.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654831290/5737ca0a-3a2f-4747-a256-de9531abd5b9.png" alt /></p>
<h3 id="heading-simplification-triumphs-in-2012">Simplification Triumphs in 2012 🏆</h3>
<p>Come January 2012, Pinterest, now handling a staggering 11 million users, had undergone a transformation. The architecture was streamlined, shedding less-proven concepts for robust alternatives.</p>
<p><strong>Pinterest's Simplified Stack 🏗️</strong><br />- Amazon EC2 + S3 + Akamai<br />- AWS ELB (Elastic Load Balancing)<br />- Flask for backend<br />- MySQL, Memcache, and sharding took center stage.</p>
<p><strong>Manual Sharding Mastery 🧩</strong></p>
<p>The art of manually sharding databases became Pinterest's forte. During the freeze, they incrementally and manually shard databases, removing table joins and embracing caching.</p>
<p><strong>The Pinterest Sharding Symphony 🎶</strong></p>
<ul>
<li><p>Feature freeze</p>
</li>
<li><p>Incremental and manual sharding</p>
</li>
<li><p>Unique constraints maintained in a colossal, unsharded database</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654832754/7e81b061-483d-442d-8e59-cd05fd596399.png" alt /></p>
<h3 id="heading-a-leap-to-22-million-users-in-2012">A Leap to 22 Million Users in 2012 🚀</h3>
<p>October 2012 marked Pinterest's ascent to 22 million users. The architecture remained the same, showcasing the power of replicating what works and scaling it up.</p>
<p><strong>Consistency Amidst Growth 🔄</strong><br />- Transition to SSDs<br />- Limited, proven choices for stability<br />- EC2 and S3 - a duo that stood the test of time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654834226/451b5e1b-aae4-44ce-9573-2e5d45ddffdb.png" alt /></p>
<h3 id="heading-pinterests-database-wizardry"><strong>Pinterest's Database Wizardry 🧙‍♂️</strong></h3>
<p>Unveiling the secrets behind Pinterest's database structure, the unique 64-bit ID structure, and the art of tables.</p>
<p><strong>ID Structure Magic 🎩</strong><br />- Shard ID, Type, Local ID - A 64-bit symphony orchestrated for scalability.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654835481/70fc53f3-d769-4da0-ab37-293feece936e.jpeg" alt /></p>
<p><strong>Tables Unveiled 📊</strong><br />- Object tables for pins, boards, comments, users<br />- Mapping tables for relational data<br />- Say goodbye to JOINs, embrace efficiency.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654836576/e2c2f550-c19f-41ea-9d3b-70bc6672f406.jpeg" alt /></p>
<h3 id="heading-conclusion-the-pinterest-legacy-continues">Conclusion : The Pinterest Legacy Continues 🚢</h3>
<p>Pinterest's journey is a testament to the delicate dance between innovation and simplicity. From the pitfalls of over-complication to the triumphs of proven choices, their saga is an inspiration for every tech pioneer. As we bid adieu to this riveting tale, Pinterest stands tall, a beacon in the digital wilderness.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704654837528/445a2625-fb10-48fc-870f-4493ecee62e7.jpeg" alt /></p>
<h3 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h3>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Navigating Asynchronous JavaScript: A Journey Through the Coffee Shop ☕🚀]]></title><description><![CDATA[Hello, fellow developers! Today, let’s unravel the mysteries of asynchronous JavaScript by immersing ourselves in the dynamic world of a bustling coffee…]]></description><link>https://devangtomar.hashnode.dev/navigating-asynchronous-javascript-a-journey-through-the-coffee-shop-aaa0dd19d724</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/navigating-asynchronous-javascript-a-journey-through-the-coffee-shop-aaa0dd19d724</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[asynchronous JavaScript]]></category><category><![CDATA[asynchronous programming]]></category><category><![CDATA[async/await]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Mon, 01 Jan 2024 18:21:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133281505/5bea61a6-1f9c-4114-90dd-725a9a2aed2b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello, fellow developers! Today, let’s unravel the mysteries of asynchronous JavaScript by immersing ourselves in the dynamic world of a bustling coffee shop. Get ready to explore the concepts of callbacks, promises, and the magic of async/await — all while sipping on a freshly brewed cup of coffee. ☕🚀</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133271238/a3856366-0695-4a23-8e1e-c3ae1d22825b.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-understanding-asynchronous-javascript"><strong>Understanding Asynchronous JavaScript 🤹🏻</strong></h4>
<p>If you’re looking to boost project efficiency, asynchronous JavaScript is your secret weapon. It allows you to break down intricate projects into manageable tasks. In this journey, we’ll delve into three techniques — callbacks, promises, and async/await — to conquer these tasks and achieve optimal results. Let’s dive right in! 🎖️</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133272884/8b362aa3-a7da-4733-9b2d-e44c4a2ba1af.jpeg" alt /></p>
<h4 id="heading-synchronous-vs-asynchronous-javascript"><strong>Synchronous vs Asynchronous JavaScript 🆚</strong></h4>
<p><strong>Synchronous System</strong>: Imagine having just one hand to complete multiple tasks — one at a time. JavaScript, by default, is synchronous (single-threaded). Tasks wait for the previous one to finish.</p>
<p><strong>Asynchronous System</strong>: Picture having multiple hands, each completing a task independently. In JavaScript, this asynchronous system enables tasks to proceed concurrently. No task waits for another, creating a more efficient workflow.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133274407/c64848e7-0011-4c3e-b9fb-cce6942d497b.png" alt /></p>
<p><strong>Synchronous Code Example</strong>:</p>
<pre><code class="lang-python">console.log(<span class="hljs-string">"Sip"</span>);
console.log(<span class="hljs-string">"Enjoy"</span>);
console.log(<span class="hljs-string">"Repeat"</span>);
</code></pre>
<p><strong>Asynchronous Code Example</strong>:</p>
<pre><code class="lang-python">console.log(<span class="hljs-string">"Sip"</span>);
// This will be shown after <span class="hljs-number">2</span> seconds

setTimeout(() =&gt; {
 console.log(<span class="hljs-string">"Enjoy"</span>);
}, <span class="hljs-number">2000</span>);

console.log(<span class="hljs-string">"Repeat"</span>);
</code></pre>
<p>Now that we’ve grasped the basics, let’s step into our coffee shop project and explore the magic of callbacks.</p>
<h4 id="heading-setting-up-our-coffee-shop-project"><strong>Setting Up Our Coffee Shop Project ☕</strong></h4>
<p>For this project, open your preferred code editor or Codepen.io. We’ll use the console to witness our coffee shop in action.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133276122/5101208a-fc49-4bb2-aa1e-06ee81f6f665.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-callbacks-in-javascript"><strong>Callbacks in JavaScript 📲</strong></h4>
<p>Callbacks come into play when you nest a function inside another function as an argument. Imagine a callback as taking smaller steps to complete a complex task. To illustrate, let’s start our coffee shop business with a storeroom for ingredients and a kitchen for production.</p>
<pre><code class="lang-python">let supplies = {
 Beans: [<span class="hljs-string">"Arabica"</span>, <span class="hljs-string">"Robusta"</span>, <span class="hljs-string">"Liberica"</span>],
 Liquid: [<span class="hljs-string">"water"</span>, <span class="hljs-string">"milk"</span>, <span class="hljs-string">"syrup"</span>],
 Cups: [<span class="hljs-string">"small"</span>, <span class="hljs-string">"medium"</span>, <span class="hljs-string">"large"</span>],
 Toppings: [<span class="hljs-string">"cinnamon"</span>, <span class="hljs-string">"chocolate"</span>]
};

let order = (beanType, callBrew) =&gt; {
 console.log(<span class="hljs-string">"Order placed. Please call brewing process"</span>);
 callBrew();
};

let brew = () =&gt; {
 console.log(<span class="hljs-string">"Brewing process initiated"</span>);
};

// Test our setup
order(<span class="hljs-string">"Arabica"</span>, brew);
</code></pre>
<p>With callbacks, we establish relationships between steps, crucial for tasks like serving the perfect cup of coffee. As we delve deeper into the project, the order of tasks becomes paramount.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133278566/82913376-17d1-4b9d-8cdb-82746cdda4b9.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-the-challenge-callback-hell"><strong>The Challenge: Callback Hell 😱</strong></h4>
<p>Nested callbacks can lead to a messy structure known as “Callback Hell.” It becomes challenging to maintain and understand the code. Fear not; there’s a hero on the horizon — promises!</p>
<h4 id="heading-escaping-callback-hell-with-promises"><strong>Escaping Callback Hell with Promises 🙅🏻</strong></h4>
<p>Promises were introduced to rescue us from the clutches of Callback Hell. They offer a cleaner structure and better task handling.</p>
<pre><code class="lang-python">let order = (time, work) =&gt; {
 <span class="hljs-keyword">return</span> new Promise((resolve, reject) =&gt; {
 <span class="hljs-keyword">if</span> (isShopOpen) {
 setTimeout(() =&gt; {
 console.log(`${supplies.Beans[beanType]} was selected`);
 resolve(work());
 }, time);
 } <span class="hljs-keyword">else</span> {
 reject(console.log(<span class="hljs-string">"Our shop is closed"</span>));
 }
 });
};

// Usage example
order(<span class="hljs-number">2000</span>, () =&gt; console.log(<span class="hljs-string">"Brewing process initiated"</span>))
 .then(() =&gt; order(<span class="hljs-number">1000</span>, () =&gt; console.log(<span class="hljs-string">"Liquid added"</span>)))
 .then(() =&gt; order(<span class="hljs-number">2000</span>, () =&gt; console.log(<span class="hljs-string">"Machine started"</span>)))
 .catch(() =&gt; console.log(<span class="hljs-string">"Customer left"</span>))
 .<span class="hljs-keyword">finally</span>(() =&gt; console.log(<span class="hljs-string">"End of the day"</span>));
</code></pre>
<p>With promises, we chain tasks using `.then()`, making the code more readable. But wait, there’s more magic to explore — the enchanting Async/Await duo!</p>
<h4 id="heading-embracing-simplicity-with-asyncawait">Embracing Simplicity with Async/Await 🚀</h4>
<p>Async/Await simplifies asynchronous JavaScript further. By labeling a function as `async`, it becomes a promise, and the `await` keyword pauses execution until the promise is resolved.</p>
<pre><code class="lang-python"><span class="hljs-keyword">async</span> function coffeeShop() {
 <span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">2000</span>, () =&gt; console.log(`${supplies.Beans[<span class="hljs-number">0</span>]} was selected`));
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">1000</span>, () =&gt; console.log(<span class="hljs-string">"Brewing process initiated"</span>));
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">2000</span>, () =&gt; console.log(<span class="hljs-string">"Liquid added"</span>));
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">1000</span>, () =&gt; console.log(<span class="hljs-string">"Start the machine"</span>));
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">2000</span>, () =&gt; console.log(`Coffee served <span class="hljs-keyword">in</span> ${supplies.Cups[<span class="hljs-number">1</span>]} cup`));
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">3000</span>, () =&gt; console.log(`${supplies.Toppings[<span class="hljs-number">0</span>]} sprinkled on top`));
  <span class="hljs-keyword">await</span> order(<span class="hljs-number">2000</span>, () =&gt; console.log(<span class="hljs-string">"Enjoy your coffee"</span>));
  } catch (error) {
 console.log(<span class="hljs-string">"Customer left"</span>, error);
 } <span class="hljs-keyword">finally</span> {
 console.log(<span class="hljs-string">"Coffee shop closed for the day"</span>);
 }
}

// Trigger the coffee shop
coffeeShop();
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:281/0*YTdyyXy2gi1St9-t.png" alt class="image--center mx-auto" /></p>
<p>In our coffee shop journey, we’ve explored the nuances of synchronous and asynchronous JavaScript, battled Callback Hell with promises, and embraced the elegance of Async/Await. Now, armed with these tools, venture forth into the vast world of asynchronous programming! May your code flow like a perfectly brewed cup of coffee. ☕🚀</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704133280049/e405157a-8edb-4dc8-abae-74f0f179303a.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-connect-with-me-on-social-media"><strong>Connect with Me on social media 📲</strong></h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Mastering Clean Functions: 10 Practices for Elegance in Code ✨]]></title><description><![CDATA[A Symphony of Code: Harmonizing 10 Practices for Elegance in Clean Functions]]></description><link>https://devangtomar.hashnode.dev/mastering-clean-functions-10-practices-for-elegance-in-code-edd324fdbfa5</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/mastering-clean-functions-10-practices-for-elegance-in-code-edd324fdbfa5</guid><category><![CDATA[coding]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Clean Architecture]]></category><category><![CDATA[#codingNewbies]]></category><category><![CDATA[Coding Best Practices]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 10 Dec 2023 17:16:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228616551/7fd7150a-8e96-4e0a-b5fb-6ca09bfa70be.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A Symphony of Code: Harmonizing 10 Practices for Elegance in Clean Functions</p>
<h4 id="heading-introduction"><strong>Introduction</strong></h4>
<p>In the pursuit of crafting elegant and maintainable code, the art of writing clean functions plays a pivotal role. Let’s explore 10 key practices that can transform your functions into a masterpiece of code.</p>
<h4 id="heading-small-is-beautiful"><strong>Small is Beautiful 🌱</strong></h4>
<p>Clean functions follow the principle of simplicity. Keep your functions small, with a clear and singular purpose. A small function is easier to understand, test, and maintain</p>
<pre><code class="lang-python"><span class="hljs-comment"># Uncleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_data</span>(<span class="hljs-params">data</span>):</span>
<span class="hljs-comment"># … complex logic …</span>

<span class="hljs-comment"># Cleaned Functions</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_data</span>(<span class="hljs-params">data</span>):</span>
<span class="hljs-comment"># … logic to handle data …</span>
</code></pre>
<h4 id="heading-meaningful-naming-matters"><strong>Meaningful Naming Matters 🔤</strong></h4>
<p>Choose names that convey the purpose of your function. A well-named function eliminates the need for extensive comments and enhances code readability.</p>
<pre><code class="lang-python">// Uncleaned Function
function c(x, y) {
// … logic …

// Cleaned Function
function calculateArea(radius, height) {
// … logic …
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228606755/f7030447-68fe-4797-96ef-8c9b91239b33.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-one-job-per-function"><strong>One Job Per Function 👷‍♀️</strong></h4>
<p>Clean functions adhere to the Single Responsibility Principle (SRP). Each function should have one job and do it well.</p>
<pre><code class="lang-python">// Uncleaned Function
public void processAndSendEmail(email) {
// … complex logic …

// Cleaned Functions
public void processEmail(email) {
// … logic to process email …
public void sendEmail(email) {
// … logic to send email …
</code></pre>
<h4 id="heading-balancing-act-with-function-arguments"><strong>Balancing Act with Function Arguments 🎭</strong></h4>
<p>Strike a balance with function arguments. Too many arguments can lead to confusion, while too few can hide essential details.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Uncleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_report</span>(<span class="hljs-params">title, startDate, endDate, format, includeSummary</span>):</span>
<span class="hljs-comment"># … logic …</span>

<span class="hljs-comment"># Cleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_report</span>(<span class="hljs-params">report_config</span>):</span>
<span class="hljs-comment"># … logic …</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228608329/fdbc95f6-fe04-4f09-a201-8ffd9966a8e8.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-error-handling-fail-fast-fail-loud"><strong>Error Handling: Fail Fast, Fail Loud 🚨</strong></h4>
<p>Handle errors at the point of occurrence. Clean functions follow the principle of failing fast and failing loud, making it easier to identify and address issues.</p>
<pre><code class="lang-python">// Uncleaned Function
public String processOrder(Order order) {
 <span class="hljs-keyword">try</span> {
 // … processing logic …
 } catch (Exception e) {
 log.error(<span class="hljs-string">"An error occurred: "</span> + e.getMessage());
 <span class="hljs-keyword">return</span> <span class="hljs-string">"Error processing order."</span>;
 }
}

// Cleaned Function
public String processOrder(Order order) {
 <span class="hljs-keyword">if</span> (!isValid(order)) {
 log.error(<span class="hljs-string">"Invalid order: "</span> + order.toString());
 <span class="hljs-keyword">return</span> <span class="hljs-string">"Error processing order."</span>;
 }
 // … processing logic …
}
private boolean isValid(Order order) {
 // … validation logic …
</code></pre>
<h4 id="heading-consistent-formatting-for-visual-appeal"><strong>Consistent Formatting for Visual Appeal 🎨</strong></h4>
<p>Follow a consistent code formatting style. Clean functions are not just about functionality but also about visual appeal.</p>
<pre><code class="lang-python">// Inconsistent Formatting
function processData(data){
// … logic …

// Consistent Formatting
function process_data(data) {
 // … logic …
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228609958/87af27f3-2ee6-4527-af8c-aeb49fe2d46e.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-avoid-global-state-dependency"><strong>Avoid Global State Dependency 🌐</strong></h4>
<p>Clean functions are self-contained and avoid reliance on global state. Minimize dependencies to enhance code predictability and testability.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Uncleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_total</span>():</span>
 <span class="hljs-keyword">global</span> cart
 <span class="hljs-comment"># … logic …</span>

<span class="hljs-comment"># Cleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_total</span>(<span class="hljs-params">cart</span>):</span>
 <span class="hljs-comment"># … logic …</span>
</code></pre>
<h4 id="heading-documentation-through-code-structure"><strong>Documentation Through Code Structure 📖</strong></h4>
<p>Let your code structure serve as documentation. Clean functions naturally lead to a well-organized and documented codebase.</p>
<pre><code class="lang-python">// Uncleaned Function
public void complexFunction() {
 // … logic …

// Cleaned Functions
public void stepOne() {
 // … logic <span class="hljs-keyword">for</span> step one …
public void stepTwo() {
 // … logic <span class="hljs-keyword">for</span> step two …
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228611554/1c17ee87-57f6-4082-a338-3c336d633c17.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-unit-testability"><strong>Unit Testability 🧪</strong></h4>
<p>Clean functions are inherently testable. The small, focused nature of clean functions makes it easier to write meaningful unit tests.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Uncleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">complex_calculation</span>(<span class="hljs-params">data</span>):</span>
 <span class="hljs-comment"># … complex logic …</span>

<span class="hljs-comment"># Cleaned Function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">simple_calculation</span>(<span class="hljs-params">data</span>):</span>
 <span class="hljs-comment"># … simple logic …</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228613248/b04a19c2-6b6e-42df-b964-a4be219ff89e.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-continuous-refinement"><strong>Continuous Refinement 🔄</strong></h4>
<p>Code is a living entity. Clean functions embrace the idea of continuous improvement. Regularly revisit and refine your functions to keep your codebase in top shape.</p>
<pre><code class="lang-python">// Initial Cleaned Function
function processData(data) {
 // … logic …

// Refined Cleaned Function
function processAndValidateData(data) {
 // … refined logic …
</code></pre>
<h4 id="heading-conclusion"><strong>Conclusion 💡</strong></h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702228614717/5ecc0057-afca-4d7c-a4d2-cfa2d8d9de3e.jpeg" alt class="image--center mx-auto" /></p>
<p>By integrating these 10 practices into your coding habits, you embark on a journey toward crafting clean functions that are not only functional but also a joy to work with. 👩‍💻👨‍💻</p>
<h4 id="heading-connect-with-me-on-social-media"><strong>Connect with Me on social media 📲</strong></h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[A Developer’s Dilemma: Navigating Rust 🦀 and Python 🐍]]></title><description><![CDATA[As developers, the choice of programming language is a compass guiding us through the vast landscapes of data analysis and machine learning. In this…]]></description><link>https://devangtomar.hashnode.dev/a-developers-dilemma-navigating-rust-and-python-6f4e27d96d3d</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/a-developers-dilemma-navigating-rust-and-python-6f4e27d96d3d</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[Rust, Solana, Web3]]></category><category><![CDATA[rustseries]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 19 Nov 2023 16:27:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411257823/1d2dcc1d-6571-446c-9df7-efee47dbe0df.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-introduction">Introduction</h4>
<p>As developers, the choice of programming language is a compass guiding us through the vast landscapes of data analysis and machine learning. In this journey, two contenders have emerged as titans: Rust 🦀 and Python 🐍. Join me as we explore the highs and lows of these languages from a developer’s perspective.</p>
<h4 id="heading-the-python-legacy">The Python Legacy 🐍</h4>
<p>Python has long been the lingua franca of data science. Its simplicity and a myriad of libraries like NumPy, pandas, and scikit-learn have made it the default choice. Let’s dive into a simple Python example:</p>
<pre><code class="lang-go"># Python Code Example: Loading a CSV with pandas
<span class="hljs-keyword">import</span> pandas as pd
data = pd.read_csv(<span class="hljs-string">"dataset.csv"</span>)
<span class="hljs-built_in">print</span>(data.head())
</code></pre>
<h4 id="heading-the-rust-revolution">The Rust Revolution 🦀</h4>
<p>Enter Rust, a systems programming language known for its performance and safety. While not traditionally associated with data science, its capabilities are intriguing.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411251543/1cf26087-043d-49e1-846e-9e5cdd689e49.jpeg" alt class="image--center mx-auto" /></p>
<p>Here’s a taste of Rust:</p>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Code Example: Reading a CSV with the csv crate</span>
use std::error::Error;
use csv::ReaderBuilder;

fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let file = std::fs::File::open(<span class="hljs-string">"dataset.csv"</span>)?;
    let mut rdr = ReaderBuilder::<span class="hljs-built_in">new</span>().has_headers(<span class="hljs-literal">true</span>).from_reader(file);

    <span class="hljs-keyword">for</span> result in rdr.records() {
        let record = result?;
        <span class="hljs-built_in">println</span>!(<span class="hljs-string">"{:?}"</span>, record);
    }

    Ok(())
}
</code></pre>
<h4 id="heading-performance-showdown">Performance Showdown 🚀</h4>
<p>One of Rust’s key selling points is its performance. Let’s compare the execution time of a simple data processing task in Python and Rust:</p>
<pre><code class="lang-go"># Python Performance Test
<span class="hljs-keyword">import</span> time

start_time = time.time()

# ... perform data processing ...

end_time = time.time()
<span class="hljs-built_in">print</span>(f<span class="hljs-string">"Python Execution Time: {end_time - start_time} seconds"</span>)
</code></pre>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Performance Test</span>
use std::time::Instant;

fn main() {
    let start_time = Instant::now();

    <span class="hljs-comment">// ... perform data processing ...</span>

    let end_time = start_time.elapsed();
    <span class="hljs-built_in">println</span>!(<span class="hljs-string">"Rust Execution Time: {:?}"</span>, end_time);
}
</code></pre>
<h4 id="heading-ecosystem-and-libraries">Ecosystem and Libraries 📚</h4>
<p>Python’s rich ecosystem is hard to match, with TensorFlow, PyTorch, and scikit-learn leading the charge. Rust, though, is catching up. The `ndarray` crate and the emerging `tangram-rs` for machine learning are making waves.</p>
<h4 id="heading-safety-and-concurrency">Safety and Concurrency 🛡️</h4>
<p>Rust’s ownership system ensures memory safety without sacrificing performance. Python, on the other hand, can sometimes struggle with concurrency. Let’s explore a concurrent task in both languages.</p>
<pre><code class="lang-go"># Python Concurrent Task
<span class="hljs-keyword">import</span> concurrent.futures

def process_data(data_chunk):
    # ... perform data processing ...

with concurrent.futures.ThreadPoolExecutor() as executor:
    # ... submit tasks <span class="hljs-keyword">for</span> parallel processing ...
</code></pre>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Concurrent Task with Rayon</span>
use rayon::prelude::*;

fn process_data(data_chunk: &amp;mut Vec&lt;i32&gt;) {
    <span class="hljs-comment">// ... perform data processing ...</span>
}

fn main() {
    let mut data_chunks: Vec&lt;Vec&lt;i32&gt;&gt; = <span class="hljs-comment">// ... prepare data chunks ...</span>

    data_chunks.par_iter_mut().for_each(|chunk| {
        process_data(chunk);
    });
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411253097/38d2b950-0540-4d5d-bea8-89eeb6c0d318.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-memory-management-in-data-processing">Memory Management in Data Processing 🧠</h4>
<p>In Python, memory management is abstracted away, making it easy for developers, data scientists to focus on algorithms. However, this can lead to challenges with large datasets. Rust’s ownership system allows for fine-grained control over memory, ensuring efficient usage. Let’s explore handling large arrays:</p>
<pre><code class="lang-go"># Python Memory Management Example
<span class="hljs-keyword">import</span> numpy as np

large_array = np.zeros(<span class="hljs-number">10</span>**<span class="hljs-number">6</span>, dtype=np.<span class="hljs-keyword">float64</span>)
# ... perform operations on the array ...
</code></pre>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Memory Management Example</span>
fn main() {
    let mut large_array: Vec&lt;f64&gt; = vec![<span class="hljs-number">0.0</span>; <span class="hljs-number">1</span>_000_000];
    <span class="hljs-comment">// ... perform operations on the array ...</span>
}
</code></pre>
<h4 id="heading-parallelism-and-multithreading">Parallelism and Multithreading 🚀</h4>
<p>Python’s Global Interpreter Lock (GIL) can limit parallelism in CPU-bound tasks. Rust, with its emphasis on concurrency, allows for easy parallelization using libraries like Rayon.</p>
<pre><code class="lang-go"># Python Multithreading Example
<span class="hljs-keyword">import</span> concurrent.futures

def process_data(data_chunk):
    # ... perform data processing ...

with concurrent.futures.ThreadPoolExecutor() as executor:
    # ... submit tasks <span class="hljs-keyword">for</span> parallel processing ...
</code></pre>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Parallelism with Rayon</span>
use rayon::prelude::*;

fn process_data(data_chunk: &amp;mut Vec&lt;i32&gt;) {
    <span class="hljs-comment">// ... perform data processing ...</span>
}

fn main() {
    let mut data_chunks: Vec&lt;Vec&lt;i32&gt;&gt; = <span class="hljs-comment">// ... prepare data chunks ...</span>

    data_chunks.par_iter_mut().for_each(|chunk| {
        process_data(chunk);
    });
}
</code></pre>
<h4 id="heading-learning-curve-and-accessibility">Learning Curve and Accessibility 📈</h4>
<p>Python’s readability and gentle learning curve have made it a go-to language for beginners. Rust, with its emphasis on ownership and borrowing, can be challenging initially but rewards with performance and memory safety.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411254745/0d6f15d3-c313-4f7b-bb8b-5a32d5315a75.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-data-visualization-capabilities">Data Visualization Capabilities 📊</h4>
<p>Python’s matplotlib and seaborn make data visualization a breeze. Rust, while not as feature-rich in this domain, offers libraries like Plotters for basic plotting.</p>
<pre><code class="lang-go"># Python Data Visualization with Matplotlib
<span class="hljs-keyword">import</span> matplotlib.pyplot as plt

data = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
plt.plot(data)
plt.show()
</code></pre>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Data Visualization with Plotters</span>
use plotters::prelude::*;

fn main() {
    let data = vec![<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

    let root = BitMapBackend::<span class="hljs-built_in">new</span>(<span class="hljs-string">"plot.png"</span>, (<span class="hljs-number">640</span>, <span class="hljs-number">480</span>)).into_drawing_area();
    root.fill(&amp;WHITE)?;

    let chart = ChartBuilder::on(&amp;root)
        .build_cartesian_2d(<span class="hljs-number">0.</span>.data.<span class="hljs-built_in">len</span>() as i32, <span class="hljs-number">0.</span><span class="hljs-number">.10</span>)?;

    chart.draw_series(LineSeries::<span class="hljs-built_in">new</span>(
        data.iter().enumerate().<span class="hljs-keyword">map</span>(|(i, &amp;v)| (i as i32, v)),
        &amp;BLUE,
    ))?;
}
</code></pre>
<h4 id="heading-interoperability-with-other-languages">Interoperability with Other Languages 🔄</h4>
<p>Python’s ability to seamlessly integrate with C and C++ libraries through tools like Cython is advantageous. Rust, though relatively new to the scene, offers Foreign Function Interface (FFI) capabilities, allowing integration with C libraries.</p>
<pre><code class="lang-go"># Python Interoperability with C
from ctypes <span class="hljs-keyword">import</span> CDLL

my_lib = CDLL(<span class="hljs-string">'./my_lib.so'</span>)
# ... use functions from the C library ...
</code></pre>
<pre><code class="lang-go"><span class="hljs-comment">// Rust Foreign Function Interface (FFI)</span>
extern crate libc;

extern <span class="hljs-string">"C"</span> {
    fn my_function();
}

fn main() {
    unsafe {
        my_function();
    }
}
</code></pre>
<h4 id="heading-choosing-your-adventure">Choosing Your Adventure 🗺️</h4>
<p>In the realm of data science, the choice between Rust and Python is akin to selecting the right tool for a specific task. Python’s versatility and well-established ecosystem make it a reliable companion, while Rust’s performance and safety make it a rising star.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411256405/fd2acae8-1162-436e-9df8-c0b878030c4e.jpeg" alt class="image--center mx-auto" /></p>
<p>The decision ultimately depends on the landscape you wish to navigate. Whether you choose the well-trodden paths of Python or embark on the uncharted territories of Rust, the journey is yours to craft. 🚀👩‍💻👨‍💻</p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Building RESTful APIs with Go 📲]]></title><description><![CDATA[Hello, fellow developers! In today’s tech-driven world, building robust and scalable RESTful APIs is a skill every programmer should master. In this…]]></description><link>https://devangtomar.hashnode.dev/building-restful-apis-with-go-133529d8e919</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/building-restful-apis-with-go-133529d8e919</guid><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Golang web development]]></category><category><![CDATA[Golang Web Framework]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 20 Oct 2023 05:31:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411193287/b8943d5e-947b-421f-87c5-359e5fbd1b43.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello, fellow developers! In today’s tech-driven world, building robust and scalable RESTful APIs is a skill every programmer should master. In this comprehensive guide, we’ll embark on a thrilling journey to create RESTful APIs using the power of Go, unveiling the secrets behind seamless API development. Get ready to dive into the world of HTTP methods, routing, JSON handling, database integration, authentication, error handling, middleware usage, and testing! 🚀✨</p>
<h4 id="heading-understanding-restful-apis-the-basics">Understanding RESTful APIs: The Basics 🗽</h4>
<p>REST (Representational State Transfer) is an architectural style for networked applications. RESTful APIs allow applications to communicate over standard HTTP methods, making them highly scalable and easy to integrate. Let’s get started by setting up a simple Go server to handle HTTP requests.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
 <span class="hljs-string">"encoding/json"</span>
 <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">type</span> User <span class="hljs-keyword">struct</span> {
 ID   <span class="hljs-keyword">int</span>    <span class="hljs-string">`json:"id"`</span>
 Name <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span>
}

<span class="hljs-keyword">var</span> users []User

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
 http.HandleFunc(<span class="hljs-string">"/users"</span>, getUsers)
 http.HandleFunc(<span class="hljs-string">"/users"</span>, createUser).Methods(<span class="hljs-string">"POST"</span>)
 http.HandleFunc(<span class="hljs-string">"/users/{id}"</span>, getUserByID).Methods(<span class="hljs-string">"GET"</span>)
 http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>In this code, we’ve defined a basic HTTP server with endpoints for creating, retrieving, updating, and deleting users. Now, let’s explore additional aspects of RESTful API development in Go.</p>
<h4 id="heading-handling-parameters-and-route-variables">Handling Parameters and Route Variables 🛣️</h4>
<p>Go allows us to handle route variables and query parameters effortlessly.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getUserByID</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-comment">// Extract route variable</span>
    <span class="hljs-comment">// id := mux.Vars(r)["id"]</span>
    <span class="hljs-comment">// Implement logic to retrieve user by ID</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getUsersByQueryParams</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
 <span class="hljs-comment">// Extract query parameters</span>
 <span class="hljs-comment">// params := r.URL.Query()</span>
 <span class="hljs-comment">// Implement logic based on query parameters</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411184624/b36b65c5-37be-4909-9c53-0280618f1bdd.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-integration-with-databases-data-persistence">Integration with Databases: Data Persistence 💾</h4>
<p>To create a truly functional API, integrating with databases is essential. Let’s use a PostgreSQL database as an example.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
 <span class="hljs-string">"database/sql"</span>
 <span class="hljs-string">"fmt"</span>
 _ <span class="hljs-string">"github.com/lib/pq"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
 connStr := <span class="hljs-string">"user=username dbname=mydb sslmode=disable"</span>
 db, err := sql.Open(<span class="hljs-string">"postgres"</span>, connStr)
 <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
  fmt.Println(<span class="hljs-string">"Error opening database:"</span>, err)
  <span class="hljs-keyword">return</span>
 }
 <span class="hljs-keyword">defer</span> db.Close()
 <span class="hljs-comment">// Implement database logic for API endpoints</span>
}
</code></pre>
<p>In this code snippet, we’ve connected to a PostgreSQL database using the <code>pq</code> driver. You can perform CRUD operations within your API endpoints using this connection.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411186248/f267ad47-ed88-4b52-bff1-bb9957894764.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-authentication-and-authorization-securing-your-apis">Authentication and Authorization: Securing Your APIs 🔐</h4>
<p>Securing your APIs is paramount. Go provides robust libraries for implementing authentication and authorization mechanisms.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">authenticateMiddleware</span><span class="hljs-params">(next http.Handler)</span> <span class="hljs-title">http</span>.<span class="hljs-title">Handler</span></span> {
    <span class="hljs-keyword">return</span> http.HandlerFunc(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
        <span class="hljs-comment">// Implement authentication logic</span>
        <span class="hljs-comment">// If authenticated, call next.ServeHTTP(w, r)</span>
        <span class="hljs-comment">// If not, return unauthorized response</span>
    })
}
</code></pre>
<h4 id="heading-error-handling-and-responses-ensuring-reliability">Error Handling and Responses: Ensuring Reliability ❌</h4>
<p>Proper error handling and consistent response formats are vital for API reliability. Go’s custom error types and structured responses enhance the developer and client experience.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> APIError <span class="hljs-keyword">struct</span> {
 Message <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"error"`</span>
 Code    <span class="hljs-keyword">int</span>    <span class="hljs-string">`json:"code"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sendErrorResponse</span><span class="hljs-params">(w http.ResponseWriter, err APIError)</span></span> {
 w.WriteHeader(err.Code)
 json.NewEncoder(w).Encode(err)
}
</code></pre>
<p>In this snippet, the <code>APIError</code> struct represents standardized error responses, ensuring clear communication between the API and its consumers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411188066/8fb976d0-e384-4e72-92ba-cc8c7665e158.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-middleware-usage-enhancing-functionality">Middleware Usage: Enhancing Functionality 👥</h4>
<p>Middleware functions in Go allow you to intercept requests and responses, enabling various functionalities such as logging, authentication, and rate limiting.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loggerMiddleware</span><span class="hljs-params">(next http.Handler)</span> <span class="hljs-title">http</span>.<span class="hljs-title">Handler</span></span> {
 <span class="hljs-keyword">return</span> http.HandlerFunc(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
  fmt.Println(<span class="hljs-string">"Request received:"</span>, r.Method, r.URL.Path)
  next.ServeHTTP(w, r)
 })
}
</code></pre>
<h4 id="heading-testing-your-apis-ensuring-quality">Testing Your APIs: Ensuring Quality 🧪</h4>
<p>Testing is crucial for API development. Go provides excellent support for writing unit tests and conducting HTTP testing for your API endpoints.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestCreateUser</span><span class="hljs-params">(t *testing.T)</span></span> {
 <span class="hljs-comment">// Implement test logic for creating users</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestGetUserByID</span><span class="hljs-params">(t *testing.T)</span></span> {
 <span class="hljs-comment">// Implement test logic for retrieving users by ID</span>
}
</code></pre>
<p>In these test functions, you can simulate API requests and validate the responses to ensure your endpoints function correctly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411189868/182c8934-5855-4821-bc08-456e52034b9d.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-conclusion">Conclusion 🎉</h4>
<p>You now know the secrets of building RESTful APIs with Go. By mastering HTTP methods, route handling, database integration, authentication, error handling, middleware usage, and testing, you’re well-equipped to create APIs that are not just functional but also secure, reliable, and highly maintainable.</p>
<p>Remember, APIs are the backbone of modern applications, enabling seamless communication between various services and systems. With Go’s simplicity and efficiency, you’re empowered to build APIs that stand the test of scalability and robustness.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411191883/7e264b3d-0151-4868-b548-7d0266ddff93.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Advanced Go Features Demystified 😱: Unraveling the Power of Go! 😎]]></title><description><![CDATA[In this article, we’re embarking on an exciting journey to demystify some of the advanced features that make Go such a powerful and efficient language…]]></description><link>https://devangtomar.hashnode.dev/advanced-go-features-demystified-unraveling-the-power-of-go-be9f38994716</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/advanced-go-features-demystified-unraveling-the-power-of-go-be9f38994716</guid><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Go Lang]]></category><category><![CDATA[Golang web development]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 13 Oct 2023 05:31:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411175486/3a543208-ff25-415c-8e58-158113cbca24.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411164340/57281af6-7009-4840-8425-35876bf768ec.png" alt class="image--center mx-auto" /></p>
<p>In this article, we’re embarking on an exciting journey to demystify some of the advanced features that make Go such a powerful and efficient language. Buckle up, because we’re about to unravel the secrets behind Go’s advanced capabilities! 💻✨</p>
<h3 id="heading-interfaces-the-swiss-army-knife-of-go-programming">Interfaces: The Swiss Army Knife of Go Programming 🛠️</h3>
<p>Interfaces in Go allow you to define a set of methods that a type must implement. They are incredibly versatile and form the basis of many advanced Go patterns.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Shape <span class="hljs-keyword">interface</span> {
    Area() <span class="hljs-keyword">float64</span>
}

<span class="hljs-keyword">type</span> Circle <span class="hljs-keyword">struct</span> {
    Radius <span class="hljs-keyword">float64</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c Circle)</span> <span class="hljs-title">Area</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">3.14</span> * c.Radius * c.Radius
}
</code></pre>
<p>In this example, the <code>Shape</code> interface defines a method <code>Area()</code>, which the <code>Circle</code> struct implements. Any type that implements the <code>Area()</code> method is implicitly implementing the <code>Shape</code> interface.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411166433/2c797cda-c006-4b86-b640-25a235d3f49c.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-goroutines-and-channels-concurrency-made-easy">Goroutines and Channels: Concurrency Made Easy 🚥</h3>
<p>Goroutines are lightweight threads, and channels are the pipes that connect them, allowing communication and synchronization between goroutines.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">worker</span><span class="hljs-params">(jobs &lt;-<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, results <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">int</span>)</span></span> {
    <span class="hljs-keyword">for</span> job := <span class="hljs-keyword">range</span> jobs {
        results &lt;- job * <span class="hljs-number">2</span>
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    jobs := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, <span class="hljs-number">100</span>)
    results := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, <span class="hljs-number">100</span>)

    <span class="hljs-keyword">go</span> worker(jobs, results)

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
        jobs &lt;- i
    }
    <span class="hljs-built_in">close</span>(jobs)

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {
        result := &lt;-results
        fmt.Println(<span class="hljs-string">"Result:"</span>, result)
    }
}
</code></pre>
<p>In this code, the <code>worker</code> function runs concurrently with the <code>main</code> function, processing jobs from the <code>jobs</code> channel and sending results to the <code>results</code> channel.</p>
<h3 id="heading-defer-statements-clean-up-made-simple">Defer Statements: Clean-Up Made Simple 🧹</h3>
<p>Go’s <code>defer</code> statement schedules a function call to be run after the function completes. It's often used for clean-up activities such as closing files or releasing resources.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readFile</span><span class="hljs-params">(filename <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, error)</span></span> {
    file, err := os.Open(filename)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, err
    }
    <span class="hljs-keyword">defer</span> file.Close() <span class="hljs-comment">// File will be closed after readFile completes</span>

    <span class="hljs-comment">// Read file contents</span>
}
</code></pre>
<p>The <code>defer</code> statement ensures that the <code>file.Close()</code> call happens even if an error occurs during the execution of the <code>readFile</code> function.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411167974/86b229d7-6d70-4fe8-b66c-be2e385c4769.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-error-handling-beyond-basic-errors">Error Handling: Beyond Basic Errors 🚨</h3>
<p>Go’s approach to error handling is simple yet powerful. You can create custom error types and add context to errors for better debugging.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> CustomError <span class="hljs-keyword">struct</span> {
    Code    <span class="hljs-keyword">int</span>
    Message <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(e CustomError)</span> <span class="hljs-title">Error</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-keyword">return</span> fmt.Sprintf(<span class="hljs-string">"Error %d: %s"</span>, e.Code, e.Message)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">process</span><span class="hljs-params">()</span> <span class="hljs-title">error</span></span> {
    <span class="hljs-comment">// ...</span>
    <span class="hljs-keyword">return</span> CustomError{Code: <span class="hljs-number">404</span>, Message: <span class="hljs-string">"Not Found"</span>}
}
</code></pre>
<p>In this example, the <code>CustomError</code> type implements the <code>error</code> interface, allowing you to create rich, structured error types.</p>
<h3 id="heading-reflection-exploring-the-unknown">Reflection: Exploring the Unknown 🕵️‍♂️</h3>
<p>Reflection in Go allows you to inspect and manipulate variables, methods, and other structures of your code at runtime. While it should be used sparingly due to its complexity, reflection can be a powerful tool in certain scenarios like serialization/deserialization or creating generic functions.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
 <span class="hljs-string">"fmt"</span>
 <span class="hljs-string">"reflect"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
 <span class="hljs-keyword">var</span> num <span class="hljs-keyword">int</span> = <span class="hljs-number">42</span>
 fmt.Println(<span class="hljs-string">"Type:"</span>, reflect.TypeOf(num))
}
</code></pre>
<p>In this example, the <code>reflect.TypeOf()</code> function provides the runtime type of the variable <code>num</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411169708/3f29fd25-8c5e-47ee-9347-347cf0fa7ddb.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-context-managing-request-scopes">Context: Managing Request Scopes 🌐</h4>
<p>Go’s <code>context</code> package enables the management of request-scoped values and deadlines across API boundaries and between goroutines. It's especially useful in microservices architectures where requests might span multiple goroutines.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
 <span class="hljs-string">"context"</span>
 <span class="hljs-string">"fmt"</span>
 <span class="hljs-string">"net/http"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
 ctx := r.Context()
 ctx = context.WithValue(ctx, <span class="hljs-string">"userID"</span>, <span class="hljs-number">123</span>)
 processRequest(ctx)
 <span class="hljs-comment">// ...</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processRequest</span><span class="hljs-params">(ctx context.Context)</span></span> {
 userID := ctx.Value(<span class="hljs-string">"userID"</span>).(<span class="hljs-keyword">int</span>)
 fmt.Println(<span class="hljs-string">"Processing request for User ID:"</span>, userID)
}
</code></pre>
<p>In this example, the <code>context</code> package helps carry values (like user IDs) across functions without explicitly passing them as arguments.</p>
<h3 id="heading-embedding-composition-through-struct-embedding">Embedding: Composition Through Struct Embedding 🧩</h3>
<p>Go allows you to achieve composition through a concept called “embedding.” Embedding lets you include one struct inside another, allowing the outer struct to inherit the inner struct’s fields and methods.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
 Name <span class="hljs-keyword">string</span>
 Age  <span class="hljs-keyword">int</span>
}

<span class="hljs-keyword">type</span> Employee <span class="hljs-keyword">struct</span> {
 Person
 JobTitle <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
 emp := Employee{
  Person:   Person{Name: <span class="hljs-string">"Alice"</span>, Age: <span class="hljs-number">30</span>},
  JobTitle: <span class="hljs-string">"Developer"</span>,
 }
 fmt.Println(emp.Name, <span class="hljs-string">"is a"</span>, emp.JobTitle)
}
</code></pre>
<p>In this example, the <code>Employee</code> struct embeds the <code>Person</code> struct, inheriting its fields (<code>Name</code> and <code>Age</code>). This composition technique enhances code reusability and readability.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411171620/ba8b1b1a-a3c6-4e8e-ab37-41490ada3729.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-custom-packages-and-dependency-management-organizing-your-codebase">Custom Packages and Dependency Management: Organizing Your Codebase 📦</h3>
<p>Organizing your code into custom packages and effectively managing dependencies is crucial for maintainable projects. Go provides powerful tools like <code>go mod</code> for dependency management and package versioning.</p>
<pre><code class="lang-go"># Creating a <span class="hljs-built_in">new</span> Go module
<span class="hljs-keyword">go</span> mod init example.com/myproject

# Installing a <span class="hljs-keyword">package</span> and adding it to <span class="hljs-keyword">go</span>.mod
<span class="hljs-keyword">go</span> get github.com/example/<span class="hljs-keyword">package</span>

# Importing your custom <span class="hljs-keyword">package</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"example.com/mypackage"</span>
</code></pre>
<p>In this example, <code>go mod</code> helps manage project dependencies, ensuring consistent and reproducible builds.</p>
<h3 id="heading-conclusion-embrace-the-power-of-go">Conclusion: Embrace the Power of Go! 🌟</h3>
<p>Congratulations! You’ve unlocked the mysteries behind some of Go’s advanced features. Interfaces, goroutines, channels, defer statements, and error handling are essential tools in your Go programming arsenal.</p>
<p>By understanding and applying these features effectively, you’ll be able to write concurrent, efficient, and robust Go applications. So, go forth, experiment, and harness the full potential of Go in your projects. 💻✨</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700411173554/6a721724-12c8-4f8b-80e1-c7ff5cbeb924.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[A Beginner’s Guide to Go 💨: Your Gateway to Efficient Programming! 🚀]]></title><description><![CDATA[In this blog post, we’ll unravel the secrets of Go, a powerful and efficient programming language developed by Google.]]></description><link>https://devangtomar.hashnode.dev/a-beginners-guide-to-go-your-gateway-to-efficient-programming-bdcd5a8a07f2</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/a-beginners-guide-to-go-your-gateway-to-efficient-programming-bdcd5a8a07f2</guid><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Golang Web Framework]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[#codingNewbies]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Fri, 06 Oct 2023 05:31:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696662711872/819d128b-538c-418a-8110-fe63b6c1a596.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome, aspiring coders, to the fascinating world of programming! Whether you’re a curious beginner or a seasoned developer exploring new languages, you’re in for a treat today. In this blog post, we’ll unravel the secrets of Go, a powerful and efficient programming language developed by Google. Buckle up, because by the end of this guide, you’ll have a solid grasp of the basics of Go programming! 💻✨</p>
<h3 id="heading-what-is-go">What is Go?</h3>
<p>Go, often referred to as Golang, is an open-source programming language created by Google engineers Robert Griesemer, Rob Pike, and Ken Thompson in 2007. Known for its simplicity, readability, and excellent performance, Go has gained widespread popularity among developers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696662703455/770e4317-1756-4fbc-9390-bda53f99fc93.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-setting-up-go-environment">Setting Up Go Environment 🛠️</h3>
<p>Before diving into coding, let’s set up your Go environment.</p>
<ol>
<li><p>Download and Install Go: Visit the <a target="_blank" href="https://golang.org/">official Go website</a> to download and install Go on your system. Follow the installation instructions provided for your specific operating system.</p>
</li>
<li><p>Verify Installation: Open your terminal or command prompt and type <code>go version</code>. If Go is installed correctly, you'll see the installed version number.</p>
</li>
</ol>
<h3 id="heading-your-first-go-program">Your First Go Program 🚪</h3>
<p>Let’s start with a classic “Hello, World!” program. Open your favourite text editor and create a file named <code>hello.go</code></p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p>In this code:</p>
<ul>
<li><p><code>package main</code> indicates that this file belongs to the main package.</p>
</li>
<li><p><code>import "fmt"</code> imports the "fmt" package, which provides functions for formatting text.</p>
</li>
<li><p><code>func main()</code> is the entry point of your program, similar to <code>main()</code> in C or Java.</p>
</li>
</ul>
<p>To run your program, navigate to the directory containing <code>hello.go</code> in your terminal and type <code>go run hello.go</code>. Voila! You've just executed your first Go program. 🎉</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696662704944/924eb2e4-3789-43a5-bbf5-22effda29c3f.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-understanding-go-basics">Understanding Go Basics 🧠</h3>
<h4 id="heading-variables-and-data-types">Variables and Data Types 📦</h4>
<p>Go is statically typed, meaning you must specify the type of a variable when you declare it. Here are a few basic data types:</p>
<ul>
<li><p><code>int</code>: Integer type (e.g., 1, -5, 42)</p>
</li>
<li><p><code>float64</code>: Floating-point type (e.g., 3.14, -0.5)</p>
</li>
<li><p><code>string</code>: String type (e.g., "Hello, Go!")</p>
</li>
</ul>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>
    <span class="hljs-keyword">var</span> pi <span class="hljs-keyword">float64</span> = <span class="hljs-number">3.14</span>
    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Alice"</span>
    fmt.Println(name, <span class="hljs-string">"is"</span>, age, <span class="hljs-string">"years old and loves pi ("</span>, pi, <span class="hljs-string">")!"</span>)
}
</code></pre>
<h4 id="heading-control-structures">Control Structures 🎛️</h4>
<p>Go supports common control structures like <code>if</code>, <code>for</code>, and <code>switch</code>. Here's a quick example of a <code>for</code> loop:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">5</span>; i++ {
        fmt.Println(<span class="hljs-string">"Iteration"</span>, i)
    }
}
</code></pre>
<h4 id="heading-functions-and-packages">Functions and Packages 📦</h4>
<p>In Go, functions are defined using the <code>func</code> keyword. You can create your packages to organize your code into reusable components.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">add</span><span class="hljs-params">(a, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> a + b
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    result := add(<span class="hljs-number">3</span>, <span class="hljs-number">7</span>)
    fmt.Println(<span class="hljs-string">"3 + 7 ="</span>, result)
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696662706937/1dd1ff5a-47e2-4051-a72d-0a2b774e76b1.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-go-package-discovery-tool-go-get">Go Package Discovery Tool: <code>go get</code> 🧐</h3>
<p>One of Go’s fantastic features is its ability to easily discover and install packages using the <code>go get</code> command. This tool allows you to download and install packages from remote repositories, making it a breeze to integrate third-party libraries into your projects.</p>
<p>To use <code>go get</code>, simply open your terminal and type:</p>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> get github.com/example/<span class="hljs-keyword">package</span>
</code></pre>
<p>Replace <code>github.com/example/package</code> with the actual repository URL of the package you want to install. Go will fetch the package and make it available for use in your programs.</p>
<h3 id="heading-creating-a-go-module-go-mod-init">Creating a Go Module: <code>go mod init</code> 📦</h3>
<p>Go Modules are a convenient way to manage dependencies and versioning in your Go projects. To create a new Go module, navigate to your project directory in the terminal and type:</p>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> mod init example.com/myproject
</code></pre>
<p>This command initializes a Go module for your project, allowing you to manage dependencies more efficiently.</p>
<h3 id="heading-calling-functions-from-modules-external-modules-and-importing-your-own-module-functions">Calling Functions from Modules: External Modules and Importing Your Own Module Functions 🔄</h3>
<p>Once you’ve set up a Go module, you can start using functions from external packages as well as functions from your own modules.</p>
<h4 id="heading-external-modules">External Modules:</h4>
<p>Let’s say you want to use a function <code>Greet</code> from an external module <code>example.com/greetings</code>. First, import the package, then call the function.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"example.com/greetings"</span>
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    message := greetings.Greet(<span class="hljs-string">"Alice"</span>)
    fmt.Println(message)
}
</code></pre>
<p>In this example, <code>Greet</code> is a function from the <code>example.com/greetings</code> module, and we're using it within our <code>main</code> function.</p>
<h4 id="heading-importing-your-own-module-functions">Importing Your Own Module Functions:</h4>
<p>Assuming you have a module named <code>mypackage</code> with a function <code>Multiply</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> mypackage

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Multiply</span><span class="hljs-params">(a, b <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> a * b
}
</code></pre>
<p>You can import and use this function in another file within the same module:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"example.com/mypackage"</span>
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    result := mypackage.Multiply(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)
    fmt.Println(<span class="hljs-string">"5 * 3 ="</span>, result)
}
</code></pre>
<p>In this example, we’re importing the <code>Multiply</code> function from our module <code>example.com/mypackage</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696662708509/ced2a4e2-e943-4b7c-8f9d-c83d42636e81.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-conclusion">Conclusion 🎉</h3>
<p>And that’s a wrap! We’ve covered the basics of getting started with Golang, from setting up your environment to writing your first program and understanding the power of modules. Remember, the journey of learning a new language is a marathon, not a sprint. It’s okay to not understand everything at once. Take your time, practice, and don’t hesitate to seek help when you need it.</p>
<p>As you continue to explore Golang, you’ll discover its power and flexibility. Whether you’re building a web service, designing a complex system, or just writing scripts for automation, Golang has got you covered.</p>
<p>I hope this guide has helped get you started with Golang. <em>Follow for more articles like this! Thanks for reading!</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696662710342/2350a462-825d-499b-8bb3-5dbb6a32f69a.jpeg" alt class="image--center mx-auto" /></p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Building a Simple Web Server with Go 🐭]]></title><description><![CDATA[Are you a beginner eager to explore the world of web servers using the Go programming language? 🚀]]></description><link>https://devangtomar.hashnode.dev/building-a-simple-web-server-with-go-dfa1f332a50e</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/building-a-simple-web-server-with-go-dfa1f332a50e</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Golang web development]]></category><category><![CDATA[Go]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Mon, 02 Oct 2023 07:01:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696269966417/1c953197-7ce6-4fee-9518-c3f7b62291e2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696269966417/1c953197-7ce6-4fee-9518-c3f7b62291e2.png" alt /></p>
<p>Are you a beginner eager to explore the world of web servers using the Go programming language? 🚀 In this comprehensive guide, I’ll take you on a journey to create a basic web server that not only serves static files but also handles essential HTTP requests. By the end of this tutorial, you’ll have a robust grasp of the fundamental concepts required for building a web server with Go. Let’s dive in!</p>
<h3 id="heading-understanding-web-servers">Understanding Web Servers 🌐</h3>
<p>A web server is a software application that processes incoming requests from clients, typically web browsers, and responds by serving web content. It plays a vital role in the architecture of the World Wide Web, enabling the exchange of information between clients and servers. Web servers are the backbone of websites, web applications, and various online services.</p>
<h3 id="heading-prerequisites">Prerequisites 🛠️</h3>
<p>Before we embark on this adventure, make sure you have the following prerequisites:</p>
<ol>
<li><p>Basic understanding of Go programming concepts.</p>
</li>
<li><p>Go programming language installed on your machine. You can download and install Go from the official website: <a target="_blank" href="https://golang.org/dl/">Go Downloads</a>.</p>
</li>
</ol>
<h3 id="heading-github-repo">GitHub repo 👨🏻‍💻</h3>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/devangtomar/simple-go-webserver">https://github.com/devangtomar/simple-go-webserver</a></div>
<p> </p>
<h3 id="heading-getting-started">Getting Started 🏁</h3>
<p>Let’s kickstart our journey by creating a simple web server that serves static HTML files and handles HTTP requests. Follow these steps:</p>
<p>Step 1: Setting Up the Project</p>
<pre><code class="lang-javascript">mkdir simple-go-webserver
cd simple-go-webserver
mkdir <span class="hljs-keyword">static</span>
cd <span class="hljs-keyword">static</span>
# Create index.html, form.html, and hello.html (you can copy the content <span class="hljs-keyword">from</span> the provided GitHub links)
</code></pre>
<p>Step 2: Writing the Go Code</p>
<p>Create a file named <code>main.go</code> in the project directory and add the following code:</p>
<pre><code class="lang-javascript">package main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net/http"</span>
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    <span class="hljs-comment">// Handler logic for /hello route</span>
}
func formHandler(w http.ResponseWriter, r *http.Request) {
    <span class="hljs-comment">// Handler logic for /form route</span>
}
func main() {
    <span class="hljs-comment">// Main function logic</span>
}
</code></pre>
<p>Step 3: Running the Web Server</p>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> run main.<span class="hljs-keyword">go</span>
</code></pre>
<p>Open your web browser and visit <a target="_blank" href="http://localhost:8080/">http://localhost:8080</a> to see your web server in action!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696269968698/1e0d07e9-ca70-484f-8ea8-1eaa4fee3b7b.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696269971231/158e14a4-391c-4b87-9338-55671d9863a7.png" alt /></p>
<h3 id="heading-key-components-of-the-code">Key Components of the Code 🧩</h3>
<p>Let’s break down the crucial components of the code:</p>
<p>1. Importing Packages: We import necessary packages like <code>fmt</code> for formatted I/O, <code>log</code> for logging, and <code>net/http</code> for building HTTP servers and handling HTTP requests and responses.</p>
<p>2. Handlers: We define two handler functions:</p>
<ul>
<li><p><code>helloHandler</code>: Handles requests to the "/hello" route.</p>
</li>
<li><p><code>formHandler</code>: Handles POST requests to the "/form" route.</p>
</li>
</ul>
<p>3. Route Handling: We use <code>http.HandleFunc</code> to associate our handler functions with specific routes, such as /hello and /form.</p>
<p>4. Serving Static Files: We create an HTTP file server to serve static files from the “static” directory using <code>http.FileServer</code>.</p>
<p>5. Listening and Serving: We use <code>http.ListenAndServe</code> to start the web server on port 8080.</p>
<h3 id="heading-conclusion">Conclusion 🎉</h3>
<p>Congratulations! You’ve successfully built a simple web server using the Go programming language. This project lays the foundation for more advanced web applications and APIs. Remember, practice and experimentation are key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696269973602/58affd20-9c3d-4276-be54-2616897393af.png" alt /></p>
<p>Explore the code, add new features, and refer to the <a target="_blank" href="https://go.dev/doc/">Go documentation</a> to enhance your web development skills. Happy coding! 🚀</p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on social media 📲</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Best Practices for Designing RESTful APIs: A Developer’s Guide 🚀]]></title><description><![CDATA[In this blog post, we’ll delve into best practices for designing REST endpoints, complete with examples, to help you build robust and user-friendly APIs.]]></description><link>https://devangtomar.hashnode.dev/best-practices-for-designing-restful-apis-a-developers-guide-25febdb00929</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/best-practices-for-designing-restful-apis-a-developers-guide-25febdb00929</guid><category><![CDATA[REST API]]></category><category><![CDATA[REST]]></category><category><![CDATA[restful]]></category><category><![CDATA[Rest operator]]></category><category><![CDATA[GraphQL]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sun, 10 Sep 2023 08:33:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338455825/efa689bb-f267-438a-99b1-8a62e3c5f6d2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a software developer, you likely encounter RESTful APIs frequently. REST (Representational State Transfer) is an architectural style for designing networked applications and adhering to its principles is crucial for creating scalable, maintainable, and efficient web services. In this blog post, we’ll delve into best practices for designing REST endpoints, complete with examples, to help you build robust and user-friendly APIs.</p>
<p><strong>1. Keep it Simple ✅</strong></p>
<p>When designing your REST API, simplicity is key. Your API naming should be self-describing and easy to understand. Avoid complex query parameters and opt for clear and concise resource names.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338446053/d6869157-b55c-4c24-960a-76dcd8c357fe.jpeg" alt class="image--center mx-auto" /></p>
<p>For example:</p>
<pre><code class="lang-javascript">✅ /api/users/<span class="hljs-number">12345</span>
❌ /api?type=user&amp;id=<span class="hljs-number">12345</span>
</code></pre>
<h4 id="heading-2-use-plural-nouns-for-naming-restful-uris"><strong>2. Use Plural Nouns for Naming RESTful URIs 📛</strong></h4>
<p>To maintain consistency and improve intuitiveness, use plural nouns to represent resources in your endpoint names. Avoid using verbs or actions, as the HTTP methods already convey the action. Examples:</p>
<pre><code class="lang-javascript">✅ GET Users -&gt; <span class="hljs-regexp">/api/u</span>sers
✅ GET User account -&gt; <span class="hljs-regexp">/api/u</span>sers/{userId}
✅ GET User’s rights -&gt; <span class="hljs-regexp">/api/u</span>sers/{userId}/rights
❌ GET Users -&gt; <span class="hljs-regexp">/api/g</span>etAllUsers
</code></pre>
<h4 id="heading-3-stick-to-standard-http-methods"><strong>3. Stick to Standard HTTP Methods 🤌</strong></h4>
<p>For CRUD operations (Create, Read, Update, and Delete), always use standard HTTP methods. This ensures consistency across your API and helps developers understand your endpoints quickly. Examples:</p>
<pre><code class="lang-javascript">POST /users         <span class="hljs-comment">// Create a new user</span>
GET /users          <span class="hljs-comment">// Get all users</span>
GET /users/{id}     <span class="hljs-comment">// Get a specific user</span>
PUT /users/{id}     <span class="hljs-comment">// Update a specific user</span>
DELETE /users/{id}  <span class="hljs-comment">// Delete a specific user</span>
</code></pre>
<h4 id="heading-4-never-use-crud-function-names-in-uris"><strong>4. Never use CRUD function names in URIs 🔗</strong></h4>
<p>Avoid using URIs to indicate CRUD functions. URIs should only be used to uniquely identify resources, not actions upon them. Examples:</p>
<pre><code class="lang-javascript">❌ /api/getUsers
❌ /api/getUserRights
✅ GET /api/users
✅ GET /api/users/<span class="hljs-number">12345</span>/rights
</code></pre>
<h4 id="heading-5-use-forward-slash-to-indicate-hierarchical-relationships"><strong>5. Use forward slash (/) to indicate hierarchical relationships ⚔️</strong></h4>
<p>The forward slash (/) character indicates a hierarchical relationship between resources in the URI path. Examples:</p>
<pre><code class="lang-javascript">/api/users/{userId}/rights
/api/customers/{id}/orders
</code></pre>
<h4 id="heading-6-use-hyphens"><strong>6. Use Hyphens (-) ⏸️</strong></h4>
<p>To improve the readability of long path segments, use hyphens (-) instead of underscores (_). Examples:</p>
<pre><code class="lang-javascript">/api/customers/{id}/addresses/{address-id}
/api/customers/{id}/shipping-addresses/{address-id}
</code></pre>
<h4 id="heading-7-embrace-query-parameters-for-flexibility"><strong>7. Embrace Query Parameters for Flexibility 💪</strong></h4>
<p>Instead of creating new APIs for sorting, filtering, and pagination, enable these capabilities in your resource collection API using query parameters. This keeps your API clean and flexible. Example:</p>
<pre><code class="lang-javascript">GET /users?gender=male&amp;age=<span class="hljs-number">25</span>–<span class="hljs-number">35</span>&amp;sort=age,desc&amp;page=<span class="hljs-number">1</span>&amp;size=<span class="hljs-number">10</span>
</code></pre>
<h4 id="heading-8-versioning-matters-be-consistent"><strong>8. Versioning Matters: Be Consistent 🆚</strong></h4>
<p>Include the version number in the URL or as a request header to maintain backward compatibility and allow for smooth transitions when making changes to your API. Examples:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// URL versioning</span>
GET /api/v1/users

<span class="hljs-comment">// Header versioning</span>
GET /api/users
<span class="hljs-attr">Accept</span>: application/vnd.example.v1+json
</code></pre>
<h4 id="heading-9-communicate-with-the-right-status-codes"><strong>9. Communicate with the Right Status Codes ❌</strong></h4>
<p>Use the correct HTTP status codes to inform clients about the outcome of their requests.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338447560/216c8097-edd6-428f-8d45-528e0bc7f7e4.jpeg" alt class="image--center mx-auto" /></p>
<p>This helps developers handle errors and understand API call results effectively. Examples:</p>
<pre><code class="lang-javascript">- <span class="hljs-number">200</span> OK: Successful GET or PUT requests
- <span class="hljs-number">201</span> Created: Successful POST requests
- <span class="hljs-number">204</span> No Content: Successful DELETE requests
- <span class="hljs-number">400</span> Bad Request: Invalid client request
- <span class="hljs-number">401</span> Unauthorized: Request requires authentication
- <span class="hljs-number">403</span> Forbidden: Client lacks permission
- <span class="hljs-number">404</span> Not Found: Requested resource not found
- <span class="hljs-number">500</span> Internal Server <span class="hljs-built_in">Error</span>: Server-side error
</code></pre>
<h4 id="heading-10-boost-discoverability-with-hateoas"><strong>10. Boost Discoverability with HATEOAS ⏩</strong></h4>
<p>Implement Hypermedia As The Engine Of Application State (HATEOAS) to provide links to related resources in API responses.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338449002/b5881328-26b2-41fb-9bcf-b8687ab63592.jpeg" alt class="image--center mx-auto" /></p>
<p>This improves discoverability and enables developers to navigate your API with ease. Example:</p>
<pre><code class="lang-javascript">GET /users/<span class="hljs-number">123</span>
{
 <span class="hljs-string">"id"</span>: <span class="hljs-number">123</span>,
 <span class="hljs-string">"name"</span>: <span class="hljs-string">"John Doe"</span>,
 <span class="hljs-string">"links"</span>: [
 {
 <span class="hljs-string">"rel"</span>: <span class="hljs-string">"self"</span>,
 <span class="hljs-string">"href"</span>: <span class="hljs-string">"/users/123"</span>
 },
 {
 <span class="hljs-string">"rel"</span>: <span class="hljs-string">"edit"</span>,
 <span class="hljs-string">"href"</span>: <span class="hljs-string">"/users/123/edit"</span>
 },
 {
 <span class="hljs-string">"rel"</span>: <span class="hljs-string">"delete"</span>,
 <span class="hljs-string">"href"</span>: <span class="hljs-string">"/users/123"</span>
 }
 ]
}
</code></pre>
<h4 id="heading-11-comprehensive-documentation-a-must-have"><strong>11. Comprehensive Documentation: A Must-Have 📃</strong></h4>
<p>An API is only as good as its documentation. Clear, consistent, and interactive documentation is crucial for developers to understand and work effectively with your API. Utilize tools like Swagger or API Blueprint to generate comprehensive documentation for your endpoints.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338451402/a88e270b-c94c-4ab5-b3b0-88889003c27c.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-12-authentication-and-authorization"><strong>12. Authentication and Authorization</strong></h4>
<p>Implement proper authentication and authorization mechanisms to secure your RESTful APIs. Use industry-standard protocols like OAuth 2.0 or JWT (JSON Web Tokens) to authenticate and authorize client requests. This ensures that only authorized users can access protected resources.</p>
<pre><code class="lang-javascript">@app.route(<span class="hljs-string">'/api/users'</span>, methods=[<span class="hljs-string">'GET'</span>])
@authenticate
@authorize(<span class="hljs-string">'admin'</span>)
def get_users():
    # Logic to retrieve users
    <span class="hljs-keyword">return</span> jsonify(users)

@app.route(<span class="hljs-string">'/api/users'</span>, methods=[<span class="hljs-string">'POST'</span>])
@authenticate
def create_user():
    # Logic to create a <span class="hljs-keyword">new</span> user
    <span class="hljs-keyword">return</span> jsonify(user)
</code></pre>
<h4 id="heading-13-error-handling"><strong>13. Error Handling ⚠️</strong></h4>
<p>Handle errors gracefully by providing meaningful error messages and appropriate HTTP status codes. Include error details in the response body to assist developers in troubleshooting. Use consistent error formats across your API to make error handling easier for clients.</p>
<pre><code class="lang-javascript">{
 “error”: {
 “code”: <span class="hljs-number">404</span>,
 “message”: “Resource not found”,
 “details”: “The requested resource could not be found.”
 }
}
</code></pre>
<h4 id="heading-14-pagination"><strong>14. Pagination 📄</strong></h4>
<p>When dealing with large collections of resources, implement pagination to improve performance and reduce the amount of data transferred. Use query parameters like `page` and `size` to control the number of results returned per page and navigate through the collection.</p>
<pre><code class="lang-javascript">@app.route(‘/api/users’, methods=[‘GET’])
def get_users():
 page = request.args.get(‘page’, <span class="hljs-keyword">default</span>=<span class="hljs-number">1</span>, type=int)
 size = request.args.get(‘size’, <span class="hljs-keyword">default</span>=<span class="hljs-number">10</span>, type=int)

 # Logic to retrieve paginated users
 <span class="hljs-keyword">return</span> jsonify(users)
</code></pre>
<h4 id="heading-15-caching"><strong>15. Caching 💵</strong></h4>
<p>Leverage caching mechanisms to improve the performance of your API.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338452824/2752a498-ed91-4f21-bd93-91f88ec2b118.jpeg" alt class="image--center mx-auto" /></p>
<p>Use appropriate caching headers like `Cache-Control` and `ETag` to enable client-side caching and reduce unnecessary network requests.</p>
<pre><code class="lang-javascript">@app.route(‘/api/users’, methods=[‘GET’])
@cache.cached(timeout=<span class="hljs-number">60</span>)
def get_users():
 # Logic to retrieve users
 <span class="hljs-keyword">return</span> jsonify(users)
</code></pre>
<h4 id="heading-16-input-validation"><strong>16. Input Validation 🔠</strong></h4>
<p>Validate and sanitize user input to prevent security vulnerabilities like SQL injection or cross-site scripting (XSS) attacks. Implement server-side input validation to ensure that only valid and safe data is processed by your API.</p>
<pre><code class="lang-javascript">@app.route(‘/api/users’, methods=[‘POST’])
def create_user():
 username = request.json.get(‘username’)
 email = request.json.get(‘email’)

 # Validate input
 <span class="hljs-keyword">if</span> not username or not email:
 <span class="hljs-keyword">return</span> jsonify(error=’Invalid input’), <span class="hljs-number">400</span>

 # Logic to create a <span class="hljs-keyword">new</span> user
 <span class="hljs-keyword">return</span> jsonify(user)
</code></pre>
<h4 id="heading-17-rate-limiting"><strong>17. Rate Limiting 🚤</strong></h4>
<p>Implement rate limiting to protect your API from abuse and ensure fair usage. Set limits on the number of requests a client can make within a specific time period to prevent excessive usage and maintain API performance.</p>
<pre><code class="lang-javascript">@app.route(‘/api/users’, methods=[‘GET’])
@ratelimit.limit(‘<span class="hljs-number">100</span>/hour’)
def get_users():
 # Logic to retrieve users
 <span class="hljs-keyword">return</span> jsonify(users)
</code></pre>
<h4 id="heading-18-api-versioning"><strong>18. API Versioning 🔢</strong></h4>
<p>Plan for future changes by designing your API with versioning in mind. Use versioning techniques like URL versioning or request header versioning to introduce breaking changes without impacting existing clients.</p>
<pre><code class="lang-javascript"># URL versioning
@app.route(‘/api/v1/users’, methods=[‘GET’])
def get_users_v1():
 # Logic to retrieve users
 <span class="hljs-keyword">return</span> jsonify(users)

# Header versioning
@app.route(<span class="hljs-string">'/api/users'</span>, methods=[<span class="hljs-string">'GET'</span>])
@version(<span class="hljs-number">1</span>)
def get_users_v1():
 # Logic to retrieve users
 <span class="hljs-keyword">return</span> jsonify(users)
</code></pre>
<h4 id="heading-19-continuous-testing-and-monitoring"><strong>19. Continuous Testing and Monitoring 🧪</strong></h4>
<p>Regularly test and monitor your API to ensure its reliability and performance. Implement automated tests, monitor API metrics, and use logging and error tracking tools to identify and resolve issues promptly.</p>
<pre><code class="lang-javascript"># Automated tests using pytest
def test_get_users():
 response = client.get(‘/api/users’)
 assert response.status_code == <span class="hljs-number">200</span>
 assert response.json[‘users’] is not None

# Monitoring API metrics using Prometheus
<span class="hljs-keyword">from</span> prometheus_flask_exporter <span class="hljs-keyword">import</span> PrometheusMetrics
metrics = PrometheusMetrics(app)
metrics.info(<span class="hljs-string">'app_info'</span>, <span class="hljs-string">'Application Information'</span>, version=<span class="hljs-string">'1.0.0'</span>)

# Logging and error tracking using Sentry
<span class="hljs-keyword">import</span> sentry_sdk
sentry_sdk.init(dsn=<span class="hljs-string">'your-sentry-dsn'</span>)
</code></pre>
<p>Now go ahead and build amazing RESTful APIs that developers will love to use! 💪💻</p>
<h4 id="heading-conclusion"><strong>Conclusion 💭</strong></h4>
<p>Designing RESTful APIs requires careful consideration of various factors, including simplicity, naming conventions, standard HTTP methods, versioning, error handling, and security.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694338454014/5fcfcb60-412e-4e5e-915e-0b2db3d01292.jpeg" alt class="image--center mx-auto" /></p>
<p>By following these additional best practices, you can create APIs that are not only functional but also scalable, secure, and well-documented. Happy API designing! 🌟👨‍💻</p>
<h4 id="heading-connect-with-me-on-social-media"><strong>Connect with Me on social media 📲</strong></h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
]]></content:encoded></item><item><title><![CDATA[Mastering Dockerfile ️🐳: 10 Advanced Tips and Best Practices ⚔]]></title><description><![CDATA[Dockerfile is a robust tool that empowers developers to create and deploy applications within Docker containers.]]></description><link>https://devangtomar.hashnode.dev/mastering-dockerfile-efb88f-10-advanced-tips-and-best-practices-ea6ea3162d8c</link><guid isPermaLink="true">https://devangtomar.hashnode.dev/mastering-dockerfile-efb88f-10-advanced-tips-and-best-practices-ea6ea3162d8c</guid><category><![CDATA[Devops articles]]></category><category><![CDATA[Dockerfile]]></category><category><![CDATA[multi stage docker file]]></category><category><![CDATA[Docker compose]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Devang Tomar]]></dc:creator><pubDate>Sat, 02 Sep 2023 06:44:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693640729187/48c347a0-34dd-435a-9193-ab504a32c219.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Dockerfile is a robust tool that empowers developers to create and deploy applications within Docker containers. While many developers are acquainted with the fundamentals of Dockerfile, there exists a treasure trove of advanced features and best practices that may not have yet graced your Docker repertoire.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:630/1*WxOtSjZrTjlr6D2OJlLD5A.jpeg" alt /></p>
<p>In this exploration, we will unearth ten lesser-known Dockerfile tricks and tips to elevate your Docker skills, optimizing your builds and streamlining your containerized applications.</p>
<h4 id="heading-1-dockerignore-file-reducing-build-context-size">1. .dockerignore File: Reducing Build Context Size</h4>
<p>A <code>.dockerignore</code> file is your secret weapon to exclude unnecessary files and directories from the build context. Shrinking the build context proves invaluable when dealing with large files or directories that need not clutter your image. <a target="_blank" href="https://docs.docker.com/engine/reference/builder/#dockerignore-file">Learn more</a>.</p>
<pre><code class="lang-javascript"># Example .dockerignore file
node_modules
*.log
</code></pre>
<h4 id="heading-2-copy-vs-add-know-the-differences">2. COPY vs. ADD: Know the Differences</h4>
<p>The <code>COPY</code> and <code>ADD</code> instructions may seem similar, but they harbor distinct nuances. Learn when to employ each, and why <code>COPY</code> is generally preferred according to Docker’s official documentation. <a target="_blank" href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy">Read more</a>.</p>
<pre><code class="lang-javascript"># Using COPY
COPY src/ <span class="hljs-regexp">/app/</span>
# Using ADD <span class="hljs-keyword">with</span> tar extraction
ADD src.tar.gz /app/
</code></pre>
<h4 id="heading-3-multi-stage-builds-streamlining-for-production">3. Multi-Stage Builds: Streamlining for Production</h4>
<p>Discover the power of multi-stage builds. Employ multiple <code>FROM</code> statements in a single Dockerfile to craft an environment for building your application, then efficiently copy the results into a lean, production-ready image. <a target="_blank" href="https://docs.docker.com/build/building/multi-stage/">More details</a>.</p>
<pre><code class="lang-javascript"># Stage <span class="hljs-number">1</span>: Build your golang executable
FROM golang <span class="hljs-keyword">as</span> buildStage
WORKDIR /app
COPY . .
RUN go build -o /go/bin/myapp

# Stage <span class="hljs-number">2</span>: Run the application
FROM alpine:latest
COPY --<span class="hljs-keyword">from</span>=buildStage /go/bin/myapp /usr/local/bin/myapp
CMD [<span class="hljs-string">"myapp"</span>]
</code></pre>
<h4 id="heading-4-multi-layers-and-caching-speeding-up-builds">4. Multi-Layers and Caching: Speeding Up Builds</h4>
<p>Docker leverages caching to expedite builds. Understand how layers, <code>RUN</code>, <code>COPY</code>, and <code>ADD</code> instructions influence caching, and when to employ techniques like chaining <code>RUN</code> commands. <a target="_blank" href="https://docs.docker.com/build/cache/">Dig deeper</a>.</p>
<pre><code class="lang-javascript"># Good practice: Chaining RUN commands
RUN yum --disablerepo=* --enablerepo=<span class="hljs-string">"myrepo"</span> &amp;&amp; yum update -y &amp;&amp; yum install nmap
</code></pre>
<h4 id="heading-5-onbuild-instruction-automation-beyond-your-image">5. ONBUILD Instruction: Automation Beyond Your Image</h4>
<p>Explore the <code>ONBUILD</code> instruction, a nifty tool to automate tasks when your Docker image serves as the base for another image. Unearth strategies to prevent resource conflicts and optimize your workflow. <a target="_blank" href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#onbuild">Learn more</a>.</p>
<pre><code class="lang-javascript">ONBUILD COPY . /app/src
ONBUILD RUN /build.sh
</code></pre>
<h4 id="heading-6-change-your-user-enhancing-security">6. Change Your User: Enhancing Security</h4>
<p>Improve security by modifying the default container user. Learn how to switch to a non-root user, bolstering security and reducing potential vulnerabilities. <a target="_blank" href="https://docs.docker.com/engine/reference/builder/#user">Read about it</a>.</p>
<pre><code class="lang-javascript">FROM alpine:latest

# Create a <span class="hljs-keyword">new</span> user and <span class="hljs-keyword">switch</span> to that user
RUN adduser -D -u <span class="hljs-number">1000</span> appuser
USER appuser

# <span class="hljs-built_in">Set</span> the working directory to /app
WORKDIR /app

# Copy the script to the container and make it executable
COPY script.sh .
RUN chmod +x script.sh

# Run the script
CMD [<span class="hljs-string">"./script.sh"</span>]
</code></pre>
<h4 id="heading-7-container-health-checks-ensuring-reliability">7. Container Health Checks: Ensuring Reliability</h4>
<p>Docker’s <code>HEALTHCHECK</code> instruction monitors container health. Configure checks to detect failures and automate container restarts. Ensure your applications stay robust and reliable. <a target="_blank" href="https://docs.docker.com/engine/reference/builder/#healthcheck">Discover more</a>.</p>
<pre><code class="lang-javascript"># <span class="hljs-built_in">Set</span> the command to start the web server
CMD [<span class="hljs-string">"python"</span>, <span class="hljs-string">"app.py"</span>]

# Add a healthcheck <span class="hljs-keyword">for</span> the web server
HEALTHCHECK --interval=<span class="hljs-number">5</span>s \\
            --timeout=<span class="hljs-number">5</span>s \\
            CMD curl --fail &lt;http:<span class="hljs-comment">//localhost:5000/health&gt; || exit 1</span>
</code></pre>
<h4 id="heading-8-shell-form-leveraging-shell-specific-features">8. Shell Form: Leveraging Shell-Specific Features</h4>
<p>In addition to the exec form, Dockerfiles support a shell form that offers features like environment variable substitution and command chaining. Unearth the power of this form to customize your commands. <a target="_blank" href="https://docs.docker.com/engine/reference/builder/#run">Explore it</a>.</p>
<pre><code class="lang-javascript"># Using Shell Form
SHELL [<span class="hljs-string">"/bin/bash"</span>, <span class="hljs-string">"-c"</span>]
RUN echo <span class="hljs-string">"This is a shell command."</span>
</code></pre>
<h4 id="heading-9-metadata-instructions-organizing-your-images">9. Metadata Instructions: Organizing Your Images</h4>
<p><code>EXPOSE</code> and <code>LABEL</code> instructions provide essential metadata. Be explicit about exposed ports and utilize labels to convey image purpose, authorship, and more. <a target="_blank" href="https://docs.docker.com/engine/reference/builder/#expose">Dive into details</a>.</p>
<pre><code class="lang-javascript">FROM ubuntu:latest
LABEL maintainer=<span class="hljs-string">"Your Name &lt;youremail@example.com&gt;"</span>
LABEL description=<span class="hljs-string">"This is a simple Dockerfile example that uses the LABEL and EXPOSE instructions."</span>
RUN apt-get update &amp;&amp; \\
    apt-get install -y nginx
EXPOSE <span class="hljs-number">80</span>
CMD [<span class="hljs-string">"nginx"</span>, <span class="hljs-string">"-g"</span>, <span class="hljs-string">"daemon off;"</span>]
</code></pre>
<h4 id="heading-10-docker-images-tar-file-magic">10. Docker Images: Tar File Magic</h4>
<p>Did you know? Docker images are essentially compressed tar files with metadata. Understand how Docker packages your files, compresses them, and maintains them as an efficient <code>tarball</code>. Learn why this knowledge is essential for efficient Docker practices.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693640725531/8f98e310-3696-480c-b195-01b7deddb52e.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-conclusion">Conclusion 💭</h4>
<p>With a touch of finesse and these advanced Dockerfile techniques, you can bolster security, enhance readability, expedite build times, and ultimately improve your continuous integration pipeline and productivity.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693640726966/96c62035-68c4-4ac8-bcb4-ba363cdc9e78.gif" alt class="image--center mx-auto" /></p>
<p>By running containers as non-root users, streamlining Dockerfiles, and using efficient build practices, you’ll not only optimize images but also create a more secure and efficient development environment. It’s time to unlock the full potential of Dockerfile and elevate your containerization game.</p>
<h4 id="heading-connect-with-me-on-social-media">Connect with Me on Social Media</h4>
<p>🐦 Follow me on Twitter: <a target="_blank" href="https://twitter.com/devangtomar7">devangtomar7</a><br />🔗 Connect with me on LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/devangtomar">devangtomar</a><br />📷 Check out my Instagram: <a target="_blank" href="https://instagram.com/be_ayushmann">be_ayushmann</a><br />Ⓜ️ Checkout my blogs on Medium: <a target="_blank" href="https://medium.com/u/8f5e1c86129d">Devang Tomar</a><br /><strong>#️⃣</strong> Checkout my blogs on Hashnode: <a target="_blank" href="https://devangtomar.hashnode.dev/">devangtomar</a><br /><strong>🧑‍💻</strong> Checkout my blogs on Dev.to: <a target="_blank" href="https://dev.to/devangtomar">devangtomar</a></p>
<p><img src="https://cdn-images-1.medium.com/max/800/0*wCUcUcpsOEIO2vlF" alt class="image--center mx-auto" /></p>
]]></content:encoded></item></channel></rss>