<?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 Muhammad Hasim on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Hasim on Medium]]></description>
        <link>https://medium.com/@notsocomplex?source=rss-2009fe82093e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*smL6aiyi3txqVLs1n8o2vQ.jpeg</url>
            <title>Stories by Muhammad Hasim on Medium</title>
            <link>https://medium.com/@notsocomplex?source=rss-2009fe82093e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:27:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@notsocomplex/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[Lunokhod1: A Memoir of Building a Telegram Bot Without a Budget]]></title>
            <link>https://notsocomplex.medium.com/lunokhod1-a-memoir-of-building-a-telegram-bot-without-a-budget-eabf51ba663d?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eabf51ba663d</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[memoir]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 13:48:42 GMT</pubDate>
            <atom:updated>2026-06-19T13:48:42.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jSXRW0WfLNxp7pEo" /><figcaption>Photo by <a href="https://unsplash.com/@dkfra19?utm_source=medium&amp;utm_medium=referral">Dimitri Karastelev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ahh, yes — here we are again. If you tuned in for a technical article, you will get it. Because in this article I will be going through my design choices and why I made them. But it’s not written around some technical topic, no sir or ma’am. This is a personal article — a memoir of an article — for it revolves around a personal Telegram bot I built called Lunokhod1.</p><p>I think it was the third or fourth time that broke the camel’s back. I had this cycle: I would go online, find a book I liked or a research paper I wanted to read on the go, browse through the world wide web, find it, download it to my PC. After that — if you’re like me — I would have to open up VLC on my iPhone, connect remotely to the web, drag and drop. Yes, I know VLC is a media player, and yes it does have a remote file transfer like Xender, and yes it was meant for mp3 and mp4 — but I tried PDF one day and it worked. Wow.</p><p>This cycle was tedious. Or was it? Or was I just itching to build something? Well, by the fourth time, I thought to myself: <em>“My God, this is too lengthy. I need a way of downloading a book on my phone and reading it on my phone.”</em> Yes, I know Kindle exists, and other book services. But bruv or sis, I don’t have the money for such subscriptions. And I know about shadow libraries, but ehhhh… this is my solution. Enjoy.</p><p>After sitting for a while, I looked down at my device and realised Telegram allows the creation of bots for free. Take that, Meta — charging me to create a bot for WhatsApp. Anyway, I thought: <em>“What if I could create a bot that could do the work for me?”</em> And that’s all it took. With this, I went crazy! I used Camera, Voice Record, and Text to solve this single problem:</p><blockquote>“Can I build a bot that can fetch a downloadable book for me, and save that book into my phone for reading?”</blockquote><p>With the story out of the way, let’s dive into how I built the bot.</p><h4>The Textual Input</h4><p>I began with the most obvious way of communicating using our device: via text. It was simple — I type in a book title and author, and it would search.</p><p>But a tiny voice inside me asked an important question:<strong> <em>“How do you usually type?”</em></strong></p><p>Well, it turns out, in the age of digitalisation and the autocorrect keyboard, I only think about what I want to say — I don’t care for the typos. That gave me an insight: <em>Don’t you think having yourself and folks stick to a rigid structure is a bit… analog?</em></p><p>The world is messy, is it not? If you make folks use a set structure to search (e.g., “Author Name, Book Name”), what happens then? What if one individual decides to type this way: <em>“I need a book by Dostoevsky (G.O.A.T) called Crime and Punishment?”</em> Or an African Queen decides to type her thoughts like this: <em>“I feel inspired right now. Due to my inspiration, I would love to read the book Native Son by Richard Wright — I need to understand the power of racism from a sociological perspective.”</em></p><p>This voice, I dare say, set the bar high for me. That would be so… if we did not exist in a world where LLMs have evolved.</p><p>With this, I introduce to you, my esteemed reader: the Intelligencia Layer.</p><p>The Intelligencia Layer</p><p>Ah! Yes — Intelligencia. Or intelligence. What is this? What constitutes as intelligence?</p><p>For my solution, if it can correctly identify the author and the title of the book from the user prompt, create a structure for me (JSON), and send it back — this is intelligence. <em>Muah!</em> And that’s what I did.</p><p>By utilizing OpenRouter (shout out!), I was able to extract the user input from the text box. (I would show this, but this is not a Telegram bot tutorial — sorry.)</p><p>Once I retrieved not just the user text but the whole struct that made up the request made by the user — why? It turns out for every message sent through the Telegram server, it also provides a way of replying to the user back. This is important, because when we have to tell the user of the progress of their request and return the book for download, without this, it would be a “shoot and forget” — no way of returning back to the user. Well, there is… but this would break the immersion. We could send the book to their email that we collected at the start of the process, but again, that would break the immersion.</p><p>So, with the payload retrieved, I extracted the user message from the struct field. I used Go to build the bot. Once extracted, I passed the message along to the OpenRouter API, where I fused it with the prompt I had previously constructed.</p><p>Once all of this is sent off, the response is a structured JSON with multiple fields — the most important being the extracted, corrected author and book title.</p><p><strong><em>What about hallucinations?</em></strong> It turns out a prompt is like a guardrail — when done properly and strictly, you can reduce hallucinations. Is this a surefire solution? Hecks nah! Does it work for now? Hecks ya!</p><p>So with that out of the way, I had my Intelligencia ready and working.</p><p>Next — I got bored and thought: <em>Wait, what if I don’t feel like typing?</em> With that, we move into the next modal: the voice!</p><h4>The Voice Input</h4><p>Voice — as old as man is — might be the most natural extension of man’s means of saying “I exist”, even before he begins to write and read. Strange I did not think of this first.</p><p>Telegram provides a voice feature for bots. A bot: voice feature, text feature, camera feature — all for free! Thank you, Telegram. Meta? <em>Shake my head.</em></p><p>It was a simple design, a simple thought: <em>What if I was lazy? What if I was on the go? What if I was not in the mood to type?</em> Well, simple — just press record and speak your heart’s desire of what book you wanted. This would then be passed over to the speech engine, where I utilized a Speech‑to‑Text layer. If you don’t know, this is where what you say is transformed into textual form.</p><p>Once this is done and I have the text — remember the Intelligencia layer? <em>Muah!</em> — I pass the text over to it, and <em>voilà</em>, I have my JSON returned with the right information.</p><p>Shout out to DeepGram! They gave me free credits — and a lot of it. This is not sponsored. Hold on, why do companies not sponsor articles like they do videos? Anyway, they gave me credits for FREE, and I did not have to provide a credit card. Above all, by God, I don’t know how they do this, but <em>DAMN!</em> DeepGram is blazing fast — at least its Speech‑to‑Text is.</p><p>So far, so good, right? I have already implemented text input and voice input, and thus far I have spent $0 to make this happen. But alas, I got bored. I know I could have just connected what I had to the book API, but I just felt unsatisfied.</p><p>Then I looked to my right. I saw a book sitting on my table. And I knew what was to come next. It was Camera time.</p><h4>The Camera Input</h4><p>This one was straightforward, really. The question: <strong><em>What if I was at a bookshop, a friend’s place, or a library and I needed the digital form of that book?</em></strong></p><p>For this, I made use of Google Gemini — its image‑focused model. Using the power of prompting, I was able to tell it what I wanted and how I wanted it. Simple, right? Once I had the extracted text, I passed it over to the Intelligencia layer, and it did its thing.</p><p>Yes, I could have used the same prompt for Intelligencia, but I made it for OCR (in case you don’t know, OCR is a technique in computer vision where we strive to extract characters from text). But the separation of concerns was screaming at me not to dare, so I decided to break it out like that.</p><p>Will this increase my token cost and will I be paying for three models? Yes. BUT!!! Is it currently running on FREE!!!? YES!!!</p><p>With that, I had come to the end. I was satisfied. I was ready to move over to the next part: the Book API!</p><h4>The Book API</h4><p>This part was a nightmare! It turns out, Anna’s Archive, Zlibrary, and NO FREAKING SHADOW LIBRARY had a publicly known API. I had two options: download Anna’s Archive <em>terabytes</em> of PDFs, or give up! I kid you not, dear reader — this part took me days. Searching, looking for hidden clues on their websites, reading through forums, only to come up empty. I was sad. I thought I was going to solve this personal issue. I was so excited I even screen recorded myself interacting with the bot on my phone (which I shall share in the article).</p><p>But I JUST could not give up. For spiritual reasons, of course.</p><p>I continued this fruitless digging until I was blessed with <a href="https://gutendex.com/">https://gutendex.com/</a> (a friendlier way of interacting with Project Gutenberg). Roll with this? Hecks nah! Here’s why: Project Gutenberg is certainly FIRE, but they lack a lot of modern books. Some books I needed were written in the 20th century, not in past centuries (pardon my ignorance if I am wrong about this).</p><p>Thus the search continued — but at least my options had tripled:</p><ul><li><strong>(A)</strong> Download terabytes of PDFs</li><li><strong>(B)</strong> GIVE UP!</li><li><strong>(C)</strong> Use Gutendex API (FREE)</li></ul><p>But I continued my search until I came across something I never knew had an API: The Internet Archive. And with this, I met my match. It was what I sought — until responses returned a 401 error. It turned out some books required me to log in to access them. DAMMIT!</p><p>And let me use this opportunity to say this: if you ever decide to use the Internet Archive API, you are in for one hell of a ride. Make sure to keep a brew of patience right beside you, especially if you choose to use their REST API over their library. I would have used it, but I really wanted to stick to Go. Their library existed only for Python. I did think of creating a microservice architecture where the Python server would be in charge of interacting with the Internet Archive API, and through that service I would expose an API that my Go code would consume.</p><p><strong>But NAH!!!!</strong></p><p>I stuck to it. I stuck to using Go — and I went through hell for it. In retrospect, I am really skipping over a lot of things. If I had filmed myself during this project, you would have seen it all: the sheer sadness, anger. For the first time in my building life, I smacked my table and keyboard multiple times, as if this would solve the issue.</p><p>Anyway, long story short, we got life off the Internet Archive API working. The solution for the 401 was to query with a collection that excluded the walled‑up stuff.</p><p>With the multiple modalities now in place — Camera, Voice, Text — and the Internet Archive API in place, all I had to do was pass in the structured JSON retrieved from the Intelligencia layer, and the request would be performed and the books retrieved. Well, I’m over‑simplifying it, but at a higher level… it was DONE!, All i had to do now was tie in the response back to the user, and wolah! they had a book on their very device, a video should make this more clear.</p><blockquote><em>Before you watch, a small note: I’ve included raw screen recordings — not polished, not edited, not rehearsed. You’ll see the times the bot didn’t work, the errors, the crashes, and the messy reality of building. I chose to show this because that’s the truth of building. If you’re here for a perfect demo, this isn’t it. If you’re here to see what it actually looks like when someone builds with no budget and a lot of hope — this is for you. In no particular order.</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtgOjdvlzT1s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtgOjdvlzT1s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtgOjdvlzT1s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef978ce6a9b99e852221559cffe6afc5/href">https://medium.com/media/ef978ce6a9b99e852221559cffe6afc5/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWVSVeAmYza0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWVSVeAmYza0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWVSVeAmYza0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdf4b61cfb329fc0bb609777756ca0d3/href">https://medium.com/media/cdf4b61cfb329fc0bb609777756ca0d3/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNdh2Gugiwec%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNdh2Gugiwec&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNdh2Gugiwec%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb1b4323186632b59cbe2a6f91cc6964/href">https://medium.com/media/cb1b4323186632b59cbe2a6f91cc6964/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzK48l2-tQTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzK48l2-tQTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzK48l2-tQTE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/92590a6781886530361694c8440164ca/href">https://medium.com/media/92590a6781886530361694c8440164ca/href</a></iframe><h4>Cache Layer</h4><p>Free is nice and all, but it comes with a catch — and that catch is rate limiting. You don’t want to stick your hands into the cookie jar too often. Have some decency — others need them too.</p><p>I decided to include a cache layer — or like I call it, Cachie Layer.</p><p>The cache layer exists to solve a commonality amongst humans: we are often repetitive in our taste. This can be seen across the globe. My love for Russian writers is easily shared by someone in Japan. This is why the cache layer exists.</p><p>Say I use the bot to find the book <em>The Overcoat</em> by Nikolai Vasil’evich Gogol. The bot does its thing and gets me the book — that’s one hit to the Internet Archive API. This is OK. Someone in Japan does the same thing, same book — that’s two hits for the same book. Now let’s scale this up: how about 5,000 hits for the same book? That’s 5,000+ requests interpreted as individual requests to the Internet Archive API.</p><p>What if we had a way of saying, <em>“Hey, don’t bother Internet Archive — I have what you want right here.”</em> That’s what caching solves. Over time, it should build up to include every query made until we become our own Internet Archive — or until we run out of the free tier plan (lol).</p><p>I decided to use a key‑value database for this one. I chose Redis. I would have a key and a value pointing to the actual book (a download link, or a link to the book in my Persistencia layer — persistence layer). For the key, I looked at what was the most constant thing about a book: its ISBN, its writer, and the book title. But I had no way of getting the ISBN, so I stuck to the title and the author. By combining these two strings together and passing them through a technique called fingerprinting, I was able to produce a fingerprint that can only be recreated when the exact combination of author name and book title are combined.</p><p>Since I pass the user input through the Intelligencia Layer, the chances of consistent output are much higher — a solution to man’s creative and rebellious nature, I guess. Because all user requests for a book pass through the same prompt, the chances of producing the same consistent output are much higher compared to not using this solution.</p><p>With this in place, the value can be one of two things:</p><ul><li><strong>A</strong>. A link to the direct download of the book</li><li><strong>B</strong>. A link to my copy of the book in storage (S3 bucket)</li></ul><p>This part I have yet to decide. I might have both as a fallback, in case the book URL stops working for some strange reason (takedown, user deletes the book from Internet Archive).</p><p>Yes, I see it. For every query, I have to run it through my fingerprinting function. How expensive is this? That’s something I have yet to consider at all. But yes — until I find a better workaround, for now, every query is passed through the fingerprinting step.</p><p>Once the fingerprint is generated, we pass it into the function responsible for retrieving the information from Redis. If nothing is found, only then do we proceed to query the Book API.</p><p>Once that’s done, the next step is to concurrently run two functions:</p><ol><li>One that sends the response back to the user.</li><li>The other that persists into the cache layer the key (fingerprint) and the link for downloading the book.</li></ol><p>Fingerprinting adds negligible CPU overhead (microseconds per request). The real latency is in network calls (Redis, API). So for now, it’s fine. If I ever hit massive scale, I can pre‑compute fingerprints offline or use a simpler key scheme. <strong>IF</strong></p><h4>The Persistencia Layer(Persistence Layer)</h4><p>This serves as the storage layer, it serves, two purposes, 1. To Grow my own shadow Library, 2. To have a fallback, but the sad part about it is, i cannot implemente it yet, not for technical reasons, NO, rather financial reason, so for now, as of writing this article has not been implemented, but the system design for it i shall included below.</p><p>This bot isn’t perfect. The cache layer still needs a proper Redis deployment(<strong>Done</strong>), the Persistencia layer is a dream waiting for funding, and the Internet Archive API still throws 401s if you blink wrong. But it works. It saves me time. And it taught me more than any tutorial ever could.</p><p>If you’ve read this far — thank you. This wasn’t a tutorial on how to build a bot. It was a memoir of why I built one. My hope is that it inspires you to build something too — even if it’s messy, even if it’s incomplete. The act of building is the point and inspired you to use mine 😂. No Seriously! 😂</p><p>Share this with someone who needs to hear that you can build without a budget. And if you’ve built something similar, drop a comment. I’d love to see it.</p><p>If you want to try the bot, reach out to me here — [@LunarKhord] on Telegram. Why? Well, as of writing this article, I have yet to deploy it. But in the future, I should edit this out to include a direct link to the bot.</p><p>And if you’re building something and need a second pair of eyes — I’m always around.</p><h4>System Design Hand Drawn Diagrams.</h4><p>Please pardon the drawing, i am too Jean-Michel Basquiat right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX3LxZ2MsJkoEkVchGfx6g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7a88aJZQwTHLS4krNKrvw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gV8rGHkeuNMAsjB7Uo8Grg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjGEnUywRlwKnZZ_Y2K9ug.jpeg" /></figure><h4>Conclusion</h4><p>And that’s it. That’s the story of how I built Lunokhod1 — a Telegram bot that started as a frustration, became a challenge, and turned into a teacher.</p><p><strong>The bot isn’t perfect.</strong></p><ul><li>The Persistencia layer is a dream waiting for funding.</li><li>The Internet Archive API still throws 401s if you blink wrong.</li><li>It’s not even deployed yet.</li></ul><p>But it works. It saves me time. And it taught me more than any tutorial ever could.</p><h4><strong>What I Learned That You Can Too</strong></h4><p>1.<strong>Start with a problem you actually have</strong> — not a trending idea, not a money-making scheme. Just something that annoys you every day.</p><p>2.<strong>Build in layers</strong> — Intelligencia, Cacheia, Persistencia — each one does one thing. That’s the cleanest way to build.</p><p>3.<strong>Don’t wait for a budget</strong> — I built this with free APIs, free credits, and a phone that was already in my pocket. The tools are there. Use them.</p><p>4.<strong>Show the struggle</strong> — I included raw screen recordings, errors, and crashes. Because that’s the truth of building. And the truth is worth more than a polished demo.</p><p>5.<strong>Keep going</strong> — Even when the 401s hit, even when you want to smack your keyboard, even when you think no one will ever use it — keep going. The act of building is the point.</p><h4>A Final Word</h4><p>If you’ve read this far — thank you.</p><p>This wasn’t a tutorial on how to build a bot. It was a memoir of why I built one. My hope is that it inspires you to build something too — even if it’s messy, even if it’s incomplete. The act of building is the point.</p><blockquote>”If you have built castles in the air, your work need not be lost; that is where they should be. Now put the foundations under them.”— Henry David Thoreau</blockquote><p>Share this with someone who needs to hear that you can build without a budget. And if you’ve built something similar, drop a comment. I’d love to see it.</p><h4>Try It Yourself</h4><p>If you want to try the bot, reach out to me here — [<strong>@LunarKhord</strong>] on Telegram.</p><p>Why? Well, as of writing this article, I have yet to deploy it. But in the future, I should edit this out to include a direct link to the bot.</p><p>And if you’re building something and need a second pair of eyes — I’m always around.</p><h4>Thank You</h4><p>Thank you for reading, for staying, for caring about the story as much as the code.</p><p>This bot is not just a tool — it’s a testament to what happens when frustration meets curiosity, and when curiosity meets Allah’s permission.</p><p>Bismillah.</p><p><strong>What next ? Well, i am thinking of building a bot for just audiobooks.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eabf51ba663d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes from Concurrency Patterns in Go]]></title>
            <link>https://notsocomplex.medium.com/notes-from-concurrency-patterns-in-go-8cfc55b44e24?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cfc55b44e24</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 11:55:51 GMT</pubDate>
            <atom:updated>2026-06-03T11:55:51.470Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrency Patterns in Go: Beginners Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P1m7DQCCf2GnhlAH" /><figcaption>Photo by <a href="https://unsplash.com/@metriics?utm_source=medium&amp;utm_medium=referral">Stephane Gagnon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Welcome — as promised, concurrency patterns in Go. Is this weird, what I just said? Well, if you’re confused, that probably means you’re a first‑time reader. In my previous article, I promised I would be writing on this topic. And as usual, it got too long, so I have to break it down into parts.</p><p>What is contained in this current article is by no means the full thing — but I do plan on covering them all to the best of my ability. As always, in writing this article, my intention was to benefit myself and to benefit you, the reader. I hope the purpose for clicking on this article is fulfilled by the time you finish reading, and that you leave far more knowledgeable than when you first came.</p><p>As always, I am <strong>very</strong> open to suggestions. Where can I improve? What should I teach next? What are my weaknesses? If you have any creative and constructive criticism, please don’t hesitate to comment it below.</p><p>And without any further ado — oh, one last thing. Please, if this article is helpful, continue the cycle and pass this on to someone else in need. Not necessarily my article — write yours, make videos, whatever. Just benefit the rest of mankind. Because teaching and knowledge sharing is a form of legacy, a form of immortality. Plus, that’s why the internet was made in the first place.</p><p>Ahhh, that’s it. Bismillah. I hope you benefit, insha’Allah.</p><p>Now, let’s dive into the first pattern: <strong>confinement</strong>.</p><p><strong>But before that — what is a design pattern? I’m glad you asked — Or Didn’t.</strong></p><h4>What Is a Design Pattern?</h4><p>A design pattern is a reusable, general solution to a commonly occurring problem in software design. It’s not a finished piece of code you can copy and paste — it’s a template or a description of how to solve a problem that you can adapt to your own situation.</p><p>Think of it like a recipe for a dish. You know the ingredients (channels, goroutines, mutexes) and you know the steps, but the recipe (the pattern) shows you how to combine them in a proven way so you don’t burn the kitchen down.</p><h4>Design patterns give you:</h4><ul><li>A shared vocabulary — “let’s use a fan‑out pattern here” is shorter than explaining the whole thing.</li><li>Proven solutions — other people have already made the mistakes so you don’t have to.</li><li>A way to reason about complex systems — they raise your level of thinking from “which lock?” to “which pattern?”</li></ul><p>In Go concurrency, we have several well‑known patterns: confinement, for‑select‑done, pipelines, fan‑out/fan‑in, worker pools, cancellation, heartbeats, and more. This article will introduce the first few. The others will come, insha’Allah.</p><p>Now, back to the first pattern: <strong>confinement</strong>.</p><h4>Confinement</h4><p>When working with concurrent code, there are a few different options for safe operations. Some of them are:</p><ul><li>Synchronization primitives for sharing memory (e.g., sync.Mutex)</li><li>Synchronization via communication (e.g., channels)</li></ul><p>However, there are a couple of other options that are implicitly safe within multiple concurrent processes:</p><ul><li>Immutable data</li><li>Data protected by <strong>confinement</strong></li></ul><p>Confinement is the simple yet powerful idea of ensuring information is only ever available from one concurrent process. When this is achieved, a concurrent program is implicitly safe, and no synchronization is needed. There are two kinds of confinement possible: <strong>adhoc</strong> and <strong>lexical</strong>.</p><p>From what I make of confinement, it seems to be solving a problem <strong>sync.Mutex</strong> already does, but without the need for locking. This had me thinking: if mutex does exist and it performs its purpose rather excellently, then why the need for the confinement pattern? Well, I did a little bit of digging, and my findings are quite interesting to me — maybe they will be to you too.</p><h4>1. Locks cause contention and kill performance</h4><p>It turns out, a solution can easily introduce new problems. A mutex can easily become a bottleneck in your application. Here’s how: when multiple goroutines contend for the same mutex, they serialize — only one proceeds, the rest block (wait). This can turn a concurrent program into effectively a sequential one. Worse, if the lock takes a long time to finish with that piece of information, we in effect have turned something meant to move fast into moving slow while using principles meant to make processing fast and safe.</p><p>With confinement, we introduce <strong>no waiting, no blocking</strong>. Each goroutine works on its own private data or a read‑only copy. Throughput stays high.</p><h4>2. Locks are prone to deadlocks</h4><p>Deadlocks occur when a goroutine holds locks and waits for another (e.g., lock A then B vs lock B then A). Debugging deadlocks can be notoriously hard. But with confinement, since there are no locks, there are no deadlocks introduced. The single‑writer pattern eliminates this class of bug completely.</p><h4>3. Locks make reasoning about code harder</h4><p>With locks, you must mentally track throughout your code where any variable can be accessed and ensure they use the same mutex. It’s easy to miss one, resulting in an unintended data race or a hold of a lock that brings the idea of concurrency to a grand halt.</p><p>With confinement, the data owner is explicitly stated and known. If you hold a reference to a value, you know only you can write to it. Readers of your code can see a frozen copy or immutable snapshot.</p><p>The above downsides to locks are not to downplay them — <strong>NO</strong>, they have their exceptional playtime and usage.</p><h4>So why ever use locks?</h4><p>Because confinement isn’t always practical:</p><ul><li><strong>Global caches / shared config</strong> — many goroutines need to read and occasionally write the same data. Writing a copy for every reader would be wasteful.</li><li><strong>Frequently updated shared state</strong> — passing copies of a large struct through a channel (to the owner goroutine) is slower than updating it in‑place with a lock.</li><li><strong>Simple coordination</strong> — sometimes a tiny mutex is easier to understand than redesigning your data flow.</li></ul><p><strong>Bottom line:</strong> Confinement trades flexibility for safety and performance. Locks are a general‑purpose tool that handle any sharing pattern, but they pay the price of contention, deadlock risk, and mental overhead. Confinement sidesteps all of that by design — you avoid locks by never sharing writable data across goroutines in the first place. That’s why it’s considered a powerful concurrency pattern, not just a theoretical exercise.</p><p>My conclusion is that it all boils down to your solution. If you understand your solution — from what data you expect, all the way down to how it should be accessed (system design included) — then it becomes easy to know what would fit into your solution. Anyway, enough of the digression.</p><h4>The Two Kinds of Confinement</h4><p>Let’s take a look at the two possible confinements:</p><ul><li>Adhoc confinement</li><li>Lexical confinement</li></ul><h4>Adhoc confinement</h4><p>Adhoc confinement is the usage of confinement in your codebase by way of convention — whether this convention is community‑based, the group you work within, or the codebase you work within.</p><p>According to Katherine Cox‑Buday, and I quote: <strong>“In my opinion, sticking to convention is difficult to achieve on projects of any size unless you have tools to perform static analysis on your code every time someone commits some code.”</strong><br>To summarise the reason for the above statement (with which I agree), she cites that during deadlines, team members can easily forget convention and alter existing code to suit their coding styles. This in turn becomes counter‑adhoc. My opinion is that I do agree with her. As the same author says: “<strong>This is why I prefer lexical confinement: it wields the compiler to enforce the confinement.”</strong></p><h4>Lexical confinement</h4><p>Lexical confinement involves using lexical scope to expose only the correct data and concurrency primitives for multiple concurrent processes to use.</p><p>Lexical confinement is a more robust, compiler‑enforced approach that uses Go’s lexical scope to confine data. It often relies on channels to manage data ownership. A common example is a <strong>chanOwner</strong> function that instantiates a channel and writes to it inside its own goroutine, returning a read‑only <strong>&lt;-chan int</strong> to consumers. This design ensures that only the owner goroutine can ever write to the channel, making data access patterns clear and correct by design.</p><h4>Lexical Confinement — Code Example</h4><p>Here’s a concrete example of lexical confinement in action:</p><pre>package main<br>import &quot;fmt&quot;<br>// chanOwner returns a read‑only channel of integers.<br>// The channel and the write goroutine are confined inside this function.<br>func chanOwner() &lt;-chan int {<br> ch := make(chan int) // bidirectional, but never exposed outside<br>go func() {<br> defer close(ch) // owner also closes the channel<br> for i := 0; i &lt; 5; i++ {<br> ch &lt;- i<br> }<br> }()<br>return ch // only the read‑only view is returned<br>}<br>func main() {<br> stream := chanOwner() // stream is &lt;-chan int<br>// The main goroutine can only read, never write.<br> for v := range stream {<br> fmt.Println(&quot;Received:&quot;, v)<br> }<br> // Cannot write to stream: stream &lt;- 10 would be a compile error.<br>}</pre><p><strong>Output:</strong></p><pre>Received: 0<br>Received: 1<br>Received: 2<br>Received: 3<br>Received: 4</pre><h4>Why this is lexical confinement</h4><ul><li>The <strong>write side</strong> of the channel (ch) is only accessible inside the anonymous goroutine that writes to it.</li><li>The <strong>read side</strong>(&lt;-chan int) is the only thing returned to the outside world.The compiler <strong>enforces</strong> that no other goroutine can write to that channel. Attempting to do so causes a compile error, not a runtime race.</li></ul><p>This pattern is a classic example of lexical confinement: the channel’s ownership and write access are lexically scoped to the <strong>chanOwner</strong> function, making data races impossible by design.</p><h4>The for‑select‑done Loop Pattern</h4><p>The <strong>for‑select‑done</strong> pattern is a powerful design pattern that combines these three Go constructs to create a concurrent, cancellable worker.</p><p>This pattern serves as a solution to a goroutine problem: <strong>goroutine leaks</strong>. Since goroutines are really lightweight to create, they aren’t garbage collected. This is fine for a small program on your terminal, but when you have the messy world to contend with, it becomes a nightmare. The once small footprint goroutines begin to pile up, leading to a goroutine leak. This is where the <strong>for‑select‑done</strong> pattern comes in clutch — it gives you a standard, reliable way to tell a goroutine, <strong>“Hey, I need to stop.” </strong>Why does this matter?</p><p>Well, I’m glad you asked (or did not ask — either way). Here’s why.</p><p>It turns out we have three possible ways of terminating a goroutine:</p><p>1. When the goroutine has completed its work<br>2. When the goroutine cannot continue its work due to an unrecoverable error<br>3. When the goroutine is <strong>told to stop </strong>(and that’s what we’re doing explicitly)</p><p>We get 1 and 2 right out of the box. The third one we have to work for(Dammit!). Ladies and gentlemen: the <strong>for‑select‑done</strong>.</p><ul><li><strong>The for loop</strong> — always in an infinite state, it provides the continuous engine, allowing the goroutine to handle multiple events over its lifetime.</li><li><strong>The select statement</strong> — this is the magical multi‑way multiplexer. It allows the goroutine to block and wait for any of its channel operations to be ready, simultaneously (I wrote an article that covered <strong>select</strong> — do check it out), executing the logic for the first one that becomes available.</li><li><strong>The</strong> <strong>done</strong> <strong>channel </strong>— this is your cancellation signal. You pass this channel (usually a <strong>&lt;-chan struct{}</strong>) into the goroutine. By convention, closing the <strong>done</strong> channel or sending a value on it signals that it’s time to clean up and exit.</li></ul><h4>Code example of for‑select‑done</h4><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br>// This function runs a goroutine,<br>// processing integers until it&#39;s told to stop<br>func process(jobChan &lt;-chan int, done &lt;-chan bool) {<br> fmt.Println(&quot;[Worker] started. Waiting for jobs or exit signal.&quot;)<br> for {<br> select {<br> case n := &lt;-jobChan:<br> // job received from the main channel<br> fmt.Printf(&quot;[Worker] Processed job: %d\n&quot;, n)<br> case &lt;-done:<br> // Exit signal received. Clean up and return<br> fmt.Println(&quot;[Worker] Received exit signal. Shutting Down!&quot;)<br> return<br> }<br> }<br>}<br>func main() {<br> jobChan := make(chan int)<br> done := make(chan bool)<br>// Start the worker goroutine<br> go process(jobChan, done)<br>// Send some jobs to the worker<br> for i := 0; i &lt;= 5; i++ {<br> jobChan &lt;- i<br> // Simulate some long running process<br> time.Sleep(500 * time.Millisecond)<br> }<br>// Tell the worker to stop<br> fmt.Println(&quot;[Main] Sending exit signal. STOP&quot;)<br> done &lt;- true<br>}</pre><p><strong>Output:</strong></p><pre>[Worker] started. Waiting for jobs or exit signal.<br>[Worker] Processed job: 0<br>[Worker] Processed job: 1<br>[Worker] Processed job: 2<br>[Worker] Processed job: 3<br>[Worker] Processed job: 4<br>[Worker] Processed job: 5<br>[Main] Sending exit signal. STOP</pre><blockquote>Now that we know a goroutine can leak, and we’ve redesigned our code to include the <strong>for‑select‑done</strong> pattern that mitigates the chances of a goroutine leak, <strong>here’s a convention</strong>: <br>“If a goroutine is responsible for creating a goroutine (parent), it is also responsible for ensuring it can stop the goroutine it created (child).”</blockquote><h4>Pipelines</h4><p>A pipeline is a tool that enables you, the programmer, to process streams or batched data. A pipeline is nothing more than a series of things that take data in, perform some operation on the data, and pass that altered data back out or into another pipeline in the chain. Each stage of the pipeline is called exactly that — a <strong>stage</strong>.</p><p>For example, a pipeline can have a stage where a user feeds in a document — that’s one pipeline stage. The fed PDF has its text extracted and cleaned — that’s another stage. The final stage vectorizes the text and stores it in a vector database — that’s a third stage. In total, three pipeline stages. It can be more; it depends on your solution, your system design capability, and your ability to decouple each stage.</p><p>A stage is something that takes in data, performs some operation on that data, and sends it back out.</p><h4>Code example of a pipeline</h4><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;strings&quot;<br>)<br>// Stage 1: Generate raw lines<br>func generateLines(rawLines []string) &lt;-chan string {<br> out := make(chan string)<br> go func() {<br> for _, line := range rawLines {<br> out &lt;- line<br> }<br> close(out) // signal end of data<br> }()<br> return out<br>}<br>// Stage 2: Clean each line (transform)<br>func cleanLines(in &lt;-chan string) &lt;-chan string {<br> out := make(chan string)<br> go func() {<br> for line := range in {<br> cleaned := strings.ToLower(line)<br> cleaned = strings.Join(strings.Fields(cleaned), &quot; &quot;) // remove extra spaces<br> out &lt;- cleaned<br> }<br> close(out)<br> }()<br> return out<br>}<br>// Stage 3: Count words in each line (sink)<br>func countWords(in &lt;-chan string) map[string]int {<br> wordCount := make(map[string]int)<br> for line := range in {<br> words := strings.Split(line, &quot; &quot;)<br> for _, w := range words {<br> wordCount[w]++<br> }<br> }<br> return wordCount<br>}<br>func main() {<br> // Simulated document lines<br> doc := []string{<br> &quot;Hello world hello Go&quot;,<br> &quot;Go pipelines are fun&quot;,<br> &quot;Fun fun fun&quot;,<br> }<br>// Build the pipeline<br> raw := generateLines(doc)<br> cleaned := cleanLines(raw)<br> result := countWords(cleaned)<br>// Output<br> fmt.Println(&quot;Word counts:&quot;)<br> for word, count := range result {<br> fmt.Printf(&quot; %s: %d\n&quot;, word, count)<br> }<br>}</pre><h4>Fan‑Out, Fan‑In Design Pattern</h4><blockquote>“Fan‑Out is a term used to describe the process of starting multiple goroutines to handle input from the pipeline, and fan‑in is a term to describe the process of combining multiple results into one channel.” — Concurrency in Go</blockquote><p><strong>By way of analogy:</strong><br>In Go’s fan‑out/fan‑in pattern, the main goroutine acts like a queen dispatching her workers: she fans out tasks to multiple worker goroutines that each fetch results independently, then fans back in as they return to a single shared channel — just as workers bring their gathered food back to the hive.</p><h4>When is a stage suitable for fan‑out / fan‑in?</h4><p>If your pipeline checks these two boxes, you’re good to implement it:</p><ul><li>It does <strong>not</strong> rely on values that the stage had calculated before.</li><li>It <strong>takes a long time to run</strong>.</li></ul><p><strong>Example scenario:</strong> A stage calls an external API, processes a large image, or queries a large database. A single goroutine becomes a bottleneck — the whole pipeline slows down to the speed of that stage.</p><ul><li><strong>Fan‑out</strong> solves this by launching multiple identical goroutines that all read from the same input channel. Each piece of work is processed by one of the workers, in parallel.</li><li><strong>Fan‑in </strong>solves the problem after fan‑out: you have multiple output channels (one per worker). You need to collect all results into a single channel for downstream stages. Fan‑in merges those channels.</li></ul><blockquote>Together they form a <strong>parallel processing pipeline</strong>:<br><strong>Input — -&gt; Fan-Out (workers) → Fan-In → Output</strong></blockquote><h4>A simple fan‑out / fan‑in program</h4><p>The program below squares a stream of numbers. Doing this with a single worker is possible but obviously slow, so we implement fan‑out to solve this.</p><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br>// The generator<br>func generator(nums …int) &lt;-chan int {<br> out := make(chan int)<br> go func() {<br> for _, num := range nums {<br> out &lt;- num<br> }<br> close(out)<br> }()<br> return out<br>}<br>// squareWorker is a slow function that squares ints<br>func squareWorker(in &lt;-chan int, id int) &lt;-chan int {<br> out := make(chan int)<br> go func() {<br> for n := range in {<br> // simulate some work<br> time.Sleep(100 * time.Millisecond)<br> out &lt;- n * n<br> }<br> close(out)<br> }()<br> return out<br>}<br>func fanIn(channels …&lt;-chan int) &lt;-chan int {<br> out := make(chan int)<br> var wg sync.WaitGroup<br>for _, ch := range channels {<br> wg.Add(1)<br> go func(c &lt;-chan int) {<br> defer wg.Done()<br> for val := range c {<br> out &lt;- val<br> }<br> }(ch)<br> }<br> go func() {<br> wg.Wait()<br> close(out)<br> }()<br> return out<br>}<br>func main() {<br> // Stage 1: generate numbers 0..9<br> input := generator(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)<br>// Fan-out: launch 3 workers<br> worker1 := squareWorker(input, 1)<br> worker2 := squareWorker(input, 2)<br> worker3 := squareWorker(input, 3)<br>// Fan-in: merge the three result channels<br> merged := fanIn(worker1, worker2, worker3)<br>// Consume results<br> for result := range merged {<br> fmt.Println(&quot;Final:&quot;, result)<br> }<br>}</pre><h4>Adding Cancellation (The done Channel)</h4><p>Without cancellation, if the consumer stops early (e.g., finds an error), the workers and generator will hang forever — a <strong>goroutine leak</strong>. We fix this by introducing a shared `done` channel (or a <strong>context.Context</strong>).</p><blockquote>In a future article, we’ll dive deep into cancellation with <strong>context</strong> and how to properly stop pipelines and worker pools.</blockquote><h4>Conclusion (and what’s next)</h4><p>We’ve covered a lot:</p><ul><li><strong>What design patterns are</strong> — reusable solutions, not copy‑paste code.</li><li><strong>Confinement(adhoc and lexical)</strong> — why it’s safer and faster than locks for many cases, and when locks are still necessary.</li><li><strong>The for‑select‑done pattern</strong> — the standard way to make a cancellable worker and prevent goroutine leaks.</li><li><strong>Pipelines</strong> — how to chain stages to process streams of data.<br>- <strong>Fan‑out / fan‑in</strong> — how to parallelise slow stages and merge results back together.</li></ul><p>But concurrency patterns don’t stop here. In upcoming articles (insha’Allah), I’ll cover:</p><ul><li><strong>Cancellation with context.Context</strong> — the idiomatic way to propagate cancellation across goroutines.</li><li><strong>Worker pools</strong> — limiting concurrency with a fixed number of workers.</li><li><strong>Heartbeats</strong> — monitoring goroutine health and liveliness.</li><li><strong>Rate limiting</strong>— controlling the frequency of operations.</li><li><strong>Bounded parallelism</strong> — managing resource usage in real‑world systems.</li></ul><p>You made it this far ? <strong>CHAMP!</strong>, thank you. You’re the reason I write. Please comment below if you’d like me to cover a specific pattern next, or if you have any questions.</p><p>Until then — keep your channels clean and your goroutines cancellable.</p><p>Bismillah.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cfc55b44e24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Select Statement]]></title>
            <link>https://notsocomplex.medium.com/the-select-statement-fce084d19bec?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce084d19bec</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Sat, 30 May 2026 16:49:03 GMT</pubDate>
            <atom:updated>2026-05-30T16:49:03.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hgq2YqjgQeju6LBb" /><figcaption>Photo by <a href="https://unsplash.com/@maaldoen?utm_source=medium&amp;utm_medium=referral">Maarten Scheel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>No cap — </strong>this is definitely the shortest article I’ve written this year. The good news is: if you’re new to the <strong>select</strong> statement, you should be up and running quickly, insha’Allah. If you need a refresher, you should be up to speed quickly too. But be not deceived — the purpose of this article is to lay a foundation for the next one, which will combine all we’ve learned into <strong>Concurrency Patterns in Go</strong>.</p><p>If you’re reading my article again, thank you so much. I really appreciate you taking your time to read what I have to say all the way from another part of the world. If it’s your first time here, thank you so much for stopping by. I do hope, insha’Allah, that this article fulfils the purpose of your clicking on it, and I hope that after you’ve learned and understood, you pass the torch on and teach what you have learned here. Because low key, it’s a way to accomplish immortality and leave behind a legacy.</p><p>Thank you for reading, as always. If there are areas you would like me to cover, or complaints, or creative and constructive criticism you can offer me, please do comment below.</p><p>Bismillah.</p><h4>What Is the Select Statement?</h4><p>If channels are the binding to goroutines, then <strong>select</strong> is the binding to channels. It gives us the ability to have a single goroutine listen in on multiple channels. It behaves a lot like the <strong>switch</strong> or <strong>case</strong> statement, depending on which language you have worked with. In addition to joining components, at these critical junctures in your program, <strong>select</strong> statements can help safely bring channels together with concepts like cancellations, timeouts, waiting, and default values.</p><p>The <strong>select</strong> statement undoubtedly looks a lot like the <strong>switch</strong> or <strong>case</strong> statement — again, depending on which language you’re coming from. This is true syntactically, but when we get down to how it works from Go’s perspective, it takes a whole different turn. Here’s an example:</p><pre>package main<br>import &quot;fmt&quot;<br>func main() {<br> var c1, c2 &lt;-chan interface{}<br> var c3 chan&lt;- interface{}<br>select {<br> case &lt;-c1:<br> fmt.Println(&quot;I am receiving from c1&quot;)<br> case &lt;-c2:<br> fmt.Println(&quot;I am receiving from c2&quot;)<br> case c3 &lt;- struct{}{}:<br> fmt.Println(&quot;I am sending to c3&quot;)<br> }<br>}</pre><p>Quite similar, right? But, unlike a <strong>switch</strong> block, <strong>case</strong> statements in a <strong>select</strong> aren’t tested sequentially, and execution won’t automatically fall through if none of the criteria is met.</p><h4>How Select Really Works</h4><p>Instead, <strong>all channel reads and writes are considered simultaneously</strong> (very cool!) to see if any of them are ready:</p><p>- <strong>For reads:</strong> channels that are populated (have a value) or <strong>closed</strong> are considered ready.<br>- <strong>For writes:</strong> channels that are <strong>not at capacity</strong> (buffer has free space, or unbuffered has a receiver waiting) are considered ready.</p><p>If none of the channels are ready, the entire `select` statement blocks. Then, when one of the channels becomes ready, that operation will proceed, and its corresponding statements will execute.</p><blockquote>In the example above, c1, c2, and c3 are all <strong>nil channels</strong>. A nil channel is never ready for reading or writing. Therefore, this <strong>select</strong> will block forever. To make it work, you must create the channels with <strong>make</strong> first.</blockquote><h4>Practical Example — Select in Action</h4><p>Let’s walk through a practical example. We create two channels, <strong>ch1</strong> and <strong>ch2</strong>, to transfer string data. Then we launch two goroutines, each sending a value to its respective channel.</p><pre>package main<br>import &quot;fmt&quot;<br>func goOne(ch chan string) {<br> ch &lt;- &quot;Channel-1&quot;<br>}<br>func goTwo(ch chan string) {<br> ch &lt;- &quot;Channel-2&quot;<br>}<br>func main() {<br> ch1 := make(chan string)<br> ch2 := make(chan string)<br>go goOne(ch1)<br> go goTwo(ch2)<br>select {<br> case val1 := &lt;-ch1:<br> fmt.Println(val1)<br> case val2 := &lt;-ch2:<br> fmt.Println(val2)<br> }<br>}</pre><p><strong>Possible outputs (non‑deterministic):</strong><br>- Channel-1<br>- Channel-2</p><p>Because both channels are ready at the same time, the Go runtime <strong>pseudo‑randomly</strong> chooses one of the two <strong>case</strong> statements. If you run this program multiple times, you may see either output — or sometimes one appears more often than the other. This randomness is a deliberate feature of <strong>select</strong> to prevent starvation.</p><blockquote>The program may exit before the other goroutine sends its value. That’s fine for this demonstration, but in real code you might use a <strong>sync.WaitGroup</strong> or a second <strong>select</strong> to receive both values.</blockquote><h4>A Cool Demonstration — Random Selection</h4><p>Let me show you something pretty cool. Its output makes the theory make a lot of sense.</p><pre>package main<br>import &quot;fmt&quot;<br>func main() {<br> channelO1 := make(chan interface{}); close(channelO1)<br> channelO2 := make(chan interface{}); close(channelO2)<br>var c1Count, c2Count int<br>for i := 10000; i &gt;= 0; i - {<br> select {<br> case &lt;-channelO1:<br> c1Count++<br> case &lt;-channelO2:<br> c2Count++<br> }<br> }<br> fmt.Printf(&quot;Channel one count: %d\nChannel two count: %d\n&quot;, c1Count, c2Count)<br>}</pre><blockquote><strong>Example output:</strong><br>Channel one count: 4971<br>Channel two count: 5030</blockquote><p>Wild, right? This makes no sense — of course it doesn’t, until I learned how the Go runtime handles <strong>select</strong> and its cases. Here’s how:</p><p>The Go runtime performs a <strong>pseudo‑random uniform selection</strong> over the set of case statements. This just means that of your set of case statements, each has an equal chance of being selected as all the others. That’s why the counts are not exactly 5000 each — one case may get slightly more selections purely by chance, but over many iterations they average out. (If you run the code yourself, the numbers will vary slightly.)</p><h4>Summary</h4><p>We’ve covered:</p><ul><li>What `select` is and how it differs from `switch`.</li><li>That all cases are considered simultaneously, not sequentially.</li><li>The rules for “ready” channels (reads on populated/closed channels, writes on non‑full buffers or waiting receivers).</li><li>The fact that nil channels block forever.</li><li>A clean, practical example with two goroutines and two channels.</li><li>The pseudo‑random selection among multiple ready cases.</li></ul><p>This short article is a foundation. Up next: <strong>Concurrency Patterns in Go— where we combine goroutines, channels, and select to build timeouts, cancellation, fan‑in, fan‑out, and worker pools.</strong></p><p>Thank you for reading. May this knowledge benefit you and those you teach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce084d19bec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Channels Explained: A Complete Guide for Beginners (With Examples)]]></title>
            <link>https://notsocomplex.medium.com/go-channels-explained-a-complete-guide-for-beginners-with-examples-370c7582fab9?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/370c7582fab9</guid>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Fri, 29 May 2026 16:56:28 GMT</pubDate>
            <atom:updated>2026-05-29T16:56:28.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tRtxStXkZXMWxIzC" /><figcaption>Photo by <a href="https://unsplash.com/@cherstve_pechivo?utm_source=medium&amp;utm_medium=referral">Liana S</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’ve read my last post on concurrency in Go, you might remember that I promised I would be writing an article on channels. This article strives to keep that promise. And if you have not read the article on concurrency, welcome. My intention in writing this article is first to learn about channels, and then to pass on what I have learned to you, my current reader. It is my hope that this article helps fill the gap, refresh your knowledge, or teach you about channels. Without any more delay — bismillah.</p><h3>What Are Channels?</h3><p>Channels are one of the synchronization primitives in Go derived from Hoare’s CSP. As its name describes its purpose, a channel is a synchronization primitive in Go. It serves — though not limited to — facilitating communication between multiple goroutines. You can think of it as the string connecting two telephone cups together, where each cup signifies (or can be thought of as) a goroutine, and the string connecting them is the channel by which the vibrations pass from cup A to cup B and vice versa.</p><p>Go channels work like network sockets between goroutines within a single application. They behave like a pipe that can share information asynchronously. Like network sockets, they can be bidirectional or unidirectional. Channels can exist as long‑lived or short‑lived connections. But unlike network sockets, channels are typed, can send structured information, and the awesome part (at least according to me) is that there’s generally no need to marshal payload — Go handles all the communication itself.</p><h4>Creating a Channel</h4><p>A channel can be created in two primary ways: as a buffered channel or as an unbuffered channel. These channels can further be made to be unidirectional or bidirectional.</p><p>Below is sample code of basic channels and the states they can exist in. The <strong>make</strong> keyword is used to create channels. To create a channel, you need to first understand your incoming or outgoing payload: how often do you receive data (continuous or spaced), and what data type is expected? The following code sample illustrates channels for different scenarios, though it is not limited to these examples.</p><pre>// - - - - - - - - - - - - - - - -<br>// 1. Unbuffered channels (blocking)<br>// - - - - - - - - - - - - - - - -<br>// Unbuffered bidirectional channel for integers<br>intStream := make(chan int)<br>// Unbuffered bidirectional channel for strings<br>docStream := make(chan string)<br>// Unbuffered bidirectional channel for single byte<br>byteStream := make(chan byte)<br>// Unbuffered bidirectional channel for a slice of bytes<br>bytesSliceStream := make(chan []byte)<br>// Unbuffered bidirectional channel for a custom struct<br>type Result struct {<br> Name string<br> Value int<br>}<br>resultStream := make(chan Result)<br>// - - - - - - - - - - - - - - - -<br>// 2. Buffered channels (non-blocking until full)<br>// - - - - - - - - - - - - - - - -<br>// Buffered bidirectional channel for ints with capacity 10<br>intStreamBuffered := make(chan int, 10)<br>// Buffered bidirectional channel for strings with capacity 5<br>stringStreamBuffered := make(chan string, 5)<br>// Buffered bidirectional channel for float64 with capacity 100<br>floatStreamBuffered := make(chan float64, 100)<br>// - - - - - - - - - - - - - - - -<br>// 3. Unidirectional channels (send‑only or receive‑only)<br>// - - - - - - - - - - - - - - - -<br>// Send‑only channel (can only send ints)<br>var sendOnly chan&lt;- int = make(chan int)<br>// Receive‑only channel (can only receive ints)<br>var receiveOnly &lt;-chan int = make(chan int)<br>// Typical use: function parameters<br>func producer(out chan&lt;- int) { // send‑only<br> out &lt;- 42<br>}<br>func consumer(in &lt;-chan int) { // receive‑only<br> val := &lt;-in<br> fmt.Println(val)<br>}</pre><p>If the idea of buffered and unbuffered channels, unidirectional and bidirectional channels is new to you, I’ve got you — next up we delve into what these are.</p><h4>Bidirectional Channels (Default)</h4><p>A bidirectional channel can both send and receive. This is the normal channel you get from <strong>make(chan T)</strong> or <strong>make(chan T, cap)</strong>.</p><pre>// Bidirectional unbuffered channel<br>messages := make(chan string)<br>// Bidirectional buffered channel (capacity 3)<br>tasks := make(chan int, 3)<br>// Using a bidirectional channel<br>go func() {<br> messages &lt;- &quot;ping&quot; // send<br>}()<br>msg := &lt;-messages // receive<br>fmt.Println(msg) // &quot;ping&quot;</pre><h4>Unidirectional Channels (Send‑only / Receive‑only)</h4><p>Sometimes you want to restrict a channel to <strong>only send</strong> or <strong>only receive</strong>. This is done with:</p><ul><li><strong>chan&lt;- T</strong> — send‑only channel (can only write)</li><li><strong>&lt;-chan T</strong> — receive‑only channel (can only read)</li></ul><p>These are most useful as <strong>function parameters</strong> to clearly state intent.</p><h4>Example 1: Send‑only channel</h4><pre>func producer(out chan&lt;- int) {<br> // out can only be sent to<br> for i := 0; i &lt; 5; i++ {<br> out &lt;- i<br> }<br> close(out) // still allowed to close<br>}</pre><h4>Example 2: Receive‑only channel</h4><pre>func consumer(in &lt;-chan int) {<br> // in can only be received from<br> for val := range in {<br> fmt.Println(&quot;received:&quot;, val)<br> }<br>}</pre><h4>Example 3: Full program with bidirectional → unidirectional conversion</h4><pre>package main<br>import &quot;fmt&quot;<br>func producer(out chan&lt;- int) {<br> for i := 1; i &lt;= 3; i++ {<br> out &lt;- i<br> }<br> close(out)<br>}<br>func consumer(in &lt;-chan int) {<br> for val := range in {<br> fmt.Println(&quot;consumer got:&quot;, val)<br> }<br>}<br>func main() {<br> ch := make(chan int) // bidirectional<br>go producer(ch) // automatically converts to send‑only<br> consumer(ch) // automatically converts to receive‑only<br>}</pre><p><strong>Output:</strong><br>consumer got: 1<br>consumer got: 2<br>consumer got: 3</p><p><strong>Important note</strong></p><ul><li>You <strong>cannot</strong> convert a send‑only channel back to bidirectional. Once restricted, it stays restricted.</li><li>The conversion happens <strong>automatically</strong> when passing a bidirectional channel to a function that expects <strong>chan&lt;-</strong> or <strong>&lt;-chan</strong>.</li></ul><h4>Footnote: Understanding the Channel Arrow</h4><p>This confused me for a bit, but after a while I discovered a neat trick by watching the direction of the arrow:</p><ul><li><strong>chan&lt;- T</strong> — the arrow <strong>points into</strong> the channel. This means you can <strong>send</strong> (write) into it. Think: the data is going <strong>into</strong> the channel.</li><li>&lt;-<strong>chan T</strong> — the arrow <strong>comes out of</strong> the channel. This means you can <strong>receive</strong> (read) from it. Think: the data is coming <strong>out of</strong> the channel.</li></ul><p>So remember: <strong>arrow pointing into the channel = send into it. Arrow coming out of the channel = receive from it.</strong></p><h3>Putting It to the Test — Compiler Errors Save You</h3><h4>First test (send‑only channel, trying to receive)</h4><p>Let’s put it to the test. The following program creates a write‑only stream, but instead of writing we try to read from it.</p><pre>package main<br>import &quot;fmt&quot;<br>func main() {<br> stringStream := make(chan string) // bidirectional<br> writeStream := make(chan&lt;- string) // send‑only<br> // readStream := make(&lt;-chan string) // receive‑only (commented out)<br>go func() {<br> stringStream &lt;- &quot;Well hello there!&quot; // valid: send to bidirectional channel<br> &lt;-writeStream // INVALID: trying to receive from send‑only channel<br> }()<br> fmt.Println(&lt;-stringStream) // valid: receive from bidirectional<br> close(stringStream)<br>}</pre><p><strong>Compiler error:</strong><br>invalid operation: cannot receive from send-only channel writeStream (variable of type chan&lt;- string)</p><h4>Second test (receive‑only channel, trying to send)</h4><pre>package main<br>import &quot;fmt&quot;<br>func main() {<br> stringStream := make(chan string) // bidirectional<br> readStream := make(&lt;-chan string) // receive‑only<br> // writeStream := make(chan&lt;- string) // send‑only (commented out)<br>go func() {<br> stringStream &lt;- &quot;Well hello there!&quot; // valid<br> readStream &lt;- &quot;Rainy init?&quot; // INVALID: trying to send to receive‑only channel<br> }()<br> fmt.Println(&lt;-stringStream)<br> close(stringStream)<br>}</pre><p><strong>Compiler error:</strong><br>invalid operation: cannot send to receive-only channel readStream (variable of type &lt;-chan string)</p><p>Neat, right? Now let’s scope down on the receiving channel — it has an ace up its sleeve: it can optionally return two values, like so:</p><pre>package main<br>import &quot;fmt&quot;<br>func main() {<br> stringStream := make(chan string)<br>go func() {<br> stringStream &lt;- &quot;Rainy Init?&quot;<br> }()<br> commonTalk, ok := &lt;-stringStream<br> fmt.Println(ok, commonTalk)<br>}</pre><p><strong>Output:</strong><br>true Rainy Init?</p><p>Interesting, right? With this we can clearly see and validate if a write operation was successfully performed by a writer, or detect a default value generated from a closed channel.</p><h4>Buffered Channels</h4><p>Buffered channels are simply channels that are created with a constant size — a capacity. The capacity determines how many values they can hold before they block.</p><p><strong>A simple declaration of a buffered channel:</strong></p><pre>var dataStream chan interface{}<br>dataStream = make(chan interface{}, 4)<br>audioStream := make(chan []byte, 1024)</pre><p>A buffered channel with no receivers and a capacity of four would be full after the fourth insertion into the buffer, and it would block on the fifth insertion. Like an unbuffered channel, a buffered channel can block. In this way, buffered channels are in‑memory FIFO queues for concurrent processes to communicate over.</p><p>The following is an illustration of a buffered channel created with a capacity of four and what occurs when we exceed this capacity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiYctJQUAGfjkmdQ83jVmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSYC_cK05HOPhcaAIObQbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEepaO1-uzdsfJBTT87gbA.png" /></figure><blockquote><strong>NOTE: The above illustrations were retrieved from Concurrency in Go: Tools and Techniques for Developers by Katherine Cox-Buday</strong>.</blockquote><p>If you made it this far, you’re simply the best. Thank you so much for taking time out to read what I have written. I write with the intention of benefiting the creation of Allah. I can only hope this article fulfills your thirst for knowledge and curiosity, and that you leave fulfilled and use this knowledge to do what transcends you and benefits yourself and the rest of humanity. Continue, shall we?</p><p>If you paid close attention to the illustrations or the text in the image, it clearly said:</p><blockquote>The goroutine performing the write is blocked, and will remain blocked until room is made in the buffer by some goroutine performing the read.</blockquote><p>This had me thinking of the following:</p><ul><li>What stops the writer from writing when the buffer is full?</li><li>How does the writer know when to resume?</li></ul><h4>Answers to Your Questions</h4><p><strong>1. What stops the writer from writing when the buffer is full?</strong></p><p>The Go runtime blocks the goroutine attempting to send. The<strong> ch &lt;- value</strong> line does not complete. The goroutine is parked (put to sleep) and removed from the run queue until space becomes available.</p><p><strong>2. How does the writer know when to resume?</strong></p><p>When a receive operation<strong> (&lt;-ch) </strong>takes a value from the buffer, the runtime <strong>wakes up one blocked sender</strong> (if any) and lets it complete its send. The sender goroutine is unparked and proceeds. The writer doesn’t “check” anything — the runtime handles it automatically.</p><h4>Minimal Code to Demonstrate Blocking and Unblocking</h4><pre>package main<br>import &quot;fmt&quot;<br>func main() {<br> ch := make(chan int, 2) // capacity 2<br>ch &lt;- 1 // fine<br> ch &lt;- 2 // fine<br> // ch &lt;- 3 // would block - uncomment to see deadlock<br>go func() {<br> fmt.Println(&quot;Reader waking up…&quot;)<br> fmt.Println(&lt;-ch) // removes 1, now buffer has 1 slot free<br> fmt.Println(&quot;Reader finished&quot;)<br> }()<br>// Give reader time to run, then this send will succeed<br> ch &lt;- 3 // now works because reader freed a slot<br> fmt.Println(&quot;Writer succeeded&quot;)<br>}</pre><h4>When to Use Channels</h4><p>Use channels when you care about communication within your app, and/or require the response of each goroutine for further processing. Channels are about <strong>value transfer</strong>, not just completion.</p><pre>results := make(chan Result)<br>go compute(results)<br>res := &lt;-results // we need the computed value</pre><h4>When Not to Use Channels</h4><ul><li>Don’t use a channel just to signal completion if you don’t need to send data. A <strong>sync.WaitGroup</strong> is cleaner and less error‑prone.</li><li>Don’t use a buffered channel as a job queue if you need reliable completion tracking — combine with <strong>WaitGroup</strong> or use a worker pool pattern.</li><li>Don’t use channels for simple mutual exclusion — use sync.Mutex.</li></ul><h4>Summary (What We Covered)</h4><p>We have covered:</p><ul><li>What channels are and why they exist (telephone cups analogy).</li><li>Buffered vs unbuffered channels.</li><li>Unidirectional channels (send‑only, receive‑only).</li><li>The arrow trick to remember direction.</li><li>How the compiler protects you from misuse (compile‑time errors).</li><li>The two‑value receive (`val, ok := &lt;-ch`) to check if a channel is still open.</li><li>Blocking behaviour of buffered channels and how the runtime handles backpressure.</li><li>Minimal runnable examples for each concept.</li></ul><h4>What’s Next — Coming Articles (Insha’Allah)</h4><p>This is not the end. Channels have more depths:</p><p>1. <strong>The select statement </strong>— waiting on multiple channels at once.<br>2. <strong>Closing channels </strong>— why, when, and how to close gracefully.<br>3. <strong>Pitfalls and misuse of channels</strong>— not a pros‑and‑cons list, but a guide on what goes wrong (deadlocks, leaks, race conditions) and how to design your algorithms to avoid them.</p><p>Insha’Allah, I will be writing an article on the pitfalls of using channels — not from a pros and cons perspective, but rather from a misuse perspective. The article will show the pitfalls and how to design your algorithm to mitigate them.</p><p>As of typing this article out in its draft form, I was approaching 12 pages. In all honesty, I have yet to cover a lot that ties into channels. Therefore, I will be breaking the other concepts or ideas into separate topics. Do watch out for these.</p><p>If you’ve read this far, thank you so much — you’re simply the best. I really do hope this article benefited you in some way. If not, please do comment down below what I should change or include the next time I write again. Arigato!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370c7582fab9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in Go]]></title>
            <link>https://notsocomplex.medium.com/concurrency-in-go-bee416d5145a?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bee416d5145a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Wed, 27 May 2026 18:01:50 GMT</pubDate>
            <atom:updated>2026-05-27T18:58:52.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xprhs7HG0vw4BSGC" /><figcaption>Photo by <a href="https://unsplash.com/@dkomow?utm_source=medium&amp;utm_medium=referral">Daniil Komov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article, insha’Allah, first delves into goroutines, which are functions capable of running concurrently. Then it delves into channels, Go’s mechanism for communicating between goroutines. We’ll also delve into mutexes, which are synchronization primitives that enable locking of resources as a way of enforcing consistency in concurrent systems.</p><p><strong>The program we will be building solves the following:</strong></p><p>You know that feeling when you have a folder full of PDFs that need passwords, and you don’t want to do them one by one? This program solves that. It looks inside a folder, finds every PDF file, and locks each one with two passwords (one to open, one to control printing and editing). And it does all that work <strong>at the same time</strong> — like having a team of tiny robots, each grabbing a PDF and encrypting it in parallel.</p><h4>What is Concurrency, and Why Do We Need It?</h4><p>Concurrency means <strong>a program doing multiple tasks at overlapping times.</strong> It’s not the same as parallelism (doing tasks a<strong>t the exact same moment </strong>on separate CPU cores). Concurrency is about <strong>structure</strong>; parallelism is about <strong>execution</strong>.</p><blockquote><strong><em>And if concurrency and parallelism don’t make any sense to you? I got you, insha’Allah — I have an article on threading in the works.</em></strong></blockquote><h4>Why does concurrency exist?</h4><p>Because the real world is slow. Reading a file from disk, waiting for a network response, or encrypting a PDF — these operations take milliseconds or seconds. Without concurrency, your program would sit idle, doing nothing, while it waits. Concurrency lets your program start another task while the first one is still waiting.</p><h4>When should you use concurrency?</h4><ul><li>When you have <strong>I/O‑bound work</strong>(file reads, HTTP requests, database queries).</li><li>When you have <strong>independent tasks</strong> that don’t need to happen one after another.</li><li>When you want <strong>better responsiveness</strong> (e.g., a GUI that doesn’t freeze).</li></ul><h4>When should you NOT use concurrency?</h4><ul><li>For <strong>trivial</strong> <strong>tasks</strong> where the overhead of starting a goroutine is larger than the task itself.</li><li>When tasks must be strictly sequential (task B needs the result of task A).</li></ul><p>Go makes concurrency easy with <strong>goroutines</strong> (lightweight threads) and <strong>channels</strong> (ways to communicate between them). The rest of this article shows you exactly how.</p><h4>Go’s Concurrency Model</h4><p>Go’s approach to concurrency is very different from other languages. Unlike Python or Java, where concurrency is implemented using OS threads or a lightweight version called green threads, both rely on the virtual machine to treat subprocesses like threads and handle context switching between them. Go takes a different route, basing its concurrency model on a model proposed by Tony Hoare called Communicating Sequential Processes (CSP).</p><p>What’s the difference between the conventional model and Tony Hoare’s model? That’s not a topic for this article, but insha’Allah in future articles I will delve into this.</p><p>Two concepts that make Go concurrency a reality</p><ul><li><strong>Goroutines</strong> — A goroutine is a function that runs independently of the function that started it. Think of it as a function that runs as if on its own thread.</li><li><strong>Channels</strong>— A channel is a pipeline for sending and receiving signals. Channels provide a way for one goroutine to send structured data to another. This is the primary mechanism for allowing goroutines to communicate with their caller or other goroutines. —<strong> Go in Practice</strong></li></ul><h4>Understanding Go’s goroutine</h4><p>A goroutine is a lightweight, independently executing function that runs concurrently with other goroutines within the same address space (the Go program’s memory).</p><p>When you prefix any function call with the keyword `go`, that function becomes a goroutine:</p><pre>go myFunction()   // myFunction now runs concurrently<br>go func() {       // anonymous function as a goroutine<br>    fmt.Println(&quot;hello from a goroutine&quot;)<br>}()</pre><h4>Why goroutines?</h4><p>Well that’s simple — they are lightweight.</p><p>Before the inception of goroutines, we used OS threads. This worked wonders, without a doubt, but there was a problem: it was terrible to scale. Here’s why:</p><p>By design, when an OS thread is spun, the OS provides it with its own space to work in. This space would contain its own program code, stack, heap, etc. For argument’s sake, let’s say all of this takes roughly 1 MB per thread. Not bad, right? Now let’s scale it to 10,000.</p><p>If you wanted to handle 10,000 concurrent connections with one thread per connection, you’d need 10,000 OS threads. That’s roughly:</p><p><strong>10,000 × 1 MB stack = 10 GB of memory minimum</strong></p><p>That’s without including the cost of context switching. If context switching is included, then we see a jump in time. Goroutines exist to solve this problem, and they do so in the most efficient of ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhakyY0SJ9lVI78vFjmWkA.png" /></figure><h4>The Go Solution: Goroutines</h4><p>Goroutines are designed to solve the C10K problem (handling 10,000 concurrent connections) and beyond. They are:</p><ul><li>Much lighter: Starting stack size is only ~2 KB (grows and shrinks as needed)</li><li>Cheaper to create: Thousands or millions of goroutines are practical</li><li>Managed by Go runtime in user space: No kernel involvement for scheduling decisions</li><li>Faster to switch: Context switching between goroutines is a matter of saving/restoring a few registers (nanoseconds, not microseconds)</li><li><strong>Key Insight:</strong> Goroutines are not threads. They are green threads or cooperative lightweight threads multiplexed onto a smaller number of OS threads. — DeepSeek</li></ul><h4>Starting a Goroutine — Three Flavours</h4><p>You can start a goroutine as stated earlier by prepending the <strong>go</strong> keyword to a function. This can be done in three flavours. Whichever you pick depends on how you choose to solve the problem.</p><ol><li><strong>Placing go in front of a function</strong></li></ol><pre>func main() {<br>    go sayHello()<br>    // continue doing other things<br>}<br>func sayHello() {<br>    fmt.Println(&quot;hello&quot;)<br>}</pre><p>2. <strong>Placing go in front of an anonymous function</strong></p><pre>go func() {<br>    fmt.Println(&quot;hello&quot;)<br>}()<br>// continue doing other things<br>```<br><br>//Using a variable<br><br>sayHello := func() {<br>    fmt.Println(&quot;hello&quot;)<br>}<br>go sayHello()<br>// continue doing other things</pre><blockquote>NOTE: The above sample code on flavours of concurrency using the go keyword was retrieved from the book <strong>Concurrency in Go</strong></blockquote><p>That’s it, to work with goroutines or concurrency in Go. Though regarding its proper usage, design, organization and orchestration of multiple goroutines is a complete topic on its own, this is all you really need to begin working with them.</p><h4>Working with goroutines</h4><p>One frequent use of goroutines is to run a function in the background — whether a long‑running function or an I/O‑blocking operation — so that other parts of the program can run freely without stalling. By doing this, other parts of the program can run freely without having to stall for the long‑running function to finish before they continue.</p><h4>Using a goroutine to run a task (broken example)</h4><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    //&quot;time&quot;<br>    &quot;io&quot;<br>    &quot;os&quot;<br>)<br><br>func echo(in io.Reader, out io.Writer) {<br>    io.Copy(out, in)<br>}<br><br>func main() {<br>    fmt.Println(&quot;Type anything within the window&quot;)<br>    go echo(os.Stdin, os.Stdout)<br><br>    fmt.Println(&quot;Timed Out!&quot;)<br>    os.Exit(0)<br>}</pre><p>That’s interesting — it did not wait for the input before exiting the program and printing the timeout message. Why could this be? A bug? In a way, yes — but this is by design supposed to occur. This tripped me up the first time I encountered it. It turns out the parent (or initiator) of a goroutine has absolute power over it. In our code sample, what occurs is that we aren’t waiting for the goroutine to run or finish before the `main` function exits. There exist multiple solutions, but let’s try the most basic one using a timer.</p><h4>Code sample with timer included</h4><p>This new example introduces a timer. By introducing a timer to the main function, we can wait for the goroutine to perform some work before the time is up.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>    &quot;io&quot;<br>    &quot;os&quot;<br>)<br><br>func echo(in io.Reader, out io.Writer) {<br>    io.Copy(out, in)<br>}<br><br>func main() {<br>    fmt.Println(&quot;Type anything within the 5 secs window&quot;)<br>    go echo(os.Stdin, os.Stdout)<br>    time.Sleep(5 * time.Second)<br>    fmt.Println(&quot;Timed Out!&quot;)<br>    os.Exit(0)<br>}</pre><p>Using a timer is fine when you know how long an event should take — for example, if you build a trivia game and expect guesses or answers to each question within 5 seconds. This is a good example. But the real world is messy and unpredictable.</p><h4>Waiting for goroutines — Introducing sync.WaitGroup</h4><p>As your programs grow in complexity and you introduce multiple goroutines, a need might arise to await all goroutines before proceeding. Using a timer would be very impractical for such a use case. That’s why Go introduced the wait group. The wait group provides a simple and intuitive way of accomplishing the above. This is done by explicitly defining the number of expected calls to its `Done` method.</p><p>Timer aside, Go provides a way of accomplishing this. A common library is <strong>sync.WaitGroup</strong>, a tool for telling a process to wait until one or more goroutines complete, specified by a numeric count.</p><h4>Simple encryption tool for encrypting PDFs (sequential version)</h4><p>This example will encrypt 100 PDFs without using goroutines.</p><p>To install the `pdfcpu` module for your Go project, run:</p><pre>go get github.com/pdfcpu/pdfcpu</pre><p>This command will download the library and add it as a dependency to your project’s <strong>go.mod</strong> file.</p><h4>A Quick Run Down on Go Modules</h4><p>If you are starting a new project, it’s a good practice to first initialize a Go module. You can do this by running:</p><pre>go mod init your-module-name</pre><p>For example:</p><pre>go mod init pdf-encryptor</pre><p>After running <strong>go mod init</strong>, you can then run the <strong>go get </strong>command to install <strong>pdfcpu</strong>.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>    &quot;path/filepath&quot;<br><br>    &quot;github.com/pdfcpu/pdfcpu/pkg/api&quot;<br>    &quot;github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model&quot;<br>)<br><br>func main() {<br>    // ------------------------------------------------------------------<br>    // 1. Read the folder path from command line arguments<br>    // ------------------------------------------------------------------<br>    // os.Args[0] is the program name, os.Args[1:] are the arguments.<br>    // Expecting exactly one argument: the path to the folder containing PDFs.<br>    if len(os.Args) &lt; 2 {<br>        fmt.Println(&quot;Usage: go run main.go &lt;path-to-pdf-folder&gt;&quot;)<br>        return<br>    }<br>    pdfFolderPath := os.Args[1]<br><br>    // ------------------------------------------------------------------<br>    // 2. Verify the folder exists and is readable<br>    // ------------------------------------------------------------------<br>    info, err := os.Stat(pdfFolderPath)<br>    if err != nil {<br>        fmt.Printf(&quot;Error accessing path &#39;%s&#39;: %v\n&quot;, pdfFolderPath, err)<br>        return<br>    }<br>    if !info.IsDir() {<br>        fmt.Printf(&quot;&#39;%s&#39; is not a directory\n&quot;, pdfFolderPath)<br>        return<br>    }<br><br>    // ------------------------------------------------------------------<br>    // 3. Read all directory entries (files/subfolders)<br>    // ------------------------------------------------------------------<br>    entries, err := os.ReadDir(pdfFolderPath)<br>    if err != nil {<br>        fmt.Printf(&quot;Failed to read directory &#39;%s&#39;: %v\n&quot;, pdfFolderPath, err)<br>        return<br>    }<br><br>    // ------------------------------------------------------------------<br>    // 4. Prepare output directory (create if missing)<br>    // ------------------------------------------------------------------<br>    // Using a subfolder &quot;output&quot; inside the input folder for portability.<br>    outputDir := filepath.Join(pdfFolderPath, &quot;output&quot;)<br>    err = os.MkdirAll(outputDir, 0755) // 0755 = rwxr-xr-x permissions<br>    if err != nil {<br>        fmt.Printf(&quot;Failed to create output directory &#39;%s&#39;: %v\n&quot;, outputDir, err)<br>        return<br>    }<br><br>    // ------------------------------------------------------------------<br>    // 5. Loop over each file and encrypt PDFs (sequential version)<br>    // ------------------------------------------------------------------<br>    for _, entry := range entries {<br>        // Skip subdirectories – only process regular files<br>        if entry.IsDir() {<br>            continue<br>        }<br><br>        // Get file name and check extension (case-insensitive check would be better)<br>        fileName := entry.Name()<br>        if filepath.Ext(fileName) != &quot;.pdf&quot; {<br>            fmt.Printf(&quot;Skipping non-PDF file: %s\n&quot;, fileName)<br>            continue<br>        }<br><br>        // Encrypt the PDF – if one fails, we log and continue (no os.Exit)<br>        err := encryptPDF(pdfFolderPath, fileName, outputDir)<br>        if err != nil {<br>            fmt.Printf(&quot;ERROR encrypting &#39;%s&#39;: %v\n&quot;, fileName, err)<br>            // Continue with next file instead of exiting<br>        }<br>    }<br>}<br><br>// encryptPDF encrypts a single PDF file and saves it to the output directory.<br>// Parameters:<br>//   - pdfDirPath : directory containing the original PDF<br>//   - fileName   : name of the PDF file (e.g., &quot;doc.pdf&quot;)<br>//   - outDir     : directory where encrypted PDF will be saved<br>// Returns an error if encryption fails, otherwise nil.<br>func encryptPDF(pdfDirPath, fileName, outDir string) error {<br>    // Build full input path<br>    inPath := filepath.Join(pdfDirPath, fileName)<br><br>    // Build output file name: insert &quot;_encrypted&quot; before the .pdf extension<br>    ext := filepath.Ext(fileName)<br>    base := fileName[:len(fileName)-len(ext)]<br>    outFileName := base + &quot;_encrypted&quot; + ext<br>    outPath := filepath.Join(outDir, outFileName)<br><br>    // Create default PDF configuration and set passwords<br>    config := model.NewDefaultConfiguration()<br>    config.UserPW = &quot;8-bitryan&quot;   // password to open the PDF<br>    config.OwnerPW = &quot;coryxkenshin&quot; // password for permissions (edit, print, etc.)<br><br>    // Encrypt the file using pdfcpu library<br>    fmt.Printf(&quot;Encrypting: %s -&gt; %s\n&quot;, fileName, outFileName)<br>    err := api.EncryptFile(inPath, outPath, config)<br>    if err != nil {<br>        // Return the error so the caller can handle it (log + continue)<br>        return fmt.Errorf(&quot;encryption failed for %s: %w&quot;, fileName, err)<br>    }<br><br>    fmt.Printf(&quot;Successfully encrypted: %s\n&quot;, fileName)<br>    return nil<br>}</pre><h4>Moving to Concurrent Encryption</h4><p>Neat, right? It works. But when we scale it becomes <strong>very</strong> horrible. Take an instance: say you decide to pass this tool to a few friends, and one of your friends works for Anna’s Archive (woo!), and they decide to encrypt 1TB worth of PDFs — for argument’s sake, let’s say that’s around 10,000,000 PDFs. The above code fails to use concurrency; as a result the program will run but at an order of N, one PDF at a time. I don’t have to tell you how slow this would be. But if we make use of goroutines and spin, say, 10 goroutines at once, that’s 10 encryptions happening at the same time. I dare say this would result in a much faster result time‑wise.</p><p>Now let’s update the above code to include goroutines.</p><h4>Concurrent PDF encryption with sync.WaitGroup</h4><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>    &quot;path/filepath&quot;<br>    &quot;strings&quot;<br>    &quot;sync&quot;<br><br>    &quot;github.com/pdfcpu/pdfcpu/pkg/api&quot;<br>    &quot;github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model&quot;<br>)<br><br>func main() {<br>    var wg sync.WaitGroup<br><br>    // Read path from arguments<br>    if len(os.Args) &lt; 2 {<br>        fmt.Println(&quot;Path to pdfs cannot be empty&quot;)<br>        return<br>    }<br>    fullPDFPath := os.Args[1]<br><br>    // Read directory – exit on error<br>    entries, err := os.ReadDir(fullPDFPath)<br>    if err != nil {<br>        fmt.Println(&quot;Something went wrong when reading dir&quot;, err)<br>        return<br>    }<br><br>    // Create output folder inside input folder<br>    outDir := filepath.Join(fullPDFPath, &quot;output&quot;)<br>    os.MkdirAll(outDir, 0755) // create if missing, ignore error (will be caught later)<br><br>    for _, file := range entries {<br>        // skip non-PDF files and subdirectories<br>        if file.IsDir() {<br>            continue<br>        }<br>        if !strings.HasSuffix(strings.ToLower(file.Name()), &quot;.pdf&quot;) {<br>            fmt.Printf(&quot;Skipping non-PDF: %s\n&quot;, file.Name())<br>            continue<br>        }<br><br>        wg.Add(1)<br>        go func(pdfPath, fileName, outDir string) {<br>            defer wg.Done()<br>            encryptPDF(pdfPath, fileName, outDir)<br>        }(fullPDFPath, file.Name(), outDir)<br>    }<br>    wg.Wait()<br>    fmt.Println(&quot;All goroutines finished&quot;)<br>}<br><br>func encryptPDF(pdfDirPath, fileName, outDir string) {<br>    fmt.Println(&quot;Processing:&quot;, fileName)<br><br>    outputFileName := strings.TrimSuffix(fileName, &quot;.pdf&quot;) + &quot;_encrypted.pdf&quot;<br>    outputPath := filepath.Join(outDir, outputFileName)<br><br>    config := model.NewDefaultConfiguration()<br>    config.UserPW = &quot;8-bitryan&quot;<br>    config.OwnerPW = &quot;coryxkenshin&quot;<br><br>    inFile := filepath.Join(pdfDirPath, fileName)<br><br>    err := api.EncryptFile(inFile, outputPath, config)<br>    if err != nil {<br>        fmt.Printf(&quot;Error encrypting %s: %v\n&quot;, fileName, err)<br>        return<br>    }<br>    fmt.Printf(&quot;PDF encrypted successfully: %s\n&quot;, fileName)<br>}</pre><p>The above implementation now runs concurrently with the aid of <strong>WaitGroup</strong>. Let’s delve into what the code does.</p><h4>What This Code Does</h4><p><strong>The Main Function</strong></p><p>First, the program waits for you to tell it which folder to work on. If you forget to give a folder path, it complains nicely and stops.</p><pre>if len(os.Args) &lt; 2 {<br>fmt.Println(&quot;Path to pdfs cannot be empty&quot;)<br>return<br>}</pre><p>Then it reads the list of files inside that folder. If the folder doesn’t exist or you don’t have permission, it prints an error and quits — no point continuing if there’s nothing to work with.</p><pre>entries, err := os.ReadDir(fullPDFPath)<br>if err != nil {<br>fmt.Println(&quot;Something went wrong when reading dir&quot;, err)<br>return<br>}</pre><p>Next, it creates an <strong>output</strong> subfolder inside your PDF folder. That’s where all the encrypted PDFs will go. The <strong>os.MkdirAll</strong> line is like: “make the folder if it’s not already there, and don’t panic if it exists.”</p><pre>outDir := filepath.Join(fullPDFPath, &quot;output&quot;)<br>os.MkdirAll(outDir, 0755)</pre><p><strong>The Loop That Starts the Workers</strong></p><p>Now comes the fun part. For every file in the folder, the program asks two questions:</p><p>1. Is this a folder itself? If yes, skip it — we only want real files.</p><p>2. Does the file name end with `.pdf` (case‑insensitive)? If no, print a message and skip it.</p><pre>if file.IsDir() { continue }<br>if !strings.HasSuffix(strings.ToLower(file.Name()), &quot;.pdf&quot;) {<br>fmt.Printf(&quot;Skipping non-PDF: %s\n&quot;, file.Name())<br>continue<br>}</pre><p>For every PDF that passes the test, the program does three things:</p><p>- <strong>wg.Add(1)</strong> — It says to itself: “I’m about to start one encryption task, so I’ll add one to my mental counter of unfinished jobs.”</p><p>- <strong>go func(…)</strong> — It launches a new “worker” (a goroutine) to handle that specific PDF. Think of it as hiring a temporary helper for each file. These workers all run at the same time.</p><p>- Inside that worker, `defer wg.Done()` is like a promise: “When I finish, I’ll tell the boss that one task is done.”</p><p>The <strong>wg.Add(1)</strong> and <strong>wg.Done()</strong> are like a tally sheet. The program keeps adding to the tally as it starts workers, and each worker subtracts one when it’s done.</p><p><strong>Waiting for Everyone to Finish</strong></p><p>After the loop finishes starting all the workers, the program hits:</p><pre>wg.Wait()</pre><p>This line is a <strong>roadblock</strong>. It says: “Do not go any further until the tally sheet says zero — until every worker has finished.” Once all the encrypted PDFs are written, the program prints “All goroutines finished” and exits. If it didn’t wait, the program would stop too early and you’d have only half your files done.</p><p><strong>The Encryption Function — What Each Worker Does</strong></p><p>Each worker runs <strong>encryptPDF</strong>. It gets three pieces of information: the folder path, the file name, and the output directory.</p><ul><li>First, it creates a new name for the encrypted file. If the original is <strong>report</strong>.<strong>pdf</strong>, the new one will be <strong>report_encrypted.pdf</strong>. It does this by cutting off the .pdf at the end and adding _encrypted.pdf</li></ul><pre>outputFileName := strings.TrimSuffix(fileName, &quot;.pdf&quot;) + &quot;_encrypted.pdf&quot;</pre><ul><li>Then it builds the full output path (e.g., MyPDFs/output/report_encrypted.pdf).</li><li>It creates a configuration object where it sets two passwords: one for the user (to open the PDF) and one for the owner (to allow printing, copying, etc.). Those passwords are hardcoded in this example — you’d probably change them in real life.</li><li>Finally, it calls api.EncryptFile — the actual magic from the pdfcpu library — which reads the original PDF, locks it with the passwords, and saves the locked version to the output folder.</li></ul><p>If something goes wrong (maybe the file is corrupted or the output folder is write‑protected), it prints an error message and returns. If everything goes well, it prints a success message.</p><h4>Why Use Goroutines (Concurrency)?</h4><p>The cool thing is that all these workers run at the same time. If you have 50 PDFs, you don’t have to wait for <strong>#1 to finish before starting,</strong> <strong>#2. On a modern computer with multiple cores, encrypting many PDFs at once can be a huge time saver.</strong></p><p>Of course, you could go overboard — launching 10,000 goroutines would slow things down. But for a few dozen or hundred PDFs, it’s fine. The <strong>sync.WaitGroup</strong> makes sure you don’t accidentally exit early.</p><h4>The WaitGroup</h4><p>The <strong>WaitGroup</strong> is part of the <strong>sync</strong> package in Go. It serves the main purpose of incrementing and decrementing a counter for goroutines that are added and then completed. It acts as a gatekeeper: each goroutine that runs increments the ledger, and each goroutine that finishes is removed from the checklist.</p><p><strong>WaitGroup</strong> is a great way to wait for a set of concurrent operations to complete when you either don’t care about the result of the concurrent operation, or you have other means of collecting or passing on the returned results.</p><h4>How WaitGroup works</h4><p>Think of a <strong>WaitGroup</strong> as a simple counter with three safety guarantees:</p><ul><li><strong>Thread‑safe</strong>: multiple goroutines can safely increase, decrease, and wait on the counter without interfering with each other.</li><li><strong>Atomic:</strong> changes to the counter happen as a single, indivisible operation.</li><li><strong>Blocks efficiently:</strong> <strong>Wait() </strong>doesn’t waste CPU cycles spinning; instead, it puts the calling goroutine to sleep until the counter reaches zero. — DeepSeek</li></ul><p>If you’ve read this far, thank you so much. Not a lot of folks do this — thanks a million! Sadly, we’ve not come to the end just yet. Concurrency is all nice and stuff, but what happens when you have two concurrent functions both accessing and modifying the same variable? It’s like two men who dash with a wedding ring, unaware of each other, but both dashing to the same woman. I bet when they both get there, there will be consequences. In computer science, this is called a <strong>race condition</strong>. This occurs when two things are racing to read or write to and from the same piece of information. Let’s discuss how Go solves this issue.</p><h4>Mutex and RWMutex: Locking with a Mutex</h4><p>We have a problem, and this problem will eventually arise when we have two or more goroutines accessing or modifying the same piece of sensitive information or area. The solution is to place a lock on the piece of information to be read or modified by a reader or writer. Once the writer is done with that piece of information, it unlocks the information for other goroutines to access and perform what they intend to do with the data. When other goroutines see the lock, they wait their turn — they wait until the lock is removed before attempting to acquire the lock themselves. This is done with <strong>sync.Mutex</strong>.</p><p><strong>Mutex</strong> (Mutual Exclusion) is a way to guard critical section(s) of your program.</p><h4>Simple example of a mutex lock</h4><pre>var mu sync.Mutex<br>var counter int<br><br>mu.Lock()<br>counter++<br>mu.Unlock()</pre><p>This part of the code confused me. I was expecting an address to be passed into <strong>Lock()</strong> — how would the lock know which variable to lock? It turns out it’s much simpler: it has to do with what sits between <strong>Lock()</strong> and <strong>Unlock().</strong> You are not protecting data directly. Rather, you as the programmer are responsible for defining a region of code between <strong>Lock()</strong> and <strong>Unlock()</strong> where only one goroutine can be at a time. In our case, the counter sits between <strong>Lock()</strong> and <strong>Unlock()</strong>. That protects it so no other goroutine can modify it. Once the current routine is done, it unlocks, and other goroutines can then lock, do their work, and unlock.</p><h4>Race condition example (without mutex)</h4><p>Here’s an example where we write a concurrent Go program that makes use of 100 goroutines to sum to 1000. It works sometimes, producing 1000; sometimes it won’t produce 1000. Using the <strong>go run -race</strong> flag allows the compiler to highlight where a race condition will occur.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func main() {<br>    counter := 0<br>    var wg sync.WaitGroup<br><br>    for i := 0; i &lt; 100; i++ {<br>        wg.Add(1)<br>        go func() {<br>            for j := 0; j &lt; 10; j++ {<br>                counter++ // race condition here<br>            }<br>            wg.Done()<br>        }()<br>    }<br><br>    wg.Wait()<br>    fmt.Println(&quot;Final counter:&quot;, counter) // expected 1000, but you&#39;ll get a random number less than 1000<br>}</pre><h4>The following implements the Mutex Lock</h4><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func main() {<br>    var mu sync.Mutex<br>    counter := 0<br>    var wg sync.WaitGroup<br><br>    for i := 0; i &lt; 100; i++ {<br>        wg.Add(1)<br>        go func() {<br>            for j := 0; j &lt; 10; j++ {<br>                mu.Lock()<br>                counter++<br>                mu.Unlock()<br>            }<br>            wg.Done()<br>        }()<br>    }<br>    wg.Wait()<br>    fmt.Println(&quot;Counter total is: &quot;, counter)<br>}</pre><p>Output of the code above with the <strong>-race</strong> flag and mutex lock included — no race condition, and the counter is reliably 1000.</p><h4>Closing Words (and a Promise)</h4><p>As of typing this, it turns out this has become a 20‑page write‑up. I’m tempted to close up shop here, but hold on — I do plan to keep my promise. I did say in the introduction I would be covering channels, and I will, insha’Allah. But I think it deserves its own article — not because it’s neuroscience‑complex, but because I want to give it its own place on the internet. If you’ve read this far, thank you so much — you’re simply the best.</p><h4>Summary &amp; Key Takeaways</h4><p>We’ve covered a lot — from the basics of goroutines to real‑world PDF encryption. If you forget everything else, hold onto these core ideas:</p><h4>What we covered</h4><ul><li>Why goroutines — They are lightweight (≈2KB stack vs 1MB for OS threads), allowing you to run thousands or millions concurrently.</li><li>Starting goroutines — Use the <strong>go</strong> keyword with a named function, anonymous function, or function variable.</li><li>The early‑exit trap — A program exits when main returns, killing all goroutines. Don’t rely on time.Sleep; use proper synchronisation.</li><li>sync.WaitGroup — A counter that lets main (or any function) wait for a group of goroutines to finish. Call Add before launching each goroutine, Done when it finishes, and Wait to block until zero.</li><li>Race conditions — When multiple goroutines access the same variable concurrently and at least one writes, the result is unpredictable. Detect them with <strong>go run -race</strong>.</li><li>sync.Mutex — Protects a critical section (code between Lock() and Unlock()). It doesn’t lock a variable — it locks a region so only one goroutine can execute that region at a time.</li><li>Concrete example — A complete program that encrypts all PDFs in a folder using goroutines and a <strong>WaitGroup</strong>, turning a slow sequential task into a fast parallel one.</li></ul><h4>Takeaways to remember</h4><ol><li>Goroutines are cheap; start thousands without fear.</li><li>Stack starts at ~2KB and grows dynamically — nothing like OS threads.</li></ol><p>3. Never let main finish before your goroutines do.</p><p>4. Use sync.WaitGroup or channels to wait.</p><p>5. A mutex protects code, not data.</p><p>6. Place Lock() and Unlock() around the few lines that must run atomically.</p><p>7. Always test with the race detector.</p><p>8. go run -race yourfile.go catches hidden concurrency bugs.</p><p><strong>(That’s where channels come in — stay tuned for the next article, insha’Allah.)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bee416d5145a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Errors and panics]]></title>
            <link>https://notsocomplex.medium.com/handling-errors-and-panics-e45137c11088?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45137c11088</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Fri, 15 May 2026 16:07:07 GMT</pubDate>
            <atom:updated>2026-05-15T16:07:07.240Z</atom:updated>
            <content:encoded><![CDATA[<p>Go Error Handling: From Errors to Panics and Recovery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*154Ljk2sW5rR3Rbp" /><figcaption>Photo by <a href="https://unsplash.com/@geekgunda?utm_source=medium&amp;utm_medium=referral">geekgunda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is for you if you are new to handling errors and panic in the language. I also assume you are already past the basic aspects of the language.</p><p>An <strong>error</strong> in Go represents an anomaly that occurs within the expected sequence of events or steps in your algorithm. When it occurs, it makes the previous or next steps impossible to complete, rendering your algorithm ineffective at solving the problem it was designed for.</p><p>A <strong>panic</strong> is a destructive occurrence during the lifespan of your program that renders your application totally useless, requiring a total reboot or shutdown.</p><h4>Error Handling</h4><p><em>Unlike languages like Python, where we throw and catch exceptions, or use try/except for a specific range of exceptions or all exceptions, Go solves error handling in a rather different way. One way is to return the error as the last statement; this is a convention and fits into the Go language design of returning multiple values. To accomplish this goal, Go employs the errors package. This package is used to return the error value, which the calling code then has to explicitly check for a nil value.</em></p><p>But how does Go actually implement this? Let’s look at the mechanics.</p><h4>Code Sample: Errors in Go</h4><pre>package main<br><br>import (<br>    &quot;errors&quot;<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>    &quot;strings&quot;<br>)<br><br>func main() {<br>    fmt.Println(&quot;Please enter a string&quot;)<br>    enteredValue := os.Args[1:]<br>    if val, err := Concat(enteredValue...); err != nil {<br>        fmt.Println(&quot;An error occurred: &quot;, err)<br>    } else {<br>        fmt.Println(&quot;Here is what you entered:&quot;, val)<br>    }<br>}<br><br>func Concat(words ...string) (string, error) {<br>    if len(words) == 0 {<br>        return &quot;&quot;, errors.New(&quot;Sentence cannot be empty&quot;)<br>    }<br>    return strings.Join(words, &quot; &quot;), nil // added space separator<br>}<br><br></pre><p><em>The code sample is simple and straight to the point. It illustrates the Go way of handling errors: we as developers are responsible for receiving that error and performing some operation to mitigate the error — a recovery. But what happens when your errors are specific and not always simple or singular? What happens when you have to handle different errors, each arising from a special case not shared by all your code? For example, a timeout error, a connection error, or a parsing error?</em></p><h4>Error Variable (Sentinel Errors)</h4><p><em>The central idea of using error variables is to create package-scoped error variables that can be returned whenever a certain error occurs. These are also called sentinel errors — those that have meaning in a specific context or scenario. By assigning error values to specific causes rather than general ones, we can isolate different types of errors and return only the error values tied to each cause.</em></p><p>But how does Go actually implement this? Let’s look at the mechanics.</p><h4>Code Sample: Sentinel Errors in Go</h4><pre>package main<br><br>import (<br>    &quot;errors&quot;<br>    &quot;fmt&quot;<br>)<br><br>// Define package-scoped sentinel errors.<br>// These are exported (capitalized) so other packages can check against them.<br>var (<br>    ErrEmptyInput = errors.New(&quot;input cannot be empty&quot;)<br>    ErrTooLong    = errors.New(&quot;input exceeds maximum length&quot;)<br>    ErrInvalidChar = errors.New(&quot;input contains invalid characters&quot;)<br>)<br><br>// validateInput checks a string against several rules.<br>// It returns a sentinel error corresponding to the first rule that fails.<br>func validateInput(s string) error {<br>    if s == &quot;&quot; {<br>        return ErrEmptyInput          // return the specific sentinel error<br>    }<br>    if len(s) &gt; 10 {<br>        return ErrTooLong<br>    }<br>    for _, ch := range s {<br>        if ch &lt; &#39;a&#39; || ch &gt; &#39;z&#39; {<br>            return ErrInvalidChar<br>        }<br>    }<br>    return nil // no error, input is valid<br>}<br><br>func main() {<br>    testInputs := []string{&quot;&quot;, &quot;hello&quot;, &quot;thisisverylong&quot;, &quot;Hello123&quot;}<br><br>    for _, input := range testInputs {<br>        err := validateInput(input)<br>        if err != nil {<br>            // Use errors.Is to check the error type (handles wrapped errors)<br>            switch {<br>            case errors.Is(err, ErrEmptyInput):<br>                fmt.Printf(&quot;Input %q: %v\n&quot;, input, err)<br>            case errors.Is(err, ErrTooLong):<br>                fmt.Printf(&quot;Input %q: %v (length %d)\n&quot;, input, err, len(input))<br>            case errors.Is(err, ErrInvalidChar):<br>                fmt.Printf(&quot;Input %q: %v\n&quot;, input, err)<br>            default:<br>                fmt.Printf(&quot;Input %q: unknown error %v\n&quot;, input, err)<br>            }<br>        } else {<br>            fmt.Printf(&quot;Input %q is valid\n&quot;, input)<br>        }<br>    }<br>}</pre><h4>The Panic System</h4><p><em>As the name indicates, a panic tells you that something has encountered an error in a way that the application may not be able to recover from. It should be used sparingly and intelligently. In this section, we explain how and when panics should be used, and along the way, we tell you about some of our own failures.</em></p><h4><strong>Differentiating panics from Errors</strong></h4><p>An error indicates that an event occurred that might violate expectations about what should have happened. A panic, by contrast, indicates that something has gone wrong in such a way that the system (or the immediate subsystem) can’t continue to function. — Go in Practice</p><h4><strong>Code Sample: Unhandled Panic in Go</strong></h4><pre>package main<br><br>import &quot;fmt&quot;<br><br>// This function deliberately causes a panic.<br>// It tries to access an out-of-bounds index in a slice.<br>func causePanic() {<br>    numbers := []int{1, 2, 3}<br>    fmt.Println(&quot;Trying to access index 10...&quot;)<br>    // This line will panic because the slice only has indices 0,1,2<br>    value := numbers[10] // panic: runtime error: index out of range [10] with length 3<br>    fmt.Println(&quot;Value is:&quot;, value) // This line never runs<br>}<br><br>func main() {<br>    fmt.Println(&quot;Program started.&quot;)<br><br>    // Call the function that panics.<br>    // There is NO defer/recover to handle the panic.<br>    causePanic()<br><br>    // This line will never be executed because the program crashes.<br>    fmt.Println(&quot;Program finished normally.&quot;)<br>}</pre><h4>What it does</h4><p>The program contains two functions:</p><ul><li>causePanic(): Creates a slice with three integers, then tries to access index 10, which does not exist.</li><li>main(): Calls causePanic() with no panic recovery mechanism.</li></ul><p>Because the slice index is out of bounds, the Go runtime <em>panics</em>. The panic is <strong>not handled</strong> by a defer + recover(), so Go unwinds the stack, prints a stack trace, and terminates the program. The final fmt.Println(&quot;Program finished normally.&quot;) never runs.</p><h4>How it works</h4><ol><li><strong>Panic generation</strong> — When an impossible operation occurs (e.g., out‑of‑bounds slice access, nil pointer dereference, or calling panic() explicitly), Go enters panic mode.</li><li><strong>Stack unwinding</strong> — Go begins to unwind the call stack, running any deferred functions along the way. In this example, there are no deferred functions.</li><li><strong>Crash</strong> — Because no handler (recover()) is found at any level, Go prints the panic value and stack trace, then exits with a non‑zero status code.</li><li><strong>Program termination</strong> — The operating system receives the exit code; the program does not continue.</li></ol><h4>Working with Panics</h4><p>The definition of panic is as follows: panic(interface{}). This definition allows any information to be passed into the panic. A rule of thumb when working with panics is to pass useful information – an error, for instance – with the main purpose being that anything passed will aid the recovery process when a panic occurs.</p><h4>Simple Panic</h4><pre>// Simple Panic<br>package main<br><br>func main() {<br>    panic(&quot;Well!&quot;)<br>}</pre><h4>Proper Panic</h4><pre>// A proper panic<br>package main<br><br>import &quot;errors&quot;<br><br>func main() {<br>    panic(errors.New(&quot;Failed to write to disk&quot;))<br>}</pre><h4>Recovery from Panics</h4><p>Panic recovery in Go depends on a feature of the language called deferred functions. Go can guarantee the execution of a function at the moment its parent function returns. This happens whether the reason for the parent function’s return is a return statement, the end of the function block, or a panic.</p><pre>defer func() {<br>    if r := recover(); r != nil {<br>        fmt.Println(&quot;Recovered from panic:&quot;, r)<br>    }<br>}()<br>panic(&quot;something went wrong&quot;)</pre><p>The recover function is a built‑in Go function that allows a program to regain control after a panic has occurred. It is only useful inside a deferred function. When called, recover returns the value that was passed to panic (for example, an error message or a string). If no panic is happening, recover returns nil. By checking recover’s return value, you can decide whether to log the panic, clean up resources, or allow the program to continue running instead of crashing.</p><p>With defer, I hope you start to see how it fits into the panic system? When we panic, we require a recovery — what better way than to defer a recovery function, since defer, by design, will always run regardless of the scenario of its parent function.</p><p>Side Note: The defer statement is a great way to close a file, clean up resources, close a database connection, handle panics, etc</p><h4>Code Sample: Capturing Panics with defer</h4><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>)<br><br>// riskyFunction simulates an operation that may panic.<br>// It takes a boolean parameter: if true, it panics; if false, it returns normally.<br>func riskyFunction(shouldPanic bool) {<br>    fmt.Println(&quot;  -&gt; Entering riskyFunction&quot;)<br>    if shouldPanic {<br>        // Simulate a critical failure (e.g., disk write error, nil pointer dereference)<br>        panic(&quot;something went horribly wrong in riskyFunction&quot;)<br>    }<br>    fmt.Println(&quot;  -&gt; Leaving riskyFunction without panic&quot;)<br>}<br><br>// safeCaller calls riskyFunction but uses defer + recover to capture any panic.<br>func safeCaller(shouldPanic bool) {<br>    // Deferred function runs even if panic occurs.<br>    defer func() {<br>        if r := recover(); r != nil {<br>            // r contains the value passed to panic().<br>            fmt.Printf(&quot;  [RECOVERED] Caught panic inside safeCaller: %v\n&quot;, r)<br>            // Optionally, log the panic for debugging.<br>            log.Printf(&quot;Panic captured: %v&quot;, r)<br>        }<br>    }()<br><br>    fmt.Println(&quot;-&gt; Calling riskyFunction from safeCaller&quot;)<br>    riskyFunction(shouldPanic)<br>    // This line only runs if no panic occurred.<br>    fmt.Println(&quot;-&gt; Back in safeCaller, execution continues normally&quot;)<br>}<br><br>func main() {<br>    fmt.Println(&quot;=== Case 1: No panic ===&quot;)<br>    safeCaller(false)<br><br>    fmt.Println(&quot;\n=== Case 2: Panic occurs, but is captured ===&quot;)<br>    safeCaller(true)<br><br>    fmt.Println(&quot;\n=== Main program continues after captured panic ===&quot;)<br>    fmt.Println(&quot;Program finished without crashing.&quot;)<br>}</pre><h4>What it does</h4><p>The program demonstrates how to <strong>capture a panic</strong> using a defer statement that calls recover().</p><ul><li>riskyFunction may or may not panic.</li><li>safeCaller calls riskyFunction and <strong>deploys a deferred anonymous function</strong> that calls recover().</li><li>If riskyFunction panics, the deferred function runs, catches the panic value, prints it, logs it, and <strong>prevents the crash</strong> – the rest of main continues normally.</li><li>If no panic occurs, recover() returns nil and the deferred function does nothing.</li></ul><h4>How it works</h4><ol><li><strong>defer</strong> – The line defer func() { ... }() tells Go: “After the surrounding function (safeCaller) finishes (whether by return, end of block, or <strong>panic</strong>), run this anonymous function.”</li><li><strong>recover()</strong> – Inside the deferred function, recover() checks if a panic is happening.</li><li>If a panic is active, recover() returns the value passed to panic (here, the string &quot;something went horribly wrong in riskyFunction&quot;).</li><li>If no panic is active, recover() returns nil.</li><li><strong>Preventing crash</strong> — By calling recover() and <strong>not re‑panicking</strong>, the program stops the panic unwinding. Execution resumes after the function that panicked (in this case, after safeCaller returns). The rest of main runs to completion.</li></ol><p>Lets combine all we’ve learnt thus far , Below is a <strong>complete, self‑contained Go program</strong> that combines:</p><ul><li><strong>Sentinel errors</strong> (ErrFileNotExist, ErrLowDiskSpace)</li><li><strong>Panic</strong> when a critical condition occurs (file missing or disk full)</li><li><strong>Defer + recover</strong> to catch the panic, attempt to fix the problem (create missing file), and retry or report the issue</li><li><strong>Explicit error handling</strong> for the write operation</li></ul><p>The program tries to open a file and write a text. If the file does <strong>not exist</strong>, it panics with ErrFileNotExist, the recover block catches it, creates the file, and retries. If the disk is <strong>full</strong> (simulated by a custom error), it panics with ErrLowDiskSpace and the recover block prints a message without crashing the whole program.</p><pre>package main<br><br>import (<br> &quot;errors&quot;<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>// Sentinel errors – package scoped<br>var ErrFileNotExist = errors.New(&quot;file does not exist&quot;)<br>var ErrLowDiskSpace = errors.New(&quot;disk space is too low or empty&quot;)<br><br>// The text we want to write to the file<br>var message = []byte(&quot;Go errors and panics: learning by doing!\n&quot;)<br><br>func main() {<br> // Defer a function that can recover from panics<br> defer func() {<br>  if r := recover(); r != nil {<br>   // Check if the panic value is one of our sentinel errors<br>   if err, ok := r.(error); ok {<br>    switch {<br>    case errors.Is(err, ErrFileNotExist):<br>     fmt.Println(&quot;[RECOVER] File missing – attempting to create it.&quot;)<br>     // Try to create the file<br>     if createFile(&quot;output.txt&quot;) {<br>      fmt.Println(&quot;[RECOVER] File created successfully. Retrying write...&quot;)<br>      // Retry the write operation<br>      writeToFileOrPanic(&quot;output.txt&quot;)<br>     } else {<br>      fmt.Println(&quot;[RECOVER] Failed to create file. Please check permissions.&quot;)<br>     }<br>    case errors.Is(err, ErrLowDiskSpace):<br>     fmt.Println(&quot;[RECOVER] Low disk space – cannot write. Free up space and try again.&quot;)<br>    default:<br>     // Unknown error – re‑panic to stop the program<br>     fmt.Printf(&quot;[RECOVER] Unknown error: %v – re‑panicking\n&quot;, err)<br>     panic(r)<br>    }<br>   } else {<br>    // Not an error value – re‑panic<br>    panic(r)<br>   }<br>  }<br> }()<br><br> // Start the operation<br> fmt.Println(&quot;Starting file write operation...&quot;)<br> writeToFileOrPanic(&quot;output.txt&quot;)<br> fmt.Println(&quot;Program finished successfully.&quot;)<br>}<br><br>// writeToFileOrPanic tries to open the file and write the message.<br>// If the file does not exist, it panics with ErrFileNotExist.<br>// If a write error occurs due to disk space, it panics with ErrLowDiskSpace.<br>func writeToFileOrPanic(filename string) {<br> // Open file for appending (or write-only). O_CREATE is NOT used – we want to panic if missing.<br> file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND, 0644)<br> if err != nil {<br>  if os.IsNotExist(err) {<br>   panic(ErrFileNotExist)<br>  }<br>  // Any other open error – treat as disk space? Simpler: just panic with generic<br>  panic(fmt.Errorf(&quot;failed to open file: %w&quot;, err))<br> }<br> defer file.Close()<br><br> // Write the message<br> n, err := file.Write(message)<br> if err != nil {<br>  // In a real system, you might check for ENOSPC (no space left)<br>  // Here we assume any write error is disk space related<br>  panic(ErrLowDiskSpace)<br> }<br> if n != len(message) {<br>  panic(ErrLowDiskSpace) // short write also indicates disk full or partial failure<br> }<br> fmt.Printf(&quot;Successfully wrote %d bytes to %s\n&quot;, n, filename)<br>}<br><br>// createFile attempts to create a new file. Returns true on success, false on failure.<br>func createFile(filename string) bool {<br> file, err := os.Create(filename)<br> if err != nil {<br>  fmt.Printf(&quot;Error creating file: %v\n&quot;, err)<br>  return false<br> }<br> file.Close()<br> return true<br>}</pre><h4>How to Test the Program</h4><h4><strong>First run</strong> — output.txt does not exist.</h4><ul><li>The program panics with ErrFileNotExist.</li><li>Recover block catches it, creates the file, and retries.</li><li>The second attempt succeeds. Output:</li></ul><pre>Starting file write operation...<br>[RECOVER] File missing – attempting to create it.<br>Successfully wrote 42 bytes to output.txt<br>[RECOVER] File created successfully. Retrying write...<br>Successfully wrote 42 bytes to output.txt<br>Program finished successfully.</pre><p><strong>2. Second run</strong> — output.txt already exists.</p><ul><li>No panic, file is appended. Output:</li></ul><pre>Starting file write operation...<br>Successfully wrote 42 bytes to output.txt<br>Program finished successfully.</pre><p>3. <strong>Simulating low disk space</strong> — Temporarily modify writeToFileOrPanic to always return ErrLowDiskSpace (e.g., after file.Write, add panic(ErrLowDiskSpace)). Then the recover block prints the disk space message and does not crash.</p><p><strong>With that, dear reader, we have come to the end of our time together. If all was lost on you, I don’t blame you — learning takes time. But if you take anything from this article, let it be this: errors for expected failures, panics for disasters, defer+recover for resilience.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45137c11088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How i Built an A2A AI Agent as part of my HNG-13 internship task]]></title>
            <link>https://notsocomplex.medium.com/how-i-built-an-a2a-ai-agent-as-part-o-my-hng-13-internship-task-ce656f33ce2e?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce656f33ce2e</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 21:51:56 GMT</pubDate>
            <atom:updated>2025-11-08T07:24:07.260Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>“I didn’t expect this project to carry me to Stage 4, but what happened next felt like a miracle”</em></strong></p><p>For this stage of the HNG Internship, we were tasked with building an <strong>AI agent</strong> that communicates using the recently introduced <strong>A2A (Agent-to-Agent) Protocol</strong> as the primary means of establishing connection and communication.</p><p>Here’s how I approached the challenge — and a demo of my project.</p><h4>The Idea: A Parcel Tracker Agent</h4><p>For my project, I wanted to create something not just functional but genuinely <em>useful</em> — something that could solve a real problem or, at the very least, show potential for practical application in the near future.</p><p>That’s how the idea for <strong>Omi</strong>, my AI parcel tracking agent, was born.</p><p>The goal was to help <strong>dropshippers, online retailers</strong>, and <strong>individuals</strong> easily track their parcels worldwide using a unified system.</p><p>As part of the project requirements, we were also asked to integrate our agents with <strong>Telex</strong> — an AI agent platform similar to <strong>Make</strong>, <strong>Beam</strong>, or <strong>Dust.it</strong>. You can think of Telex as a mix between <strong>Slack</strong> and <strong>AI agents</strong>, where agents can communicate and collaborate seamlessly.</p><p>Rather than dive deep into the A2A protocol here, I’ll cover that in a dedicated article soon. But for anyone curious, this <a href="https://fynix.dev/blog/a2a-python-fastapi">blog post by Fynix</a></p><h3>The Steps i took to accomplish the AI Agent:</h3><h4>Step 1: Getting Permission to Create an AI Agent on Telex</h4><p>The initial setup steps aren’t yet public, so I can’t share every detail. However, once I was approved to create an agent, I followed the process shown in my screenshots (not included here for privacy reasons).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h27aA-nLPOSUNX_s2OmAfw.png" /></figure><p><strong>STEP 2: Fill out the AI Agent form</strong></p><p>After clicking the <strong>“Add New”</strong> button on Telex, I was presented with a form to define my agent’s basic details — name, description, API endpoints, and permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WNujNVjIFg1kv3oBFXkpg.png" /></figure><h4>STEP 3: Configuring My Telex Agent to Communicate with My Remote Agent</h4><p>Once Omi was created, I clicked the <strong>“JSON”</strong> configuration button.<br> Here, I had to provide the Telex Agent with information on how to reach my remote backend — essentially linking both systems together via the <strong>A2A protocol</strong>.</p><p>On my end, I also configured Omi’s server (built with FastAPI) to accept and respond to A2A-formatted requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCyKYaUMmPWb03vhBhkEqQ.png" /></figure><h4>Testing Phase</h4><p>For testing, I used <strong>mock data</strong> that resembled what I would receive from a Universal Parcel Tracker API.</p><p>Instead of running everything locally, I chose to connect Telex directly to my development environment using <strong>ngrok</strong>. This created a secure public tunnel from Telex to my local FastAPI server.</p><p>By doing this, I could:</p><ul><li>Test how Telex communicated with my agent in real time.</li><li>Debug live issues early instead of discovering them only after deployment.</li></ul><p>Once everything worked perfectly, I deployed Omi to <strong>Railway</strong>, swapping my ngrok URL for the production one — and it continued to function smoothly.</p><p>Below is the parcel data I used for the demo video:</p><pre>Parcel ID: PKG002NG <br>Carrier: DHL</pre><h3>Future Improvements</h3><p>Due to time constraints, I wasn’t able to implement all the features I had planned. In shā’ Allāh, I intend to add the following soon:</p><ul><li><strong>Proactive decision-making:</strong><br> Collect customer details tied to parcels so Omi can automatically notify users if their deliveries are delayed — by email or even by phone.</li><li><strong>Priority handling:</strong><br> Allow users to set preferences like “prioritize parcel A over parcel B” or define what Omi should do if a parcel is late.</li></ul><h3>Why I Used Mock Data Instead of a Real API</h3><p>During testing, I realized a major limitation:<br> To test the agent with real data, I’d need to order an item online and get an actual tracking number — which wasn’t financially feasible for me at the time.</p><p>So instead, I decided to <strong>mock</strong> the API responses.</p><p>Using an <strong>LLM</strong>, I generated realistic tracking data for eight or more parcels and stored them in a database. This approach let me simulate real-world API calls without needing to purchase anything.</p><p>Despite being mock data, it provided the same logic flow as a real integration — and the entire agent ran successfully from end to end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RT85PnNd19y0dviHbqn6oQ.gif" /></figure><h3>Final Thoughts</h3><p>This project was more than just a coding challenge. It was a test of patience, problem-solving, and trust in the process.</p><p>From debugging connection issues in real time to working around financial limitations, every part of Omi’s development reminded me that <strong>innovation is born from persistence and belief</strong> — belief that if you do your best, Allah will handle the rest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce656f33ce2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Omi: The Failure, the Pivot, and the Creation of a YouTube Monetization Tool]]></title>
            <link>https://notsocomplex.medium.com/omi-the-failure-the-pivot-and-the-creation-of-a-youtube-monetization-tool-45476debf475?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/45476debf475</guid>
            <category><![CDATA[saas-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solo-founder-journey]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[youtube-monetization]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 18:30:52 GMT</pubDate>
            <atom:updated>2025-08-19T18:30:52.899Z</atom:updated>
            <content:encoded><![CDATA[<h4>A chronicle of my pivot from Blip to Omi</h4><p>This is a story, no this is my story of how i choose to chase an idea, and where it lead up to, in this short story I strive not to bore you, like every good story there’s always a beginning, a Genesis, so lets start there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4qgzG_FyLWlZ_fZKQlopA.png" /><figcaption><strong>Omi: The Failure, the Pivot, and the Creation of a YouTube Monetization Tool</strong></figcaption></figure><h4>🌱 The Genesis</h4><p>After finishing the foundational phase of my bootcamp, I stepped into the specialization track. I chose backend engineering over frontend — because I enjoyed building from the ground up.</p><p>Two months into the final phase, an email landed in my inbox: <em>“What will you build for your graduation project?”</em> At first, I shrugged it off. A minute turned into an hour, then a day, then a week. I had <strong>no idea</strong> what to build. But I did know one thing: I hated “simple” projects. The kind you can copy-paste from YouTube, Google, or an LLM prompt. My compass as an engineer always pointed toward one thing: <strong>Build to Impact</strong> (copyright, lol).</p><p>I had less than a month to build a “Toy Version.” The spark came while watching theRadBrad. In one of his playthroughs, he complained about YouTube removing his videos. And I thought: <em>What if creators could check their videos for violations before uploading them?</em></p><p>That was it. The idea. I hacked together a rough frontend with generative tools, then coded the backend myself with Node.js, Express, Multer, and Gemini. Was it perfect? Not even close. But it worked. I graduated.</p><p>After graduation, I was lost. Job hunting? Brutal. SaaS building? Tempting.Eventually, I decided to do both. That’s when it hit me: go back, strip everything down, and rebuild that scrappy graduation project from scratch.</p><h4>Blip its inception and DEATH</h4><p>Blip was what my project was supposed to look like if I had more time, not the toy it was, but eh, at least it was a proof of concept, so I got dirty, so I set up PostgreSQL. Used busboy to stream uploads. Learned JPEG streams are a nightmare (headers, start, end markers). So I switched to full video uploads. Built a file manager to separate user uploads. Used FFMPEG to extract scenes, then ran DHash to remove duplicates. Batched everything into one request with a queue. It was a wild ride: async, queuing, edge cases. But in the end, it felt real. Not just sexy for recruiters — real, and oh i added JWT token and a refresh token for when the JWT token expires.</p><p>So they day came when i decided it was time to share or tell the internet about what I had built and well, i share it on sub reddits, facebook groups,and i even made a survey, everything was ready, i typed on the message and hit send, and after days and weeks, well, nobody gave a DAMN.</p><h4>A Rebirth: The Pivot Blip becomes Omi</h4><p>When nobody said a word — and moderators even started removing my posts — I was stumped. I had poured myself into Blip, but it was like shouting into the void. So I slept on it. And I slept on it again.</p><p>Alḥamdulillāh, one morning I woke up with a realization: maybe I was solving the wrong problem. YouTube copyright issues are real, yes, but most creators either <em>learn to work around them</em> or eventually reach a stage where their videos are rarely removed.</p><p>The real pain point? <strong>Monetization.<br></strong> That’s where creators truly bleed. You can have a video up, but if it’s demonetized, your income is gone. And with YouTube recently cracking down harder on AI content (forcing disclaimers and penalizing those who don’t comply), I realized this is the <em>perfect moment</em> to build something different.</p><p>So Blip pivoted into what I now call <strong>Omi</strong> — a YouTube monetization tool. Its sole purpose:</p><ul><li>Help creators identify <em>where</em> in their video or audio they might get demonetized.</li><li>Safeguard their income streams by catching issues before upload.</li><li>Even analyze already-published videos to detect hidden leaks.</li></ul><p>To test whether this problem was real, I performed my own “research.” I dug into the tools out there. Most were surface-level — either generic copyright checkers or analytics dashboards. None truly focused on monetization risks. Here’s the summary:</p><h3>⚔️ Omi vs. The Competition</h3><p><em>(Positioning: Omi = </em><strong><em>proactive revenue shield</em></strong><em> | Others = reactive tools)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVgZB4aFikohokVB7K2tQg.png" /></figure><h4>🚀 What next</h4><p>In retrospect, I learned that marketing is a truly hard thing, and it’s the heart of every successful company. A big shout-out to all the marketers who sell what is beneficial to the world.</p><p>Now that I’ve pivoted, Omi has become even more technically demanding. This means I’ll have to push the bar higher, and I’m very much ready for it. But right now, I’d love to hear some feedback.</p><p>If you’re a YouTube creator, would a tool like Omi actually help you protect your income? What’s your #1 pain point when it comes to monetization? You can find me on X here:<a href="https://x.com/KrazyGenus"> https://x.com/KrazyGenus</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45476debf475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I No Longer Trust Stateless JWT — and What I’m Doing About It]]></title>
            <link>https://notsocomplex.medium.com/why-i-no-longer-trust-stateless-jwt-and-what-im-doing-about-it-932f21a7d062?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/932f21a7d062</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[building-in-public]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devlog]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 16:46:37 GMT</pubDate>
            <atom:updated>2025-06-13T16:46:37.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I No Longer Trust Stateless JWT — and What I’m Doing About It</h3><h4>By Muhammad Hasim</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*POVdvBqqeYNCODQ0" /><figcaption>Photo by <a href="https://unsplash.com/@scottwebb?utm_source=medium&amp;utm_medium=referral">Scott Webb</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As I continued building my project, <strong>Blip</strong>, I implemented a tried-and-true method of authentication using JWT (JSON Web Tokens). At first glance, it seemed like the perfect solution: secure, stateless, and scalable. But, as I dug deeper into the nuances of real-world authentication systems, I realized something. Something critical was missing.</p><p>I needed more than just a simple stateless JWT flow. My system required <strong>control</strong>, <strong>security</strong>, and <strong>flexibility</strong>. That’s when I began rethinking my approach.</p><h3>🚫 The Limitation of Stateless JWT</h3><p>Here’s the standard JWT flow:</p><ol><li>A user signs up, their password is hashed.</li><li>On login, their credentials are verified.</li><li>A JWT is issued with the user’s userId and email encoded inside.</li><li>The client stores the JWT and sends it back with each request.</li><li>Middleware verifies the JWT and grants access to protected routes.</li></ol><p><strong>Sounds great, right?</strong> It’s fast and scalable — but I felt something was missing.</p><p>What happens when:</p><ul><li>A user’s JWT is stolen?</li><li>I need to block a user across all devices?</li><li>I want to invalidate a session without waiting for the token’s expiration?</li></ul><p>In a <strong>stateless JWT system</strong>, there’s no built-in way to revoke a token until it expires. Once it’s issued, it’s valid until its natural end — and that’s where the problem lies.</p><h3>✅ Adding Redis for Session Tracking</h3><p>In order to make my system more secure and manageable, I decided to add <strong>Redis</strong> as a session store. Here’s how I enhanced the JWT flow with Redis:</p><ol><li><strong>Login</strong>:</li></ol><ul><li>A user logs in, and a JWT is issued as usual.</li><li>But now, I also store a small session object in <strong>Redis</strong>, keyed by their userId (session:user:123).</li></ul><ol><li><strong>Redis Session</strong>:<br> The session object contains relevant user information such as:</li></ol><pre>{   &quot;email&quot;: &quot;user@example.com&quot;,   &quot;isBanned&quot;: false,   &quot;lastLogin&quot;: &quot;2025-06-13T12:00:00Z&quot; }</pre><ol><li><strong>Request</strong>:</li></ol><ul><li>The user accesses a protected route, sending the JWT in the headers.</li><li>Middleware verifies the JWT, then uses the userId from the token to <strong>query Redis</strong> and check if the session exists.</li><li>If the session is missing or the user is banned, access is denied.</li><li>If the session is found and valid, the user is granted access to the route.</li></ul><p>This system gives me the flexibility to:</p><ul><li><strong>Revoke sessions</strong> by deleting the Redis key.</li><li><strong>Monitor sessions</strong> in real-time.</li><li><strong>Track user activity</strong> with added metadata.</li></ul><h3>🧠 Why This Matters</h3><p>JWT is a powerful tool for authentication, but <strong>stateless JWT systems are not enough</strong> for serious, production-level applications. Adding Redis to the flow allows me to manage sessions in a way that JWT alone cannot.</p><p>By implementing session management through Redis, I’m able to:</p><ul><li><strong>Track and control active sessions</strong> (especially useful for multi-device users).</li><li><strong>Immediately revoke sessions</strong> if a user logs out, changes their password, or is banned.</li><li>Have more granular <strong>control over user access</strong> with added session data (e.g., roles, flags, and last login time).</li></ul><p>This shift in my thinking also brought me closer to understanding <strong>dependency injection</strong> in backend systems, especially as I integrate more complex patterns. The connection between <strong>Express.js middleware</strong> and <strong>FastAPI’s dependency injection</strong> is clearer than ever.</p><h3>⚙️ What’s Next for My Backend?</h3><p>By integrating Redis into my authentication flow, I’ve taken a step toward building a more robust and secure system. I’ve learned that <strong>backend engineering</strong> isn’t just about writing code that works — it’s about anticipating real-world challenges like token expiration, session management, and user security.</p><p>And as I continue to build Blip, I keep reminding myself that backend systems should evolve as we learn more. The journey is far from over, but I’m excited to keep improving, <strong>one step at a time</strong>.</p><h3>🔗 Conclusion: Why You Should Rethink JWT and Redis</h3><p>If you’re working on a project where security and session management matter, I highly encourage you to reconsider the <strong>stateless nature of JWT</strong>. Adding a session store like Redis doesn’t complicate the system — it enhances it.</p><ul><li><strong>Global session management</strong> becomes possible.</li><li><strong>Revoke or update sessions instantly</strong>.</li><li>Track, monitor, and enforce access control seamlessly.</li></ul><p>As backend engineers, we’re not just solving for today. We’re building for tomorrow.</p><h3>💬 Let’s Connect</h3><p>If you’re building something similar or would like to share your thoughts on JWT, Redis, or any other topic, feel free to connect with me on LinkedIn. I’m always happy to exchange ideas with fellow builders.</p><p><strong>Muhammad Hasim</strong><br> Backend Engineer &amp; Builder of Blip<br> “Build to Impact”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=932f21a7d062" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ FastAPI Path Parameters & Enums: How McDonald’s and Mortal Kombat Taught Me API Design [Part 2]]]></title>
            <link>https://notsocomplex.medium.com/fastapi-path-parameters-enums-how-mcdonalds-and-mortal-kombat-taught-me-api-design-part-2-c195c88cf234?source=rss-2009fe82093e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c195c88cf234</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devotional]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Muhammad Hasim]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 08:19:19 GMT</pubDate>
            <atom:updated>2025-06-01T08:19:19.114Z</atom:updated>
            <content:encoded><![CDATA[<h4>A FastAPI tutorial: How to use path parameters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KE1ZHoaO0ZBHCPqM" /><figcaption>Photo by <a href="https://unsplash.com/@romulusprince?utm_source=medium&amp;utm_medium=referral">Wajih Ghali</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to another FastAPI tutorial in our series!</p><p>Last we met we create a simple endpoin that returned a JSON response.</p><p>Today, we’ll explore how to make our API flexible and user-friendly by using <strong>path parameters</strong> and <strong>Enums</strong>. But instead of a boring use case, let’s spice it up…</p><p>The <strong>API path</strong> is the main point of interaction between us (the backend devs) and the outside world — whether that’s frontend code, mobile apps, or curious hackers playing with Postman.</p><p>So if we want to make our API <em>flexible</em>, we need to allow users to <strong>pass in extra information directly through the URL</strong>.</p><p>Let’s take our example from earlier:</p><pre>@app.get(&quot;/player/{player_name}&quot;)<br>def play_info(player_name: str):<br>    return {&quot;message&quot;: f&quot;{player_name} enters the arena!&quot;}</pre><p>Here, /player/{player_name} is a <strong>path parameter</strong>.</p><p>So calling /player/pewdiepie returns.</p><pre>{ &quot;message&quot;: &quot;pewdiepie enters the arena!&quot; }</pre><p>What that means is: instead of making users send complex data in the body or query strings, we let them <em>talk to the API naturally</em>, like:</p><pre>/player/pewdiepie</pre><p>or</p><pre>/player/coryxkenshin</pre><p>It’s clean. It’s readable. It works like a Google search — but structured.</p><h3>🔀 Multiple Path Parameters</h3><p>Want to add more flavor? Stack your parameters:</p><pre>@app.get(&quot;/player/{player_name}/score/{score}&quot;)<br>def player_score(player_name: str, score: int):<br>    return {&quot;player&quot;: player_name, &quot;score&quot;: score}</pre><p>Example request:<br> /player/markiplier/score/9999</p><p>Response:</p><pre>{<br>  &quot;player&quot;: &quot;markiplier&quot;,<br>  &quot;score&quot;: 9999<br>}</pre><p>But — <strong>REMEMBER TO REMEMBER</strong> — path parameters are <em>very</em> flexible. If you choose to support them, users can pass in <strong>whatever they want</strong> and hit your endpoint.</p><p>That sounds great… but it comes with a catch.</p><p>If you don’t place guardrails, your logic could break — or worse, return garbage.</p><p>That’s where <strong>Enums</strong> come in. They allow you to <strong>restrict inputs</strong> to a fixed set of valid choices, like a menu. We’ll cover that next.</p><p>For now, just remember this rule of thumb:</p><blockquote><em>Whatever path parameters you support, make sure your logic actually supports them.</em></blockquote><h3>⚔️ Enter Enum: Controlling the Chaos</h3><p>We don’t want <strong>random junk</strong> entering our API like some uninvited button-masher in Mortal Kombat.</p><p>So what do we do?</p><p>We bring in a <strong>sentinel</strong> — something that stands guard and says,</p><blockquote><em>“Only the legends may pass.”</em></blockquote><p>That’s where Enum comes in.</p><p>It lets us <strong>lock down</strong> the path to <strong>only allow specific values</strong> — in this case, legendary gaming channels:</p><pre>from enum import Enum<br>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>class GameChannel(str, Enum):<br>    pewdiepie = &quot;pewdiepie&quot;<br>    coryxkenshin = &quot;coryxkenshin&quot;<br>    jacksepticeye = &quot;jacksepticeye&quot;<br><br>@app.get(&quot;/champion/{channel}&quot;)<br>def champion_entry(channel: GameChannel):<br>    return {&quot;message&quot;: f&quot;{channel.value} is a worthy combatant!&quot;}</pre><p>✅ <strong>Valid:</strong></p><pre>/champion/pewdiepie  <br>/champion/coryxkenshin</pre><p>❌ <strong>Invalid:</strong></p><pre>/champion/randomkid  <br># → 422 error: &quot;value is not a valid enumeration member&quot;</pre><p>With Enum, you’re telling FastAPI:</p><blockquote><em>“If it’s not on this list, it’s not getting in.”</em></blockquote><p>It’s like a <strong>guest list</strong> for your endpoints. Clean, secure, and intentional.</p><h3>🍔 By Way of Analogy</h3><p>Let’s imagine it’s 6PM. You just got out of class or work, and you’re <strong>dead hungry</strong>.</p><p>A normal, functional human would begin to <strong>search for food</strong>. Say you’re craving junk food, and the closest place is McDonald’s (or maybe Subway if you’re feeling <em>slightly</em> responsible).</p><p>Now think of this:<br> Your <strong>walk or drive</strong> to McDonald’s is like a <strong>request</strong>.<br> The <strong>address</strong> where the McDonald’s sits? That’s the <strong>API path</strong> — the endpoint you’re trying to reach.</p><p>But you don’t just walk in and get food instantly.<br> You get to the counter (or kiosk), and you still have to say what you want.</p><p>So you make <strong>another request</strong>:</p><blockquote><em>“A large burger with Pepsi, please.”</em></blockquote><p>That’s your <strong>parameter</strong> — the extra info you’re passing along with your request. You’re not just saying “feed me,” you’re saying <em>what kind of</em> food you want.</p><p>So to recap:</p><ul><li>🛣️ The <em>drive to McDonald’s</em> = the API call</li><li>📍 The <em>McDonald’s address</em> = the endpoint (/mcdonalds)</li><li>🍔 The <em>order you place</em> = the parameters (/mcdonalds/{food_type}/{drink_type})</li></ul><p>FastAPI lets you build <strong>both parts</strong> of that journey — the endpoint, and the specific options someone can ask for. Whether it’s burgers, drinks, or YouTubers.</p><p>And if we want even more flexibility, we can <strong>nest more parameters</strong>, or even <strong>restrict their values</strong> using Enums.</p><h3>🏁 Wrapping Up</h3><p>In this tutorial, we saw how to make our FastAPI endpoints smarter, safer, and smoother:</p><ul><li>✅ <strong>Path parameters</strong> let users speak to your API naturally.</li><li>🔐 <strong>Enums</strong> protect your routes from random noise and keep your logic clean.</li><li>🎮 And analogies? Well… turns out McDonald’s and Mortal Kombat have a lot to teach us about backend development.</li></ul><p>FastAPI gives you power, but it’s on you to <strong>use it with precision</strong>.</p><p>In the next post, we’ll take it further — tackle query parameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c195c88cf234" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>