<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Himanshu Koli on Medium]]></title>
        <description><![CDATA[Stories by Himanshu Koli on Medium]]></description>
        <link>https://medium.com/@koliv5936?source=rss-548c05b183ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_iW-WQaBLHRoWEC9Vags0g.jpeg</url>
            <title>Stories by Himanshu Koli on Medium</title>
            <link>https://medium.com/@koliv5936?source=rss-548c05b183ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:09:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@koliv5936/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Garbage Collection Works in Java]]></title>
            <link>https://blog.stackademic.com/how-garbage-collection-works-in-java-eade0bcc0600?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/eade0bcc0600</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 11:49:58 GMT</pubDate>
            <atom:updated>2026-02-21T11:49:58.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xUbmmfsx7o-jVO-j" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Understanding JVM Memory, G1 GC, Old Gen Exhaustion &amp; Real-World Latency Incidents</h3><p>If you build Java backend systems, especially high-throughput microservices, understanding <strong>Garbage Collection (GC)</strong> is not optional.</p><p>Many production incidents that look like:</p><ul><li>API latency spikes</li><li>Thread pool saturation</li><li>Upstream timeouts</li><li>CPU surges</li></ul><p>Are often rooted in <strong>heap memory pressure and GC behavior</strong>.</p><p>In this article, we’ll break down:</p><ul><li>How JVM heap works</li><li>What Young and Old generations are</li><li>How G1 GC operates</li><li>What happens during Old Gen exhaustion</li><li>Why GC pause time increases latency</li><li>How to detect and prevent such incidents</li></ul><h3>1. JVM Memory Model</h3><pre>+--------------------------------------------------+<br>|                    JVM Memory                    |<br>+--------------------------------------------------+<br>|                                                  |<br>|  +------------------- Heap -------------------+  |<br>|  |                                            |  |<br>|  |   +-------- Young Gen --------+            |  |<br>|  |   |  Eden  | Survivor | S0/S1 |            |  |<br>|  |   +-----------------------------+          |  |<br>|  |                                            |  |<br>|  |   +------------ Old Gen ------------+      |  |<br>|  |   |   Long-lived Objects            |      |  |<br>|  |   +----------------------------------+     |  |<br>|  +--------------------------------------------+  |<br>|                                                  |<br>|  Non-Heap:                                       |<br>|   - Metaspace                                    |<br>|   - Code Cache                                   |<br>|   - Thread Stacks                                |<br>+--------------------------------------------------+</pre><p>Java memory is divided into two broad areas:</p><h4>Heap Memory</h4><p>Where objects are allocated at runtime.<br>Configured using:</p><pre>-Xms (initial heap size)<br>-Xmx (max heap size)</pre><p>Heap is further divided into:</p><ul><li>Young Generation</li><li>Old Generation</li></ul><h4>Non-Heap Memory</h4><ul><li>Metaspace (class metadata)</li><li>Code cache</li><li>Thread stacks</li><li>Direct memory</li></ul><p>Most production GC incidents are <strong>heap-related</strong>, especially Old Gen.</p><h4>Object Lifecycle in JVM</h4><pre>Step 1: Object Created<br>        ↓<br>     [ Eden ]<br><br>Step 2: Minor GC Runs<br>        ↓<br>     Survives?<br>        ↓ Yes<br>     [ Survivor Space ]<br><br>Step 3: Survives Multiple GCs?<br>        ↓ Yes<br>     Promoted<br>        ↓<br>     [ Old Generation ]</pre><h3>2. Young Generation :Where Objects Are Born</h3><p>The Young Generation consists of:</p><ul><li>Eden Space</li><li>Survivor Spaces (S0, S1)</li></ul><h3>How it works:</h3><ol><li>New objects are created in Eden.</li><li>When Eden fills → Minor GC runs.</li><li>Surviving objects move to Survivor.</li><li>Objects that survive multiple cycles get promoted to Old Gen.</li></ol><p>Most objects die young (request DTOs, JSON parsing, temporary objects).</p><p>Minor GC:</p><ul><li>Fast</li><li>Frequent</li><li>Low impact</li></ul><h3>3. Old Generation :Where Problems Begin</h3><p>Old Gen stores long-lived objects:</p><ul><li>Caches</li><li>Static maps</li><li>Thread pools</li><li>Retained collections</li><li>Leaked references</li></ul><p>Old Gen GC is expensive.</p><p>If Old Gen usage continuously rises and GC cannot reclaim enough memory, the JVM enters <strong>memory pressure mode</strong>.</p><h3>4. G1 GC :Garbage First Collector</h3><p>Modern JVMs commonly use <strong>G1 GC</strong>.</p><p>Unlike older collectors, G1:</p><ul><li>Divides heap into regions</li><li>Cleans regions with most garbage first</li><li>Attempts to maintain predictable pause times</li></ul><p>Instead of cleaning entire generations, G1 performs:</p><ul><li>Young GC</li><li>Mixed GC</li><li>Full GC (worst case)</li></ul><h3>5. What Triggers Aggressive GC?</h3><p>G1 has an internal threshold called:</p><p><strong>IHOP — Initiating Heap Occupancy Percent</strong></p><p>When Old Gen crosses a certain percentage of total heap:</p><ul><li>G1 starts running Mixed GC more aggressively.</li><li>It scans Old regions to reclaim memory.</li><li>If reclaimable memory is low → GC runs more frequently.</li><li>Pause times increase.</li></ul><p>This is exactly what happens in real production incidents.</p><h3>6. Stop-The-World (STW) Pauses</h3><p>During GC:</p><p>All application threads pause.</p><p>This is called <strong>Stop-The-World</strong>.</p><p>Even if a pause is:</p><ul><li>200–500ms<br>If frequent, the impact compounds:</li><li>Requests queue up</li><li>Threads remain blocked</li><li>Thread pools saturate</li><li>Latency spikes</li></ul><h3>7. What Is GC Pause Time?</h3><p>GC Pause Time = Duration for which application threads are halted.</p><p>If pause frequency increases:</p><ul><li>latency increases</li><li>CPU usage increases</li><li>Threads peak rises</li><li>Upstream timeouts begin</li></ul><p>Monitoring this metric is critical.</p><h3>8. Threads Peak :Why It Spikes During GC</h3><p>When GC pauses increase:</p><ol><li>Request processing slows.</li><li>Existing threads remain busy longer.</li><li>New requests continue arriving.</li><li>Thread pool fills.</li><li>Threads peak rises.</li></ol><p>Each thread consumes stack memory (~1MB default).</p><p>1000 threads ≈ ~1GB stack memory.</p><p>Thread spike is usually a <strong>symptom</strong>, not root cause.</p><h3>9. Real-World Failure Pattern (Old Gen Exhaustion)</h3><p>Let’s understand the classic chain:</p><ol><li>Old Gen steadily grows over days.</li><li>GC frees some memory but baseline rises.</li><li>Old Gen reaches ~85–95% of heap.</li><li>G1 triggers aggressive Mixed GC.</li><li>CPU spent in GC increases.</li><li>Pause times increase.</li><li>Threads block.</li><li>P99 latency spikes.</li><li>Upstream services timeout.</li><li>Restart can clears heap.</li></ol><p>This pattern strongly indicates <strong>long-lived object retention or memory leak</strong>.</p><h3>10. How to Prove GC Was the Root Cause</h3><p>You correlate:</p><ul><li>Old Gen usage graph</li><li>GC pause time</li><li>GC CPU %</li><li>Thread count</li><li>API latency timestamps</li></ul><p>If all spike together, and restart fixes it immediately:<br>The cause is heap-state driven.<br>Not traffic.<br>Not deployment.<br>Not infra.</p><h3>11. Common Causes of Old Gen Buildup</h3><ul><li>Unbounded caches</li><li>ConcurrentHashMap without eviction</li><li>Caffeine cache without max size</li><li>Static collections growing</li><li>ThreadLocal misuse</li><li>CompletableFuture chains retaining references</li><li>Unclosed HTTP responses</li><li>Connection pool mismanagement</li></ul><p>It’s often not a “classic memory leak”.<br>It’s object retention.</p><h3>12. Prevention Strategy</h3><h3>1. Add Monitoring Alerts</h3><ul><li>Old Gen &gt; 80%</li><li>GC pause time spike</li><li>GC CPU % &gt; 5–10%</li></ul><h3>2. Maintain Heap Headroom</h3><p>Avoid sustained usage above 80–85%.</p><h3>3. Analyze Heap Dumps</h3><pre>jmap -dump:live,format=b,file=heap.hprof &lt;pid&gt;</pre><p>Analyze using Eclipse MAT.</p><h3>4. Enable GC Logs</h3><pre>-Xlog:gc*</pre><h3>5. Fix Root Object Retention</h3><p>Controlled restarts are temporary mitigation, not solution.</p><h3>13. Key Takeaways</h3><ul><li>Heap ≠ Old Gen. Old Gen exhaustion is the real danger.</li><li>GC pause time directly impacts API latency.</li><li>Thread spikes are usually secondary effects.</li><li>Restart fixing the issue indicates heap-state dependency.</li><li>Monitoring Old Gen and GC pause time is mandatory in production systems.</li></ul><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, JAVA, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eade0bcc0600" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-garbage-collection-works-in-java-eade0bcc0600">How Garbage Collection Works in Java</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Devs Actually Track a System in Production Using Metrics and Alerts]]></title>
            <link>https://medium.com/@koliv5936/how-devs-actually-track-a-system-in-production-using-metrics-and-alerts-c505f6827ba5?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c505f6827ba5</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 20:12:25 GMT</pubDate>
            <atom:updated>2025-11-14T20:12:25.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xngNahzVr1n4xwae" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Tracking a system in production is one of the most underrated skills for developers. You can write the most elegant code, but if it crashes at 2 AM during a traffic spike, someone will still have to wake up and fix it.<br> This blog explains <em>how developers actually monitor real systems</em>, what they measure, how alerts work, and how you, even as a fresher, can understand it confidently.</p><p>Let’s go step by step.</p><h3>1. What Is Monitoring?</h3><p>Think of monitoring like a <strong>health tracker</strong> for your application.<br> Just like a smartwatch tracks your heart rate, steps, and sleep quality, monitoring tools track your system’s CPU usage, request latency, database performance, error rates, and more.</p><p>If something unusual happens, the system becomes slow or starts failing, monitoring helps engineers see the problem <em>before</em> users complain.</p><h3>2. Why Devs Track Systems in Production</h3><p>In the real world, systems fail. Even well-designed ones.</p><p>Here are common situations where monitoring saves the day:</p><h4>1. Sudden Traffic Spike</h4><p>Imagine your app usually gets 20 requests per second.<br> Suddenly, a viral post drives 2000 requests per second.</p><p>Metrics show:</p><ul><li>CPU rising</li><li>Response time increasing</li><li>Memory rising</li><li>Queue backlog increasing</li></ul><p>Alerts fire: devs scale up servers <em>before</em> customers see downtime.</p><h4>2. Memory Leak</h4><p>A small bug causes memory usage to increase 2–3 MB every minute.<br> For 2 hours, this goes unnoticed.<br> At 5 GB, the server crashes.</p><p>Monitoring helps spot:</p><ul><li>Steady memory increase</li><li>GC pressure</li><li>Container restart loops</li></ul><p>Fix deployed <em>before</em> it crashes again.</p><h4>3. Slow Database</h4><p>A single slow SQL query can block other queries.</p><p>Metrics show:</p><ul><li>DB CPU at 90%</li><li>Query latency rising</li><li>Active connections reaching max</li></ul><p>The engineering team knows where to look.</p><h4>4. Kafka / Queue Lag</h4><p>If consumers slow down, messages pile up.<br> Monitoring shows:</p><ul><li>Kafka lag increasing</li><li>Consumer throughput dropping</li></ul><p>Alerts trigger before customers see delays.</p><h3>3. Monitoring vs Logging vs Tracing</h3><ul><li>Monitoring tells you <em>what</em> is wrong using numeric metrics (CPU = 90%, errors = 2%).</li><li>Logging tells you <em>why</em> something happened by showing detailed events and error messages.</li><li>Tracing follows a single request across microservices so you can see which service or internal call caused the slowdown.<br> Together, they form the three pillars of <strong>observability</strong>.</li></ul><h3>4. Types of Metrics to Track</h3><p>Monitoring isn’t random — companies follow structured approaches like RED, USE, and application-level metrics.</p><h4>RED Metrics (Rate, Errors, Duration)</h4><p>Used mainly for APIs/microservices.</p><ul><li><strong>Rate</strong>: Number of requests per second</li><li><strong>Errors</strong>: Failed requests</li><li><strong>Duration</strong>: Latency of each request</li></ul><p>If latency goes up or errors spike, something is wrong.</p><h4>USE Metrics (Utilisation, Saturation, Errors)</h4><p>Used for system-level monitoring like CPU, disks, network, and queues.</p><ul><li><strong>Utilisation</strong>: How busy a resource is</li><li><strong>Saturation</strong>: How overloaded it is</li><li><strong>Errors</strong>: Failed operations</li></ul><p>Example:<br> CPU at 95% (high utilisation) + long run queue (high saturation) = server can become slow.</p><h4>Application Metrics</h4><p>These vary based on your tech stack.</p><p>Examples:</p><ul><li><strong>Goroutine count</strong> in Go apps</li><li><strong>Active DB connections</strong></li><li><strong>Query latency</strong></li><li><strong>Queue backlog</strong></li><li><strong>Kafka consumer lag</strong></li><li><strong>Cache hit ratio</strong> (Redis/Redis cluster)</li><li><strong>Job processing rate</strong> (cron workers)</li></ul><p>Apps feel healthy only when <strong>business logic metrics</strong> are also tracked, not just infra metrics.</p><h3>5. How Alerts Actually Work in Companies</h3><p>Alerts are rules that notify developers when something unusual happens.</p><h4>1. Threshold Alerts</h4><p>Fixed conditions.<br> Example:</p><ul><li>CPU &gt; 85% for 5 minutes</li><li>Error rate &gt; 2%</li><li>Kafka lag &gt; 10,000</li></ul><h3>2. Anomaly Alerts</h3><p>Machine-learning-based detection of unusual patterns.</p><p>Example:</p><ul><li>Traffic suddenly drops 40%</li><li>Latency spikes compared to the usual daily trend</li></ul><p>Useful when the normal varies a lot.</p><h4>3. Alert Fatigue</h4><p>When engineers receive too many alerts.</p><p>Symptoms:</p><ul><li>People start ignoring alerts</li><li>Important failures get missed</li><li>Team burnout</li></ul><p>Companies solve this by:</p><ul><li>Reducing low-priority alerts</li><li>Grouping similar alerts</li><li>Using on-call rotations</li></ul><h3>6. Tools Developers Use in Real Companies</h3><p>These tools are used across the industry:</p><ul><li><strong>Prometheus</strong>: open-source metric database</li><li><strong>Grafana</strong>: dashboard visualisations</li><li><strong>Datadog</strong>: SaaS monitoring (very popular in startups)</li><li><strong>New Relic</strong>: APM (Application Performance Monitoring)</li><li><strong>AWS CloudWatch: </strong>for AWS infra</li><li><strong>Google Cloud Monitoring: </strong>for GCP</li><li><strong>OpenTelemetry: </strong>unified way to collect logs, metrics, traces</li></ul><p>Prometheus + Grafana is the most common stack.</p><h3>7. How Engineers Test Monitoring Locally</h3><p>Before deploying anything, engineers test performance and monitoring on their machines.</p><h4>1. pprof</h4><p>Go developers use pprof to visualise CPU and memory usage locally.</p><h4>2. Load Testing</h4><p>Tools like:</p><ul><li>k6</li><li>Locust</li><li>JMeter</li></ul><p>help simulate real traffic to catch bottlenecks early.</p><h4>3. Synthetic Checks</h4><p>Small automated scripts that mimic user behaviour.<br> Example:<br> A script that hits /health or /login Every 1 minute, it measures latency.</p><p>These help detect failures <em>before</em> users face them.</p><h3>8. Real World Production Failure Examples</h3><h4>1. Latency spike caused by DB congestion</h4><p>Grafana showed:</p><ul><li>DB CPU shooting to 95%</li><li>Active connections hitting max</li><li>Slow query logs rising</li></ul><p>Root cause:<br> A new release added an inefficient SQL join.</p><p>Metrics pointed the exact direction.</p><h4>2. Kafka Consumer Behind by 300k Messages</h4><p>Lag graph showed a sudden upward slope.</p><p>Root cause:<br> An external API dependency slowed down.</p><p>Metrics helped identify:</p><ul><li>Consumer throughput dropped</li><li>Queue backlog growing</li></ul><h4>3. Memory Leak in a Go Worker</h4><p>Goroutine count grew continuously.</p><p>Memory graph also showed a saw-tooth pattern increasing gradually.</p><p>Root cause:<br> A faulty retry loop is creating goroutines without cleanup.</p><h4>4. Traffic Spike During Sale Event</h4><p>Requests-per-second shot up 10x.<br> Autoscaling kicked in.</p><p>Without monitoring, everything would’ve gone down.</p><h3>9. Best Practices for Freshers Learning Monitoring</h3><p>Here are the most practical things you can start with:</p><h4>Understand RED + USE</h4><p>These two frameworks cover most production failures.</p><h4>Get comfortable reading Grafana dashboards</h4><p>Find patterns like:</p><ul><li>Spikes</li><li>Drops</li><li>Slow increases</li><li>Correlation across graphs</li></ul><h4>Learn pprof early</h4><p>It makes you a better Go engineer.</p><h4>Add basic app metrics for every project</h4><p>Even local side projects can have:</p><ul><li>request count</li><li>error count</li><li>latency histogram</li><li>goroutine count</li></ul><h4>Avoid noisy alerts</h4><p>One meaningful alert is better than 20 useless ones.</p><h4>Learn how your company’s on-call system works</h4><p>PagerDuty, Opsgenie, Slack alerts — understand them</p><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c505f6827ba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buffered vs unbuffered channels in Go with code example]]></title>
            <link>https://blog.stackademic.com/buffered-vs-unbuffered-channels-in-go-with-code-example-45b2fc36bcd2?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/45b2fc36bcd2</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[go-waitgroup]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 18:03:12 GMT</pubDate>
            <atom:updated>2025-11-08T08:17:30.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZUuYW34dFe_HfzR" /><figcaption>Photo by <a href="https://unsplash.com/@hoodyk?utm_source=medium&amp;utm_medium=referral">Katherine Hood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>✅ First, What Is a Channel?</h3><p>A <strong>channel</strong> in Go is a communication pipe that allows one goroutine to send data to another goroutine safely.</p><p>Think of it like a pipe through which one routine sends a value and another receives it.</p><h3>✅ Unbuffered Channel (Synchronous Communication)</h3><p>An <strong>unbuffered channel</strong> has <strong>no storage capacity</strong>.<br> That means <strong>send and receive must happen at the same time.</strong></p><p>If a goroutine tries to send data, it <strong>blocks</strong> (waits) until another goroutine is ready to receive it.<br> Likewise, if a goroutine tries to receive, it <strong>blocks</strong> until a sender sends a value.</p><h3>Simple example:</h3><pre>ch := make(chan int) // unbuffered<br><br>go func() {<br>    ch &lt;- 10 // blocks until someone receives<br>}()<br>value := &lt;-ch // receiver unblocks the sender<br>fmt.Println(value)</pre><p>Here, both goroutines must “meet” at the channel.<br> It’s like a handshake; sender and receiver must be present together.</p><h3>✅ Buffered Channel (Asynchronous Communication)</h3><p>A <strong>buffered channel</strong> has storage space inside it.<br> You can send values <strong>without waiting</strong>, as long as there is space in the buffer.</p><p>Only when the buffer is <strong>full</strong> does the sender block.<br> Receiver blocks <strong>only when the buffer is empty</strong>.</p><h3>Example:</h3><pre>ch := make(chan int, 3) // buffer size = 3<br>ch &lt;- 1 // does NOT block<br>ch &lt;- 2 // does NOT block<br>ch &lt;- 3 // does NOT block<br>// ch &lt;- 4 // would block here, buffer full<br>fmt.Println(&lt;-ch) // receive 1<br>fmt.Println(&lt;-ch) // receive 2</pre><p>So buffered channels allow <strong>decoupling</strong>: sender and receiver don’t need to arrive at the same time.</p><h3>✅ When to Use What?</h3><h3>When to use unbuffered channels</h3><ul><li>You want strict synchronisation between goroutines</li><li>You want to guarantee the receiver processes the message immediately</li><li>Used in worker coordination, event signalling, goroutine handshakes</li></ul><h3>When to use buffered channels</h3><ul><li>You want to avoid blocking the sender</li><li>You want the producer and consumer to run at different speeds</li><li>Useful for pipelines, queues, background processing, and rate-limiting</li></ul><h3>✅ Pro-Level Example: Worker Pool</h3><pre>jobs := make(chan int, 5)     // buffered (queue)<br>results := make(chan int)     // unbuffered (sync result)<br>for w := 1; w &lt;= 3; w++ {<br>    go func(id int) {<br>        for j := range jobs {<br>            results &lt;- j * 2 // blocks until receiver reads<br>        }<br>    }(w)<br>}<br>for j := 1; j &lt;= 5; j++ {<br>    jobs &lt;- j // does not block immediately<br>}<br>close(jobs)<br>for a := 1; a &lt;= 5; a++ {<br>    fmt.Println(&lt;-results)<br>}</pre><ul><li>jobs channel is buffered so that the main goroutine can queue tasks fast</li><li>results channel is unbuffered, so workers and receiver sync for each result</li></ul><h3>✅ Real-World Use Case of Unbuffered Channel (Synchronous)</h3><h3>📌 Example: Payment Processing System (like Razorpay, Stripe, PayPal)</h3><p>In a financial company, every transaction must be <strong>confirmed before moving to the next step</strong> (because money can’t be “queued” casually).</p><p>Flow:</p><pre>API request → Validate → Debit account → Confirm success → Send response</pre><p>Here, an <strong>unbuffered channel</strong> can be used between goroutines like:</p><ul><li>Goroutine 1: Validates request</li><li>Goroutine 2: Talks to bank server / core banking system</li><li>Goroutine 3: Confirms debit and signals success</li></ul><p>Each step <strong>waits for the previous one</strong> — no async queueing allowed.</p><p>🔍 Why unbuffered?</p><ul><li>Forces <strong>strict ordering</strong> (you cannot debit unless validation is done)</li><li>Prevents race conditions in money flow</li><li>Ensures that if one step blocks, the whole flow pauses safely</li></ul><p>🧠 Think of it as:</p><blockquote><em>“Don’t proceed until I confirm, handshake required.”</em></blockquote><h3>✅ Real-World Use Case of Buffered Channel (Asynchronous)</h3><h3>📌 Example: Logging or Analytics Queue (Uber, Swiggy, LinkedIn)</h3><p>Companies generate <strong>millions of logs or metrics per second</strong>. If every log is written synchronously, the main system slows down.</p><p>So they use a <strong>buffered channel</strong> to collect logs fast, and a separate worker goroutine writes them to:</p><ul><li>Kafka</li><li>Database</li><li>Elasticsearch</li><li>BigQuery</li><li>S3</li></ul><p>Flow:</p><pre>App serving users fast → (buffered channel queue) → background goroutine writes logs</pre><p>🔍 Why buffered?</p><ul><li>Main goroutine doesn’t wait — just drops data into channel</li><li>Writer goroutine drains the queue at its own pace</li><li>Can absorb traffic spikes without slowing down business logic</li></ul><p>🧠 Think of it as:</p><blockquote><em>“Put logs in the box. Someone will process them later.”</em></blockquote><h3>✅ Another Unbuffered Channel Use Case (Internal at Google/Uber)</h3><h3>Goroutine orchestration during graceful shutdowns</h3><p>When a service receives SIGTERM (Kubernetes pod shutdown), goroutines must stop in a <strong>controlled order</strong>.</p><p>Example:</p><ul><li>Stop accepting new requests</li><li>Finish active requests</li><li>Flush metrics</li><li>Close DB connections</li></ul><p>An unbuffered channel is used to <strong>signal completion of each step</strong>, so shutdown is <strong>orderly and guaranteed</strong>.</p><h3>✅ Another Buffered Channel Use Case (Real at YouTube / Netflix)</h3><h3>Video transcoding workers</h3><ul><li>Thousands of video chunks need to be processed</li><li>Producer goroutine pushes work into a buffered channel (task queue)</li><li>Multiple worker goroutines pick up jobs in parallel</li><li>Smooth even when the input rate &gt; the processing rate temporarily</li></ul><p>Buffered channel acts like a <strong>mini internal job queue</strong>.</p><h3>✅ One-Line Summary to Remember</h3><ul><li><strong>Unbuffered channel = synchronous, no storage, sender waits.</strong></li><li><strong>Buffered channel = asynchronous, temporary storage, sender and receiver decoupled.</strong></li></ul><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b2fc36bcd2" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/buffered-vs-unbuffered-channels-in-go-with-code-example-45b2fc36bcd2">Buffered vs unbuffered channels in Go with code example</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Arrays vs Slices in Go: A Complete Guide (Beginner to Pro)]]></title>
            <link>https://medium.com/@koliv5936/arrays-vs-slices-in-go-a-complete-guide-beginner-to-pro-89f0623fe428?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f0623fe428</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[slice]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 17:50:00 GMT</pubDate>
            <atom:updated>2025-11-05T17:50:00.359Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re coming from languages like Java, Python, or C++, Go’s <em>arrays</em> and <em>slices</em> can feel confusing at first. They look similar… but behave very differently under the hood.</p><p>This article will walk you through <strong>how arrays and slices work in memory, how they behave when passed into functions, and how </strong><strong>append works internally, and when to use which, like a real Go engineer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*GswQEtOt8u3n_TS0A2r7Lg.png" /></figure><p>👉 <strong>Arrays own the data. Slices borrow it.</strong></p><h3>✅ 2. Memory Layout Explained</h3><h4>🔹 Array Memory</h4><pre>arr := [4]int{10, 20, 30, 40}<br><br>/*<br>Stack or Heap memory:<br>| 10 | 20 | 30 | 40 |<br>  ^ entire array belongs to &#39;arr&#39;<br>*/</pre><ul><li>Stored as one continuous block</li><li>Passing arr to function → copies entire block</li><li>Assignment b := arr → full copy again</li></ul><p>✅ Efficient when <strong>size is tiny &amp; known</strong><br> ❌ Expensive when large (full copy every time)</p><h4>🔹 Slice Memory</h4><p>A slice is <strong>not the data</strong>. It is a small struct:</p><pre>type slice struct {<br>    ptr *T   // pointer to backing array<br>    len int  // number of visible elements<br>    cap int  // capacity until reallocation<br>}</pre><p>Example:</p><pre>arr := [5]int{10, 20, 30, 40, 50}<br>slc := arr[1:4] // {20, 30, 40}</pre><pre>Backing Array:<br>| 10 | 20 | 30 | 40 | 50 |<br>       ↑<br>       ptr<br><br>arSlice Header (in stack):<br>ptr → &amp;arr[1]<br>len = 3<br>cap = 4  (from index 1 to end)<br><br></pre><p>✅ Only the 3-word header is copied<br> ✅ Multiple slices can share the same array<br> ⚠️ Modifying a slice modifies the array</p><h3>✅ 3. Copying, Passing, and Pointer Semantics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*W-u70MO--izGjENaRF6m2g.png" /></figure><p>Action Array Slice Passed to function Full copy Only header copied Modify inside function Original NOT changed Original changed &amp;arr Address of entire array — &amp;slc The address of slice header Data pointer is slc.ptr</p><p>Example:</p><pre>func modifyArray(a [3]int) { a[0] = 100 }<br>func modifySlice(s []int) { s[0] = 100 }</pre><pre>arr := [3]int{1, 2, 3}<br>slc := []int{1, 2, 3}</pre><pre>modifyArray(arr)<br>modifySlice(slc)</pre><pre>fmt.Println(arr) // [1 2 3]<br>fmt.Println(slc) // [100 2 3]</pre><h3>✅ 4. The Truth About append()</h3><p>Appending to a slice works in 2 modes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*NsWHosGcIfAU9st0TtHIRQ.png" /></figure><pre>s := []int{1, 2}<br>s = append(s, 3) // maybe reallocation</pre><p>Meaning:</p><ul><li>Sometimes append mutates <em>existing</em> array</li><li>Sometimes it moves data to <em>new</em> memory</li></ul><p>👉 That’s why pointer-based code should <strong>never assume append keeps the same array</strong>.</p><p>You can detect this:</p><pre>before := &amp;s[0]<br>s = append(s, 4)<br>after := &amp;s[0]<br>fmt.Println(before == after) // true OR false</pre><h3>✅ 5. Capacity Trick: Preventing Reallocation</h3><pre>s := make([]int, 0, 100)</pre><p>Pre-allocates capacity, avoids extra allocations, a <strong>major performance optimisation</strong> in Go.</p><h3>✅ 6. When to Use What</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*q8UM-tL7OjEuWH-RiuTO2g.png" /></figure><blockquote><strong><em>Arrays in Go are value types with fixed size and full-copy behavior. Slices are lightweight descriptors (pointer + len + cap) that reference underlying arrays and enable dynamic resizing with </em></strong><strong><em>append.</em></strong></blockquote><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f0623fe428" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building Your Own GPT-Powered App Using OpenAI APIs (with Example)]]></title>
            <link>https://medium.com/@koliv5936/building-your-own-gpt-powered-app-using-openai-apis-with-example-3cb363f9670c?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cb363f9670c</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 06:44:32 GMT</pubDate>
            <atom:updated>2025-07-02T06:44:32.210Z</atom:updated>
            <content:encoded><![CDATA[<p>GPT models have changed the way we interact with technology. From chatbots to auto-generators, businesses and developers are integrating GPT into their apps to deliver smarter user experiences. In this blog, you’ll learn <strong>how to build your own GPT-powered app using OpenAI APIs</strong>, with a <strong>hands-on example in Golang</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*56qBQeeNaDb1L12c" /><figcaption>Photo by <a href="https://unsplash.com/@boliviainteligente?utm_source=medium&amp;utm_medium=referral">BoliviaInteligente</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🧠 What Is GPT and Why Use OpenAI API?</h3><p><strong>GPT (Generative Pre-trained Transformer)</strong> is a language model developed by OpenAI. It can understand and generate human-like text, making it ideal for:</p><ul><li>Customer support bots</li><li>Email/sms/notification writers</li><li>Code assistants</li><li>SEO blog generators</li><li>Virtual tutors</li><li>AI agents for domain-specific tasks</li></ul><p>OpenAI provides a simple-to-use API that allows developers to integrate GPT models like gpt-3.5, gpt-4, or gpt-4o into their apps.</p><h3>🔑 How to Get OpenAI API Keys</h3><p>To use OpenAI’s GPT models, you need an API key. Here’s how to get one:</p><ol><li><strong>Sign Up at OpenAI</strong><br> Go to <a href="https://platform.openai.com/signup">https://platform.openai.com/signup</a> and sign up with your email, Google, or Microsoft account.</li><li><strong>Verify Email &amp; Phone</strong><br> OpenAI requires phone number verification before granting API access.</li><li><strong>Get Your API Key</strong></li></ol><ul><li>Visit <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a></li><li>Click <strong>“Create new secret key”</strong></li><li>Copy and save your key securely. You won’t be able to see it again later.</li></ul><p><strong>4. Billing (if needed)</strong><br> New accounts often get free credits. After that, usage is billed as per OpenAI’s pricing.</p><ul><li><strong>⚠️ Never expose your API key in public code repositories. Always store it securely using </strong><strong>.env files or secret managers.</strong></li></ul><h3>⚙️ Prerequisites</h3><ul><li>OpenAI account with API key</li><li>Golang installed (This example is for golang you can also use any language of your preference)</li><li>Basic understanding of REST APIs</li></ul><h3>🛠️ Step-by-Step: Building a GPT-powered CLI App in Golang</h3><p>Let’s build a <strong>CLI-based app</strong> where the user enters a prompt and gets a GPT response in the terminal.</p><h3>📦 Step 1: Install Required Packages</h3><p>You’ll need:</p><pre>go mod init gpt-cli-app<br>go get github.com/go-resty/resty/v2</pre><h3>🔑 Step 2: Set Your OpenAI API Key</h3><p>Create a .env file:</p><pre>OPENAI_API_KEY=your-api-key-here</pre><p>Load it using godotenv:</p><pre>go get github.com/joho/godotenv</pre><h3>💻 Step 3: Write the GPT Client Code</h3><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br><br> &quot;github.com/go-resty/resty/v2&quot;<br> &quot;github.com/joho/godotenv&quot;<br>)<br><br>const OPENAI_API_URL = &quot;https://api.openai.com/v1/chat/completions&quot;<br><br>type Message struct {<br> Role    string `json:&quot;role&quot;`<br> Content string `json:&quot;content&quot;`<br>}<br><br>type ChatRequest struct {<br> Model    string    `json:&quot;model&quot;`<br> Messages []Message `json:&quot;messages&quot;`<br>}<br><br>type ChatResponse struct {<br> Choices []struct {<br>  Message Message `json:&quot;message&quot;`<br> } `json:&quot;choices&quot;`<br>}<br><br>func main() {<br> err := godotenv.Load()<br> if err != nil {<br>  log.Fatal(&quot;Error loading .env file&quot;)<br> }<br><br> apiKey := os.Getenv(&quot;OPENAI_API_KEY&quot;)<br> if apiKey == &quot;&quot; {<br>  log.Fatal(&quot;OPENAI_API_KEY is not set&quot;)<br> }<br><br> var userPrompt string<br> fmt.Print(&quot;Enter your prompt: &quot;)<br> fmt.Scanln(&amp;userPrompt)<br><br> client := resty.New()<br><br> reqBody := ChatRequest{<br>  Model: &quot;gpt-3.5-turbo&quot;,<br>  Messages: []Message{<br>   {Role: &quot;user&quot;, Content: userPrompt},<br>  },<br> }<br><br> var result ChatResponse<br> resp, err := client.R().<br>  SetHeader(&quot;Content-Type&quot;, &quot;application/json&quot;).<br>  SetHeader(&quot;Authorization&quot;, &quot;Bearer &quot;+apiKey).<br>  SetBody(reqBody).<br>  SetResult(&amp;result).<br>  Post(OPENAI_API_URL)<br><br> if err != nil {<br>  log.Fatalf(&quot;API request failed: %v&quot;, err)<br> }<br><br> if resp.IsSuccess() {<br>  fmt.Println(&quot;GPT Response:&quot;)<br>  fmt.Println(result.Choices[0].Message.Content)<br> } else {<br>  fmt.Printf(&quot;Error: %s\n&quot;, resp.String())<br> }<br>}</pre><h3>🧪 Step 4: Run It</h3><pre>go run main.go</pre><p>Example Output:</p><pre>Enter your prompt: Give me a fun fact about space<br>GPT Response: Did you know that a day on Venus is longer than its year? Venus takes about 243 Earth days to rotate once, but only about 225 Earth days to orbit the Sun!</pre><h3>🧩 Where to Go From Here?</h3><p>You can now enhance your app:</p><ul><li>Add a web UI using React or HTML templates</li><li>Support multiple message history for conversational context</li><li>Use gpt-4 or gpt-4o for better accuracy</li><li>Add speech-to-text and text-to-speech support</li><li>Deploy on platforms like Heroku, Railway, or AWS Lambda</li></ul><h3>🛡️ Tips for Secure &amp; Efficient Usage</h3><ol><li><strong>Rate Limiting</strong>: Respect the API limits to avoid throttling</li><li><strong>Streaming Responses</strong>: For real-time apps, use OpenAI’s streaming support</li><li><strong>Prompt Engineering</strong>: Clear, specific prompts yield better results</li><li><strong>Avoid Hardcoding API Keys</strong>: Use env variables &amp; secrets manager</li><li><strong>Handle Failures</strong>: Add retry logic, timeouts, and error parsing</li></ol><h3>💡 Want to Go Further?</h3><p>Here are some app ideas to try:</p><ul><li>Blog post generator</li><li>Resume analyzer</li><li>Programming tutor CLI</li><li>AI feedback tool for writing</li><li>WhatsApp or Slack chatbot using GPT</li></ul><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cb363f9670c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ The Ultimate Guide to Learning Golang: Curated Resources, Communities, and Pro Tips]]></title>
            <link>https://blog.stackademic.com/the-ultimate-guide-to-learning-golang-curated-resources-communities-and-pro-tips-073f2c38c51c?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/073f2c38c51c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 18:58:54 GMT</pubDate>
            <atom:updated>2025-11-08T08:17:24.720Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether you’re just beginning your Go journey or you’re looking to sharpen your skills as a backend or systems developer, this guide curates some of the best resources shared by experienced Go developers. From fundamentals to advanced distributed systems, there’s something here for everyone. Bookmark it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ifpd_HtDiK9u6h68SZgNuA.png" /></figure><h3>🚀 Beginner-Friendly Resources</h3><h3>📗 Official Go Documentation</h3><ul><li><a href="https://golang.org/">The Go Programming Language</a></li><li><a href="https://golang.org/doc/">Documentation Hub</a></li></ul><blockquote><em>Start with the </em><a href="https://tour.golang.org/welcome/1"><em>Tour of Go</em></a><em> to grasp syntax and the language’s design philosophy.</em></blockquote><h3>🎥 Online Courses</h3><ul><li><a href="https://www.udemy.com/share/1013gw/"><strong>Todd McLeod’s Udemy Course</strong></a><br> Highly recommended for beginners. Covers everything from variables to concurrency.<br> <em>Tip: Build your own GitHub repo while following the course to reinforce learning.</em></li><li><a href="https://learn.microsoft.com/en-us/training/paths/go-first-steps/"><strong>Microsoft’s “Go: First Steps”</strong></a><br> A polished and well-structured official tutorial for Go, developed by Microsoft.</li></ul><h3>🛠️ Practice-Oriented Platforms</h3><ul><li><a href="https://exercism.io/tracks/go"><strong>Exercism Go Track</strong></a><br> Practice algorithms and data structures in Go. Free and peer-reviewed!</li><li><a href="https://gobyexample.com/"><strong>Go by Example</strong></a><br> A hands-on introduction to Go syntax and features via practical code snippets.</li></ul><h3>📚 Deep Dives &amp; Advanced Blogs</h3><h3>✍️ Official Blog Series</h3><ul><li><a href="https://blog.golang.org/">blog.golang.org</a></li><li><a href="https://blog.golang.org/strings">Strings</a></li><li><a href="https://blog.golang.org/slices-intro">Slices Intro</a></li><li><a href="https://blog.golang.org/slices">Slices: Usage and Internals</a></li></ul><h3>🧠 In-Depth Articles</h3><ul><li><a href="https://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go">How to Use Interfaces in Go — Jordan Orelli</a></li><li><a href="https://dave.cheney.net/2018/05/29/how-the-go-runtime-implements-maps-efficiently-without-generics">Go Runtime Map Internals — Dave Cheney</a></li><li><a href="https://eli.thegreenplace.net/2019/simple-go-project-layout-with-modules/">Simple Go Project Layout — Eli Bendersky</a></li><li><a href="https://itnext.io/structuring-a-production-grade-rest-api-in-golang-c0229b3feedc">Structuring a Production-Grade REST API in Golang</a></li><li><a href="https://research.swtch.com/interfaces">Go Interface Internals — Russ Cox</a></li></ul><h3>🧪 Distributed Systems &amp; Real-World Engineering</h3><ul><li><a href="https://pdos.csail.mit.edu/6.824/schedule.html"><strong>MIT’s 6.824: Distributed Systems Course</strong></a><br> One of the most intense but rewarding learning paths. Assignments are in Go.<br> <em>Tip: Try the </em><a href="https://pdos.csail.mit.edu/6.824/labs/lab-raft.html"><em>Raft assignment</em></a><em> — even if you don’t finish, the learning is gold.</em></li><li><strong>HashiCorp Open Source Projects</strong><br> Read code from tools like <a href="https://github.com/hashicorp/consul">Consul</a>, <a href="https://github.com/hashicorp/nomad">Nomad</a>, and <a href="https://github.com/hashicorp/terraform">Terraform</a> to see Go in action.</li></ul><h3>📘 Books Worth Owning</h3><ul><li><a href="https://www.amazon.com/Concurrency-Go-Tools-Techniques-Developers/dp/1491941197/">Concurrency in Go by Katherine Cox-Buday</a><br> Must-read for understanding goroutines, channels, and Go’s concurrency model.</li><li><a href="https://www.amazon.com/Kubernetes-Best-Practices-Blueprints-Applications/dp/1492056472">Kubernetes Best Practices</a><br> Ideal if you’re using Go in cloud-native or DevOps environments.</li><li><a href="https://www.amazon.com/dp/1492077216">Learning Go (O’Reilly)</a> — Also available on <a href="https://learning.oreilly.com/get-learning/?code=LEARNINGGO21">O’Reilly Online Learning</a></li></ul><h3>🌐 Communities &amp; Forums</h3><ul><li><a href="https://www.reddit.com/r/golang/"><strong>r/golang</strong></a> — Ask questions, share projects, and read experiences from Go developers around the world.</li><li><a href="https://invite.slack.golangbridge.org/"><strong>Gopher Slack</strong></a> — A great place to ask questions and get involved in real-time with other gophers.</li></ul><h3>💼 Golang Job Boards</h3><ul><li><a href="https://golang.cafe/">https://golang.cafe/</a></li><li><a href="https://www.golangprojects.com/">https://www.golangprojects.com/</a></li><li><a href="https://www.welovegolang.com/">https://www.welovegolang.com/</a></li></ul><h3>🎯 Final Thoughts</h3><p>Go is designed to be simple but powerful, especially in backend infrastructure, SRE, cloud-native applications, and distributed systems. If you’re a Python, Java, or C++ developer, switching to Go can be refreshingly efficient.</p><p>💡 <strong>Pro Tip</strong>: Build side projects while you learn. Clone tools, write simple REST APIs, experiment with goroutines. You’ll learn more by doing than reading.</p><p><strong>If this guide helped you, share it with fellow developers or teams starting with Go. Happy coding! 🧵<br>I will keep editing it if I find something more to add here….</strong></p><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=073f2c38c51c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-ultimate-guide-to-learning-golang-curated-resources-communities-and-pro-tips-073f2c38c51c">📘 The Ultimate Guide to Learning Golang: Curated Resources, Communities, and Pro Tips</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Swiggy Interview Experience: Software development engineer role]]></title>
            <link>https://medium.com/@koliv5936/my-swiggy-interview-experience-software-development-engineer-role-355507a7e874?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/355507a7e874</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[swiggy]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 15:02:52 GMT</pubDate>
            <atom:updated>2025-06-21T15:02:52.667Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently interviewed at <strong>Swiggy</strong> for a <strong>Golang Developer</strong> role. The entire process was structured, intense, and very backend-focused, including everything from DSA and concurrency to system design and real-world project discussions.</p><p>Here’s a detailed breakdown of each round, how I approached them, and tips that might help you crack your Swiggy interview!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ElWipgYxjI_URZuU" /><figcaption>Photo by <a href="https://unsplash.com/@vantaymedia?utm_source=medium&amp;utm_medium=referral">Van Tay Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>✅ Role: Backend Engineer (Golang)</h3><p><strong>Experience Level:</strong> 1–2 years<br> <strong>Stack Focus:</strong> Golang, DSA, System Design, Concurrency, Project Deep Dive</p><h3>🔹 Round 1: Online Coding Assessment</h3><p>This was a 7<strong>0-minute</strong> DSA-focused round conducted online. It contained:</p><ul><li><strong>3 DSA problems</strong> of medium difficulty (Leetcode-style)</li><li>All questions were to be solved in <strong>Golang only</strong></li><li>The platform evaluated both <strong>correctness</strong> and <strong>efficiency</strong></li></ul><h4>My Strategy:</h4><ul><li>Focused on solving all test cases, including edge cases</li><li>Prioritised clean and readable code over hacky tricks</li><li>Used maps, slices, and two-pointer techniques</li></ul><p>✅ <strong>Result:</strong> All 3 questions passed all test cases.</p><h3>🔹 Round 2: DSA + Golang Interview (Live Coding)</h3><p>This round was a <strong>video interview </strong>and was done on intervue platform.</p><h3>What was asked?</h3><ul><li>A <strong>DSA problem</strong> (medium-hard) that needed to be solved live</li><li>Must be submitted on <strong>Leetcode</strong> with <strong>all test cases passing</strong></li><li>Follow-up questions on:</li><li><strong>Golang internals</strong> (pointers, slices, maps)</li><li><strong>Goroutines and concurrency</strong></li><li><strong>WaitGroups</strong>, <strong>channels</strong>, and how Go handles parallelism</li></ul><h3>My Take:</h3><ul><li>Gave real-world examples of concurrency use (e.g., worker pool)</li><li>Walked through my thought process for DSA before coding</li></ul><p>✅ <strong>Result:</strong> Passed with full test cases and clean explanation.</p><h3>🔹 Round 3: Low-Level System Design (Cab Booking System)</h3><p>This round tested my ability to design scalable backend systems using Go.</p><h3>Problem:</h3><p>Design a system like <strong>Uber/Ola</strong> — a <strong>cab booking platform</strong> with:</p><ul><li>Cab registration</li><li>Location updates</li><li>Ride requests</li><li>Optimal cab assignment</li></ul><h3>What I Covered:</h3><ul><li>Entities: Cab, User, Ride, BookingManager</li><li>APIs: BookRide, UpdateLocation, EndRide</li><li>Used <strong>goroutines</strong> for simulating location updates</li></ul><blockquote><strong><em>Tip:</em></strong><em> It’s okay to make assumptions — just communicate them clearly.</em></blockquote><p>✅ <strong>Result:</strong> Good discussion. The interviewer was impressed with modularity and concurrency awareness.</p><h3>🔹 Round 4: Hiring Manager Round (Discussion-Based)</h3><p>This was more <strong>conversational and evaluative</strong>, focused on understanding my mindset and approach.</p><h3>Topics Covered:</h3><ul><li>Deep dive into <strong>past projects</strong> (scale, ownership, tech choices)</li><li>Asked how I design APIs (versioning, idempotency, security)</li><li>Asked how you would scale a system to handle more traffic</li><li>Microservices vs Monolith — pros, cons, when to use what</li><li>Collaboration with frontend/devops/product teams</li><li>Why do you want to leave your current organisation</li><li>What are your strengths and weaknesses based on your manager&#39;s review</li><li>How would you use your past experience at Swiggy to solve problems</li></ul><p>❎ <strong>Result:</strong> I got a rejection mail without any feedback, and even I tried to approach HR, they also didn’t provide any feedback on why I got rejected.</p><h3>📌 Key Takeaways from My Swiggy Interview</h3><ol><li><strong>Master Golang deeply</strong> — not just syntax, but internals like memory allocation, goroutines, maps, slices, etc.</li><li><strong>Solve Leetcode medium-level questions consistently</strong> — especially those involving maps, arrays, concurrency, and heaps.</li><li><strong>Practice LLD in Go</strong> — design cab, parking lot, elevator systems with interfaces and goroutines.</li><li><strong>Communicate your thought process</strong> — interviewers care how you approach a problem, not just whether you get the answer.</li><li><strong>Know your projects inside out</strong> — scale, trade-offs, architecture, deployment.</li></ol><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355507a7e874" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Uber Eats Paid the Price: Missing Idempotency Keys and What You Can Learn]]></title>
            <link>https://medium.com/@koliv5936/uber-eats-paid-the-price-missing-idempotency-keys-and-what-you-can-learn-e7b1a00fb6be?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b1a00fb6be</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[trending]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 11:32:36 GMT</pubDate>
            <atom:updated>2025-06-18T11:32:36.331Z</atom:updated>
            <content:encoded><![CDATA[<p>Without proper idempotency safeguards, even minor issues in your API design can lead to <strong>massive financial losses</strong> and <strong>user trust erosion</strong>.</p><p>Uber Eats India discovered this hard way during a cashback promo: users exploited a flaw in the order endpoint to receive <strong>multiple cashback payouts for a single order</strong>, simply by retrying the request. This blog unpacks what went wrong and how you can avoid it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Ckl_L8dOKC4KBqe" /><figcaption>Photo by <a href="https://unsplash.com/@cardmapr?utm_source=medium&amp;utm_medium=referral">CardMapr.nl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🍽️ The Uber Eats Cashback Backfire</h3><p><strong>What happened:</strong></p><ul><li>Uber Eats ran a promo offering cashback per order.</li><li>Slow network or UI lag led users to <strong>retry the POST /orders request</strong>.</li><li>Without an <strong>Idempotency-Key</strong>, each retry was treated as a <strong>new order</strong>.</li><li>Result: Duplicate orders, multiple cashback payouts, and huge losses (reports mention <strong>crores of rupees</strong>)</li></ul><h3>🧠 What Is Idempotency?</h3><p><strong>Idempotency</strong> ensures that <strong>repeated identical requests do not produce unintended side effects</strong>.</p><ul><li>Safe, idempotent methods: GET, PUT, DELETE</li><li>Non-idempotent by default: POST, PATCH</li><li>Example:<br> PUT /users/123 → always overwrites; safe to repeat<br> POST /orders → may create multiple orders if repeated</li></ul><h3>🛠️ How to Implement POST Idempotency</h3><h3>🎯 Step 1: Client Sends Unique Idempotency-Key</h3><p>Client generates a UUID and includes it in a header:</p><pre>POST /orders<br>Idempotency-Key: 5d3f…a5c9<br>Content-Type: application/json<br>{ …order data… }</pre><h3>🗃️ Step 2: Server Lookup</h3><ul><li>Check your store (Redis, DB, etc.) for the key:</li><li><strong>If found</strong> → return the stored response</li><li><strong>If not found</strong> → process the order, <strong>save the response</strong> with the key, and return it</li></ul><h3>⏳ Step 3: Expire and Validate</h3><ul><li>Set TTL (e.g. 24–48 hours) to clean old keys</li><li>Optionally, <strong>validate payload</strong>: reject if the same key has changed input</li></ul><h3>⚙️ Pseudocode:</h3><pre>if cache.Exists(key) {<br>    return cache.GetResponse(key)<br>}<br>resp := processOrder(req)<br>cache.Store(key, resp, TTL)<br>return resp</pre><h3>✅ Best Practices</h3><ul><li>Use UUIDs for keys and include them in headers</li><li>Scope keys by user ID &amp; endpoint to prevent collisions</li><li>Store responses temporarily (TTL-managed)</li><li>Validate that requests with the same key have matching payloads</li><li>Use shared storage (e.g., Redis) across your services</li><li>Apply to <strong>all POSTs with side effects</strong>: orders, payments, coupons, emails</li></ul><h3>🧠 Final Words</h3><p>Uber Eats’ incident shows that <strong>neglecting idempotency is costly</strong>. A simple guard, like an Idempotency-Key—can save your system from duplicated side effects, unexpected charges, and user frustration.</p><blockquote><em>Idempotency isn’t luxury — it’s a safety net.<br> Design every side-effectful </em><em>POST endpoint to be idempotent—and sleep easy.</em></blockquote><h3>🔜 Up Next in the Series</h3><ul><li>REST vs gRPC: Choosing the Right Protocol</li><li>Secure API Design: Auth, Headers &amp; HTTPS</li><li>Rate Limiting vs Throttling in Go Backends</li></ul><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b1a00fb6be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ REST vs gRPC: Which One to Use — External vs Internal APIs Explained]]></title>
            <link>https://medium.com/@koliv5936/rest-vs-grpc-which-one-to-use-external-vs-internal-apis-explained-47d5dac625d7?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/47d5dac625d7</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 05:16:36 GMT</pubDate>
            <atom:updated>2025-06-17T05:16:36.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔁 REST vs gRPC: Which One to Use — External vs Internal APIs Explained</h3><p>In modern backend systems, APIs are everywhere, but not all APIs are created equal. Two popular communication protocols dominate the field:</p><ul><li>🌐 <strong>REST</strong> (based on HTTP + JSON)</li><li>⚡ <strong>gRPC</strong> (based on HTTP/2 + Protocol Buffers)</li></ul><p>While both are powerful, <strong>the choice between REST and gRPC comes down to context</strong>. REST is commonly used for <strong>external</strong> communication, and gRPC shines in <strong>internal service-to-service</strong> interactions.</p><p>Let’s break this down simply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TAUe2zKdkCxgjCVY" /><figcaption>Photo by <a href="https://unsplash.com/@douglasamarelo?utm_source=medium&amp;utm_medium=referral">Douglas Lopes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🌐 What is REST?</h3><p><strong>REST (Representational State Transfer)</strong> is the most common style for web APIs. It uses standard HTTP methods (GET, POST, etc.) and sends data in <strong>human-readable JSON</strong> format.</p><h3>✅ REST is ideal for:</h3><ul><li>Frontend clients (web, mobile apps)</li><li>Third-party developers</li><li>Public APIs</li><li>Admin dashboards</li></ul><h3>✅ REST benefits:</h3><ul><li>Easy to test with tools like Postman, curl</li><li>Works well over HTTP/1.1</li><li>Simple, readable, and widely understood</li><li>Works directly in browsers and proxies</li></ul><p><strong>Example:</strong></p><pre>GET /users/123</pre><p>Returns:</p><pre>{<br>  &quot;id&quot;: &quot;123&quot;,<br>  &quot;name&quot;: &quot;Himanshu&quot;<br>}</pre><h3>⚡ What is gRPC?</h3><p><strong>gRPC</strong> is a high-performance, contract-first RPC (Remote Procedure Call) framework developed by Google. It uses <strong>Protocol Buffers (protobuf)</strong> to serialise data into a compact binary format and transmits over <strong>HTTP/2</strong>.</p><h3>✅ gRPC is ideal for:</h3><ul><li>Microservices inside your backend</li><li>Internal service-to-service calls</li><li>Low-latency and high-throughput systems</li></ul><h3>✅ gRPC benefits:</h3><ul><li>Strongly typed (code is auto-generated from .proto files)</li><li>Faster and more efficient than JSON</li><li>Bi-directional streaming support</li><li>Great for polyglot systems (Go, Java, Python, etc.)</li></ul><p><strong>Example:</strong></p><pre>rpc GetUser(GetUserRequest) returns (UserResponse);</pre><p>The generated code handles networking, serialisation, and error mapping for you.</p><h3>🧠 REST vs gRPC: External vs Internal Use Case</h3><p>Let’s clarify the typical use pattern:</p><h3>✅ Use REST for External APIs</h3><ul><li>Exposed to the public (web/mobile apps, third parties)</li><li>Needs a human-readable format</li><li>It should be easy to explore, debug, and secure</li></ul><blockquote><em>E.g., a payment gateway exposing APIs to clients</em></blockquote><h3>✅ Use gRPC for Internal APIs</h3><ul><li>Communication between internal microservices</li><li>Need strict contracts and performance</li><li>Behind a secure, trusted network</li></ul><blockquote><em>E.g., a billing service talking to a user service inside a Kubernetes cluster</em></blockquote><h3>🤜 REST vs gRPC — Summary</h3><p>Since Medium doesn’t support tables, here’s a side-by-side comparison:</p><p><strong>🔸 REST</strong></p><ul><li>Text-based (JSON)</li><li>Uses HTTP/1.1</li><li>Simple, human-readable</li><li>Browser and mobile-friendly</li><li>Best for external/public APIs</li></ul><p><strong>🔹 gRPC</strong></p><ul><li>Binary format (protobuf)</li><li>Uses HTTP/2</li><li>Strongly typed, faster</li><li>Supports streaming</li><li>Best for internal service-to-service calls</li></ul><h3>🔁 Can You Use Both?</h3><p>Yes, and many companies do.</p><p>🧩 Typical architecture:</p><pre>Frontend (React/Flutter)<br>      ↓ REST<br>   API Gateway<br>      ↓ gRPC<br>  Microservices (User, Auth, Billing)</pre><p>This hybrid approach offers:</p><ul><li>Developer-friendly external APIs (via REST)</li><li>Performance-optimised internal systems (via gRPC)</li></ul><h3>🧠 Final Thoughts</h3><p><strong>Use the right tool for the right job</strong>:</p><ul><li>REST for <strong>external</strong>, human-facing APIs</li><li>gRPC for <strong>internal</strong>, machine-to-machine efficiency</li></ul><h3>📚 Coming Up Next in the Series:</h3><ul><li>🔐 Secure API Design: Headers, HTTPS, and Token Strategies</li><li>🧱 REST API Best Practices (with Golang &amp; Gin)</li><li>🚦 Rate Limiting vs Throttling in API Backends</li></ul><p>💬 Found this useful? Drop a comment or follow for more backend content on Golang, microservices, and API architecture.</p><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47d5dac625d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How Travel Sites Show Hotels from Booking, Agoda & Airbnb (Adapter Pattern in Golang)]]></title>
            <link>https://medium.com/@koliv5936/how-travel-sites-show-hotels-from-booking-agoda-airbnb-adapter-pattern-in-golang-06742356cfd3?source=rss-548c05b183ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/06742356cfd3</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[adapter-pattern]]></category>
            <dc:creator><![CDATA[Himanshu Koli]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 05:21:31 GMT</pubDate>
            <atom:updated>2025-06-15T05:21:31.437Z</atom:updated>
            <content:encoded><![CDATA[<h3>👋 Introduction</h3><p>Imagine you’re building a travel site like <strong>Trivago</strong> or <strong>MakeMyTrip</strong>. You want to show hotels from:</p><ul><li>🏨 Booking.com</li><li>🏠 Airbnb</li><li>🏩 Agoda</li></ul><p>But here’s the challenge:</p><p>Each provider has its <strong>own API</strong>, its own <strong>data format</strong>, and its own way of <strong>returning hotels</strong>.</p><p>How do you <strong>unify</strong> them all without rewriting your whole system?</p><p>👉 You use the <strong>Adapter Pattern</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MDs49fbU-OCvuayK" /><figcaption>Photo by <a href="https://unsplash.com/@alesnesetril?utm_source=medium&amp;utm_medium=referral">Ales Nesetril</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🎯 What Is the Adapter Pattern?</h3><blockquote><strong><em>“Adapter Pattern converts the interface of a class into another interface clients expect.”</em></strong></blockquote><p>It’s like a power adapter — you plug in a U.S. charger into a European socket.</p><h3>✈️ Real-Life Analogy: Hotel Aggregator</h3><p>You ask your travel site:<br> “Show me hotels in Goa under ₹5000.”</p><p>It queries <strong>Booking.com</strong>, <strong>Agoda</strong>, and <strong>Airbnb</strong>, all with different data formats.</p><p>The <strong>Adapter Pattern</strong> standardises them into one format so your UI can display them consistently.</p><h3>👨‍💻 Golang Example: Adapter Pattern</h3><h4>🔧 Step 1: Define the Common Interface</h4><pre>type Hotel struct {<br>	Name     string<br>	Location string<br>	Price    int<br>}<br><br>type HotelProvider interface {<br>     Search(location string) []Hotel<br>}</pre><h4>🏨 Step 2: Define Provider APIs (with different formats)</h4><pre>type BookingHotel struct {<br>	HotelName string<br>	City      string<br>	Cost      int<br>}<br><br>type AgodaRoom struct {<br>         Name string<br>         Area string<br>         Rate int<br>}</pre><h4>🧩 Step 3: Create Adapters</h4><pre>type BookingAdapter struct{}<br><br>func (b *BookingAdapter) Search(location string) []Hotel {<br>   hotels := []BookingHotel{<br>      {&quot;Radisson&quot;, &quot;Goa&quot;, 4000},<br>      {&quot;Taj&quot;, &quot;Goa&quot;, 6000},<br>   }<br><br>   var result []Hotel<br><br>   for _, h := range hotels {<br>      if h.City == location {<br>         result = append(result, Hotel{h.HotelName, h.City, h.Cost})<br>      }<br>   }<br><br> return result<br>}<br><br>type AgodaAdapter struct{}<br><br>func (a *AgodaAdapter) Search(location string) []Hotel {<br>   rooms := []AgodaRoom{<br>      {&quot;Hyatt&quot;, &quot;Goa&quot;, 4500},<br>      {&quot;ITC&quot;, &quot;Delhi&quot;, 7000},<br>   }<br>   var result []Hotel<br><br>   for _, r := range rooms {<br>      if r.Area == location {<br>         result = append(result, Hotel{r.Name, r.Area, r.Rate})<br>      }<br>   }<br><br>   return result<br>}</pre><h4>🧪 Step 4: Use in main()</h4><pre>func main() {<br>	providers := []HotelProvider{<br>		&amp;BookingAdapter{},<br>		&amp;AgodaAdapter{},<br>	}<br>        location := &quot;Goa&quot;<br>        for _, p := range providers {<br>        hotels := p.Search(location)<br>        for _, h := range hotels {<br>           fmt.Printf(&quot;Hotel: %s | Location: %s | Price: ₹%d\n&quot;, h.Name, h.Location, h.Price)<br>        }<br>     }<br>}</pre><h4>✅ Output</h4><pre>Hotel: Radisson | Location: Goa | Price: ₹4000<br>Hotel: Hyatt | Location: Goa | Price: ₹4500</pre><h3>💡 Why Use the Adapter Pattern?</h3><ul><li>🔄 Standardise multiple incompatible interfaces</li><li>🧩 Cleanly plug in third-party APIs</li><li>🔌 Avoid modifying core business logic</li><li>♻️ Extend integrations without touching the consumer code</li></ul><h3>🛠️ Real-World Use Cases</h3><ul><li>🧳 Hotel or flight aggregators (Booking, Agoda, MakeMyTrip)</li><li>📦 Logging frameworks (Zap, Logrus, Stdlib)</li><li>🧬 Legacy system integrations</li><li>📂 File parsers (CSV, JSON, XML adapters)</li></ul><h3>📌 Summary</h3><p>The <strong>Adapter Pattern</strong> is your best friend when you need to <strong>integrate third-party systems</strong> or standardise <strong>inconsistent interfaces</strong>.</p><p>In Go, interfaces and composition make adapters clean and elegant.</p><h3>🔜 Next in the Series:</h3><p><strong>Part 8 →Proxy Pattern: How Netflix Handles Millions of Requests Without Overloading Their Servers</strong></p><p>💬 Got a system where the Adapter helped you? Share your story.<br> 🔁 Like this post? Repost or follow for the next one in the series!</p><h3>🙌 Thanks for reading!</h3><p>If you enjoyed this, follow me for more content on Go, system design, and backend interviews.<br>For any suggestions, please reach out at</p><p>📧 <strong>Email</strong>: koliv5936@gmail.com<br>💼 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/himanshu-koli-b26940201/">https://www.linkedin.com/in/himanshu-koli-b26940201/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06742356cfd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>