<?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 Ayoub Idel on Medium]]></title>
        <description><![CDATA[Stories by Ayoub Idel on Medium]]></description>
        <link>https://medium.com/@pskshksh?source=rss-78511046581e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Ayoub Idel on Medium</title>
            <link>https://medium.com/@pskshksh?source=rss-78511046581e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:35:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pskshksh/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[Your Startup Doesn’t Need Kafka. Here’s What It Actually Needs.]]></title>
            <link>https://medium.com/@pskshksh/your-startup-doesnt-need-kafka-here-s-what-it-actually-needs-2b74fbe864c5?source=rss-78511046581e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b74fbe864c5</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Ayoub Idel]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 09:47:04 GMT</pubDate>
            <atom:updated>2026-02-03T15:43:20.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*texQdYhXzB4m4YRtXORQeg.png" /></figure><p>Every week, I see another team spin up Kafka for a workload that could run on a napkin.</p><p>Not because they need it. Because that’s what the blog posts told them to do.</p><p>Today I want to show you something different. I’m going to explain how message systems actually work under the hood, why <em>Kafka</em> exists, and when your trusty <em>Postgres</em> database is more than enough.</p><p>By the end, you’ll be able to make this decision yourself — with actual understanding, not just cargo-culted best practices.</p><h3>How I Discovered This</h3><p>I didn’t come to this conclusion from reading blog posts. I learned it the hard way → in production.</p><p>I was architecting a feedback management platform. The kind where companies collect customer feedback from multiple channels (message sent, delivered, read, optin, optout, …), analyze sentiment, route issues to the right place, and track everything.</p><p>We were handling <strong>5,000 to 10,000 requests per second</strong>. Real traffic. Real scale.</p><p>My first instinct? Kafka. Obviously. That’s what you use for this kind of volume, right?</p><p>But then I started thinking about what we actually needed. We needed to queue feedback items for processing. We needed multiple services to react to new feedback events. We needed durability and replay capability.</p><p>All things <strong>Kafka</strong> does. All things <strong>Postgres</strong> does too.</p><p>So I tried something different. I built it on Postgres with proper partitioning. And it worked. Not “barely survived” worked — it worked <em>well</em>. Low latency, high throughput, zero drama.</p><p>The beautiful part? Once the architecture worked for one client, scaling to N clients was just duplication. Same pattern, same tables, same queries. Client 2 gets their own partition. Client 50 gets their own partition. The system grows horizontally without changing the core design.</p><p>That experience changed how I think about infrastructure decisions.</p><h3>First, Let’s Get Clear on What We’re Building</h3><p>Before we talk solutions, let’s talk problems. There are two fundamentally different patterns here, and people mix them up constantly.</p><h3>Pattern 1: The Queue</h3><p>A queue is like a to-do list. Tasks go in, workers grab them one at a time, and once a task is done — it’s gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*4QKc9Mfwbe5EbKGpTijYfA.png" /></figure><p><strong>Real examples:</strong></p><ul><li>Send this email</li><li>Process this payment</li><li>Resize this image</li><li>Generate this PDF</li></ul><p>The key insight: <strong>one job, one worker, then it’s done.</strong></p><h3>Pattern 2: The Pub/Sub (Publish-Subscribe)</h3><p>Pub/sub is like a newspaper. Publishers write articles, and <em>multiple</em> subscribers all read the same content. The articles stick around — they don’t vanish after one person reads them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*GbRt7I8p6SInIJEfiUhNOQ.png" /></figure><ul><li>User clicked “buy” → notify inventory, notify shipping, notify analytics, notify fraud detection</li><li>Sensor reading arrived → store in database, update dashboard, check for anomalies</li><li>Order placed → email service, SMS service, and analytics all need to know</li></ul><p>The key insight: <strong>one event, many readers, data sticks around.</strong></p><h3>How Kafka Solves Pub/Sub</h3><p>Kafka is essentially a <strong>distributed append-only log</strong>. That sounds fancy, but the concept is dead simple.</p><p>Imagine a notebook where you can only write on the next blank line. You can never erase. You can never insert in the middle. Just append, append, append.</p><pre>┌──────────────────────────────────────────────────────────┐<br>│                     KAFKA TOPIC                          │<br>│                                                          │<br>│  Partition 0        Partition 1        Partition 2       │<br>│  ┌───┬───┬───┐     ┌───┬───┬───┐     ┌───┬───┬───┐       │<br>│  │ 0 │ 1 │ 2 │     │ 0 │ 1 │ 2 │     │ 0 │ 1 │ 2 │       │<br>│  ├───┼───┼───┤     ├───┼───┼───┤     ├───┼───┼───┤       │<br>│  │ 3 │ 4 │ 5 │     │ 3 │ 4 │ 5 │     │ 3 │ 4 │ 5 │       │<br>│  ├───┼───┼───┤     ├───┼───┼───┤     ├───┼───┼───┤       │<br>│  │ 6 │ 7 │...│     │ 6 │ 7 │...│     │ 6 │ 7 │...│       │<br>│  └───┴───┴───┘     └───┴───┴───┘     └───┴───┴───┘       │<br>│       ▲                 ▲                 ▲              │<br>│       │                 │                 │              │<br>│   offset=7          offset=7          offset=7           │<br>│   (newest)          (newest)          (newest)           │<br>│                                                          │<br>│  Each partition is an independent ordered log            │<br>│  Messages get an &quot;offset&quot; number (0, 1, 2, 3...)         │<br>│  Consumers track where they left off by offset           │<br>│                                                          │<br>└──────────────────────────────────────────────────────────┘</pre><p><strong>Why partitions?</strong> Parallelism. If you have 3 partitions, you can have 3 consumers reading simultaneously — each handling one partition.</p><p><strong>Why offsets?</strong> Replayability. Consumer crashed? No problem. It remembers “I was at offset 47” and picks up right where it left off.</p><p>This design is brilliant for massive scale. But it comes with baggage: you need to run a cluster, manage ZooKeeper (or KRaft), handle rebalancing, deal with broker failures…</p><p>The question is: do you actually need any of that?</p><h3>The Postgres Alternative: Same Concepts, Simpler Stack</h3><p>Here’s the thing — those Kafka concepts aren’t magic. They’re just data structures. And Postgres can do data structures.</p><h3>Building a Log in Postgres</h3><p>A Kafka partition is just an ordered, append-only sequence of messages. In Postgres:</p><pre>CREATE TABLE events (<br>    offset      BIGSERIAL PRIMARY KEY,  -- auto-incrementing = append-only ordering<br>    payload     JSONB NOT NULL,<br>    created_at  TIMESTAMPTZ DEFAULT now()<br>);</pre><pre>-- Writing is just an INSERT<br>INSERT INTO events (payload) VALUES (&#39;{&quot;user&quot;: 123, &quot;action&quot;: &quot;click&quot;}&#39;);</pre><pre>-- The offset is assigned automatically: 1, 2, 3, 4...</pre><p>That’s it. That’s a log.</p><h3>Tracking Consumer Progress</h3><p>Kafka consumers remember their offset. So can we:</p><pre>CREATE TABLE consumer_progress (<br>    consumer_group  TEXT PRIMARY KEY,<br>    last_offset     BIGINT NOT NULL DEFAULT 0<br>);</pre><pre>-- Consumer &quot;analytics&quot; picks up where it left off<br>SELECT * FROM events <br>WHERE offset &gt; (SELECT last_offset FROM consumer_progress WHERE consumer_group = &#39;analytics&#39;)<br>ORDER BY offset<br>LIMIT 100;</pre><pre>-- After processing, update the bookmark<br>UPDATE consumer_progress SET last_offset = 147 WHERE consumer_group = &#39;analytics&#39;;</pre><p>Now you have independent consumer groups, each tracking their own position.</p><h3>The Full Picture</h3><pre>┌────────────────────────────────────────────────────────────────┐<br>│                    POSTGRES &quot;KAFKA&quot;                            │<br>│                                                                │<br>│  ┌─────────────────────────────────────────────────────────┐   │<br>│  │                    events table                         │   │<br>│  │  ┌────────┬─────────────────────────┬───────────────┐   │   │<br>│  │  │ offset │         payload         │  created_at   │   │   │<br>│  │  ├────────┼─────────────────────────┼───────────────┤   │   │<br>│  │  │   1    │ {&quot;user&quot;:1,&quot;act&quot;:&quot;buy&quot;}  │ 2024-01-01... │   │   │<br>│  │  │   2    │ {&quot;user&quot;:2,&quot;act&quot;:&quot;view&quot;} │ 2024-01-01... │   │   │<br>│  │  │   3    │ {&quot;user&quot;:1,&quot;act&quot;:&quot;review&quot;}│ 2024-01-01.. │   │   │<br>│  │  │  ...   │          ...            │     ...       │   │   │<br>│  │  └────────┴─────────────────────────┴───────────────┘   │   │<br>│  └─────────────────────────────────────────────────────────┘   │<br>│                              │                                 │<br>│         ┌────────────────────┼────────────────────┐            │<br>│         ▼                    ▼                    ▼            │<br>│  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐   │<br>│  │  Analytics      │ │   Search        │ │   Alerts        │   │<br>│  │  last_off=47    │ │   last_off=52   │ │   last_off=38   │   │<br>│  └─────────────────┘ └─────────────────┘ └─────────────────┘   │<br>│                                                                │<br>│  Each consumer group tracks its own offset                     │<br>│  They can read at different speeds, replay history, etc.       │<br>│                                                                │<br>└────────────────────────────────────────────────────────────────┘</pre><h3>The Partitioning Strategy That Made It Work</h3><p>Here’s what I learned from the feedback platform: <strong>partitioning is everything</strong>.</p><p>When you’re handling thousands of requests per second, a single table becomes a bottleneck. But with smart partitioning, Postgres handles it beautifully.</p><pre>┌────────────────────────────────────────────────────────────────┐<br>│                   PARTITIONED ARCHITECTURE                     │<br>│                                                                │<br>│   Incoming Events (5k-10k/sec)                                 │<br>│          │                                                     │<br>│          ▼                                                     │<br>│   ┌─────────────┐                                              │<br>│   │   Router    │  (partition by client_id, tenant, etc.)      │<br>│   └──────┬──────┘                                              │<br>│          │                                                     │<br>│    ┌─────┼─────┬─────────┬─────────┐                           │<br>│    ▼     ▼     ▼         ▼         ▼                           │<br>│ ┌──────┐┌──────┐┌──────┐┌──────┐┌──────┐                       │<br>│ │Part 1││Part 2││Part 3││Part 4││Part N│                       │<br>│ │Client││Client││Client││Client││Client│                       │<br>│ │  A   ││  B   ││  C   ││  D   ││  ... │                       │<br>│ └──────┘└──────┘└──────┘└──────┘└──────┘                       │<br>│                                                                │<br>│   Each partition = independent write path                      │<br>│   No lock contention between clients                           │<br>│   Linear horizontal scaling                                    │<br>│                                                                │<br>└────────────────────────────────────────────────────────────────┘</pre><p>The insight that changed everything for me:</p><p><strong>If it works for one client, it works for N clients.</strong></p><p>Each client gets their own partition (or set of partitions). They don’t compete for locks. They don’t step on each other. Adding client #51 is the same as adding client #2 — just duplicate the pattern.</p><pre>-- Partitioned events table<br>CREATE TABLE events (<br>    id          BIGSERIAL,<br>    client_id   INT NOT NULL,<br>    offset      BIGINT NOT NULL,<br>    payload     JSONB NOT NULL,<br>    created_at  TIMESTAMPTZ DEFAULT now(),<br>    PRIMARY KEY (client_id, id)<br>) PARTITION BY HASH (client_id);</pre><pre>-- Create partitions<br>CREATE TABLE events_p0 PARTITION OF events FOR VALUES WITH (MODULUS 8, REMAINDER 0);<br>CREATE TABLE events_p1 PARTITION OF events FOR VALUES WITH (MODULUS 8, REMAINDER 1);<br>CREATE TABLE events_p2 PARTITION OF events FOR VALUES WITH (MODULUS 8, REMAINDER 2);<br>-- ... and so on</pre><p>This is exactly what Kafka does with partitions — I just did it in Postgres.</p><h3>Building a Queue in Postgres</h3><p>Queues are even simpler. The secret weapon: SELECT FOR UPDATE SKIP LOCKED.</p><p>This SQL command does exactly what a queue needs:</p><ol><li>Find an available job</li><li>Lock it so no other worker can grab it</li><li>Skip any jobs that are already locked</li></ol><pre>CREATE TABLE jobs (<br>    id          BIGSERIAL PRIMARY KEY,<br>    payload     JSONB NOT NULL,<br>    status      TEXT DEFAULT &#39;pending&#39;,<br>    created_at  TIMESTAMPTZ DEFAULT now()<br>);</pre><pre>-- Worker grabs the next available job (atomically!)<br>BEGIN;</pre><pre>SELECT * FROM jobs <br>WHERE status = &#39;pending&#39;<br>ORDER BY id <br>FOR UPDATE SKIP LOCKED <br>LIMIT 1;</pre><pre>-- Process the job... then mark it done<br>UPDATE jobs SET status = &#39;completed&#39; WHERE id = 123;</pre><pre>COMMIT;</pre><pre>┌────────────────────────────────────────────────────────────┐<br>│                   POSTGRES QUEUE                           │<br>│                                                            │<br>│  ┌──────────────────────────────────────────────────────┐  │<br>│  │                     jobs table                       │  │<br>│  │  ┌────┬───────────────────┬──────────┬────────────┐  │  │<br>│  │  │ id │      payload      │  status  │   worker   │  │  │<br>│  │  ├────┼───────────────────┼──────────┼────────────┤  │  │<br>│  │  │  1 │ {send email to A} │ complete │     -      │  │  │<br>│  │  │  2 │ {send email to B} │ 🔒LOCKED │  Worker 1  │  │  │<br>│  │  │  3 │ {send email to C} │ 🔒LOCKED │  Worker 2  │  │  │<br>│  │  │  4 │ {send email to D} │ pending  │     -      │  │  │  ◄─ Next available<br>│  │  │  5 │ {send email to E} │ pending  │     -      │  │  │<br>│  │  └────┴───────────────────┴──────────┴────────────┘  │  │<br>│  └──────────────────────────────────────────────────────┘  │<br>│                                                            │<br>│  SKIP LOCKED means Worker 3 will grab job #4,              │<br>│  not wait for job #2 or #3 to finish                       │<br>│                                                            │<br>└────────────────────────────────────────────────────────────┘</pre><p>No RabbitMQ. No Redis. No SQS. Just SQL.</p><h3>“Cool Theory. Does It Actually Work?”</h3><p>Beyond my own production experience, benchmarks confirm this works at serious scale.</p><h3>Pub/Sub Performance</h3><p>Setup Write Speed Read Speed Latency (p99) Small (4 CPU, single node) 4.8 MB/s 24.6 MB/s 60ms Replicated (3 nodes, cross-AZ) 4.9 MB/s 24.5 MB/s 186ms Large (96 CPU) 238 MB/s 1.16 GB/s 853ms</p><p>That small 4-CPU setup handles what <strong>55% of Kafka deployments actually process</strong>.</p><p>The replicated setup gives you real durability — data survives if a machine dies. And the cost savings compared to managed Kafka services? <strong>Massive.</strong> We’re talking 4–5x cheaper, sometimes more.</p><h3>Queue Performance</h3><p>Setup Throughput Latency (p99) Small (4 CPU) 2,900 jobs/sec 17ms Replicated (3 nodes) 2,400 jobs/sec 920ms Large (96 CPU) 20,000 jobs/sec 930ms</p><p><strong>2,900 jobs per second</strong> on a tiny machine. That’s 250 million jobs per day. How many background jobs does your app actually run?</p><h3>When Postgres Makes Sense</h3><p>✅ Your throughput is under 50 MB/s (that’s most companies) it depends on test and machines but 50 sounds fair for me</p><p>✅ You already run Postgres (no new ops burden)</p><p>✅ You want to query messages with SQL (debugging heaven)</p><p>✅ You need to join events with other business data</p><p>✅ Your team knows SQL better than Kafka internals</p><p>✅ You value simplicity over theoretical scalability</p><p><strong>Consider Kafka when:</strong></p><p>⚠️ You’re pushing hundreds of MB/s consistently</p><p>⚠️ You need the Kafka Connect ecosystem (100+ connectors)</p><p>⚠️ You have dedicated infra teams for distributed systems</p><p>⚠️ You’re already committed to the Kafka ecosystem</p><h3>The Hidden Cost Nobody Talks About</h3><p>Every new system in your stack has a tax:</p><pre>┌────────────────────────────────────────────────────────────┐<br>│                                                            │<br>│               THE COMPLEXITY TAX                           │<br>│                                                            │<br>│   ┌────────────────────────────────────────────────────┐  │<br>│   │                                                    │  │<br>│   │    New System Added                                │  │<br>│   │         │                                          │  │<br>│   │         ├──► Learn configuration                   │  │<br>│   │         ├──► Set up monitoring                     │  │<br>│   │         ├──► Create alerting rules                 │  │<br>│   │         ├──► Write runbooks                        │  │<br>│   │         ├──► Build deployment pipelines            │  │<br>│   │         ├──► Handle upgrades                       │  │<br>│   │         ├──► Debug production issues at 3am        │  │<br>│   │         ├──► Train the team                        │  │<br>│   │         ├──► Maintain client libraries             │  │<br>│   │         └──► Keep up with ecosystem changes        │  │<br>│   │                                                    │  │<br>│   │    Time cost: 2-6 months to &quot;production ready&quot;     │  │<br>│   │    Ongoing cost: Forever                           │  │<br>│   │                                                    │  │<br>│   └────────────────────────────────────────────────────┘  │<br>│                                                            │<br>└────────────────────────────────────────────────────────────┘</pre><p>If you already run Postgres, you’ve already paid this tax. Adding pub/sub or queue functionality is just… SQL.</p><p>If you add Kafka, you pay the tax again. For a fresh system. That your team doesn’t know yet.</p><p>Sometimes that’s worth it. Usually it’s not.</p><h3>“But What If We Go Viral?”</h3><p>I love this objection. Let me address it directly.</p><p><strong>Fact 1: OpenAI still uses unsharded Postgres.</strong></p><p>They went from zero to 100 million users faster than any company in history. Their infra team says: “If you are building a startup with read-heavy workloads, just start with Postgres.”</p><p><strong>Fact 2: You have years to migrate.</strong></p><p>Even at 100% year-over-year growth (which is exceptional), it takes 3.3 years to 10x your scale. At 50% growth? 5.7 years. You’ll have changed jobs twice by then.</p><p><strong>Fact 3: Premature optimization is expensive.</strong></p><p>Every hour spent setting up Kafka “for scale” is an hour not spent on features, customers, or actual problems. The best infrastructure is the one that lets you focus on your real job.</p><h3>The Bottom Line</h3><p>Kafka is a brilliant piece of engineering. For the right problems, at the right scale, it’s exactly what you need.</p><p>But most of us don’t have those problems.</p><p>Most of us have a few thousand events per second. Maybe a few hundred background jobs per minute. Maybe some basic fan-out to a handful of services.</p><p>For that? Your database is already running. It already has transactions, durability, monitoring, backups, and a query language your team actually knows.</p><p>I learned this building a feedback platform handling 5k-10k requests per second. With the right partitioning strategy, Postgres didn’t just survive — it thrived. And when we added more clients, we just duplicated the pattern.</p><p>Don’t add complexity because blog posts told you to. Add complexity when the pain forces you to.</p><p>Until then: just use Postgres.</p><h3>Quick Reference: The Code</h3><p><strong>Pub/Sub — Publishing:</strong></p><pre>INSERT INTO events (payload) VALUES (&#39;{&quot;event&quot;: &quot;user_signup&quot;, &quot;user_id&quot;: 123}&#39;);</pre><p><strong>Pub/Sub — Consuming:</strong></p><pre>SELECT * FROM events WHERE offset &gt; $last_seen ORDER BY offset LIMIT 100;</pre><p><strong>Queue — Adding a job:</strong></p><pre>INSERT INTO jobs (payload) VALUES (&#39;{&quot;task&quot;: &quot;send_email&quot;, &quot;to&quot;: &quot;user@example.com&quot;}&#39;);</pre><p><strong>Queue — Processing a job:</strong></p><pre>BEGIN;<br>SELECT * FROM jobs WHERE status = &#39;pending&#39; FOR UPDATE SKIP LOCKED LIMIT 1;<br>-- do work<br>UPDATE jobs SET status = &#39;done&#39; WHERE id = $id;<br>COMMIT;</pre><p>That’s it. That’s the whole thing.</p><p><em>Have you tried this approach? Did it work? Did it fail spectacularly? I’d genuinely love to hear your war stories in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b74fbe864c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Banishing the Ghosts in Your Go Code: A Friendly Guide to Eliminating Dead Code]]></title>
            <link>https://medium.com/@pskshksh/banishing-the-ghosts-in-your-go-code-a-friendly-guide-to-eliminating-dead-code-bfd8f3b0984f?source=rss-78511046581e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfd8f3b0984f</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ayoub Idel]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 13:01:50 GMT</pubDate>
            <atom:updated>2024-02-13T13:01:50.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*EiaioP5BOqk3Rvf5.jpg" /><figcaption>Gopher ghost</figcaption></figure><p>In the enchanting world of software development, where lines of code are woven together to bring applications to life, there lurks a less visible, often ignored presence: dead code. Like the forgotten rooms of an old mansion, dead code sits unused, gathering dust in the corners of your Go projects. Today, let’s embark on a light-hearted journey to uncover these hidden nooks and bid farewell to the ghostly code that haunts our repositories, with a little help from a tool named deadcode.</p><h3>What is Dead Code?</h3><p>Imagine you’re a novelist, and over the years, you’ve drafted chapters that never made it into your published books. These drafts, while once full of potential, now serve no purpose other than taking up space on your shelf. In the realm of Go programming, dead code is similar to these unused drafts. It refers to functions and methods in your codebase that, despite their presence, never get called or executed in any running version of your program.</p><h3>Introducing Your Guide: The deadcode Tool</h3><p>To aid in our quest, we have a trusty guide: the deadcode tool. This tool is like a knowledgeable librarian who can sift through the vast library of your code and point out which parts haven&#39;t been looked at in years. It&#39;s designed to help Go developers identify and eliminate dead code, making their codebases cleaner, lighter, and more maintainable.</p><h3>Getting Started with deadcode</h3><p>To enlist the help of this guide, you simply need to install it and ask for its wisdom. Here’s how you can do that:</p><pre>$ go install golang.org/x/tools/cmd/deadcode@latest</pre><p>Once installed, you can ask deadcode to survey your code like so:</p><pre>$ deadcode -help</pre><p>The command above will introduce you to how deadcode operates, guiding you on your quest to identify those forgotten functions.</p><h3>A Simple Tale</h3><p>Let’s illustrate the problem with a story. Imagine you’re crafting a magical spell (a Go program) that greets the world. Along the way, you also create a spell for saying goodbye, but you never actually use it.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    fmt.Println(&quot;Hello, Gophers!&quot;)<br>}<br><br>func goodbye() {<br>    fmt.Println(&quot;Goodbye, Gophers!&quot;)<br>}</pre><p>Running this spell simply greets the world. The goodbye function, much like an unused spellbook on a wizard&#39;s shelf, remains untouched. This is a simple example of dead code.</p><h3>How deadcode Comes to the Rescue</h3><p>By invoking the deadcode tool on our spellbook (codebase), we can easily identify which spells (functions) we never cast:</p><pre>$ deadcode .<br>/path/to/your/spellbook.go:xx: unreachable func: goodbye</pre><p>deadcode tells us that our goodbye function is a ghost, whispering through the halls of our codebase unheard.</p><h3>Making the Decision</h3><p>Armed with this knowledge, we now face a choice: keep the ghostly code for sentimental reasons or banish it to tidy up our spellbook. In many cases, especially in larger and more complex projects, removing dead code can significantly lighten your load and make your project easier to navigate and maintain.</p><h3>Understanding and Trusting Your Guide</h3><p>The deadcode tool uses a clever strategy to uncover these spectral functions. It starts from the entry points of your application (like the main function) and traces through all possible paths of execution, marking the spells (functions) it encounters along the way. Those left unmarked by the end of this magical journey are considered dead.</p><h3>Why Care About Dead Code?</h3><p>Aside from tidying up, removing dead code has practical benefits. It can speed up compilation times, reduce binary sizes, and simplify your codebase, making it easier for fellow wizards (developers) to read and contribute to your magical projects.</p><h3>Embracing the Journey</h3><p>As you continue to craft spells and weave magic with Go, remember that codebases, like stories, evolve. What was once a bustling town in your narrative may become a forgotten ruin. Periodically invoking the deadcode tool is like dusting off old maps and deciding which lands are worth revisiting and which tales are complete.</p><p>So, dear coding adventurers, I encourage you to embark on this journey of discovery and cleanup within your Go projects. With deadcode by your side, you&#39;re well-equipped to banish those spectral lines of code to the annals of history, making room for new adventures and more efficient magic.</p><p>Happy coding, and may your codebases be ever lively and ghost-free!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfd8f3b0984f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Data Duplication in Go: Simultaneous Reading and Multiple Writing]]></title>
            <link>https://medium.com/@pskshksh/efficient-data-duplication-in-go-simultaneous-reading-and-multiple-writing-d7afe0e7727a?source=rss-78511046581e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7afe0e7727a</guid>
            <category><![CDATA[golang-tools]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ayoub Idel]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 18:13:15 GMT</pubDate>
            <atom:updated>2024-03-01T10:10:45.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/186/0*AxS9h5CnzYY11_a9" /></figure><p>In the world of software development, efficiently handling I/O operations is crucial for performance and resource management. Go, with its powerful standard library, offers elegant solutions for complex data streaming scenarios. Among these, the io.TeeReader and io.MultiWriter functions stand out for their ability to facilitate reading data once and writing it to multiple destinations simultaneously. This article explores how to leverage these functions, providing a clear, structured guide to their application.</p><h3>Introduction</h3><p>Go’s io package includes two particularly useful functions for data streaming and duplication:</p><ul><li>io.TeeReader: Allows data read from an io.Reader to be written to an io.Writer simultaneously, effectively splitting the data stream.</li><li>io.MultiWriter: Enables writing to multiple io.Writer objects from a single write operation, distributing the data across various outputs.</li></ul><p>Combining these functions allows developers to implement efficient data routing and duplication mechanisms within their applications, such as logging, data processing pipelines, and more.</p><h3>Practical Example: Reading Once, Writing Multiple Times</h3><p>Consider a scenario where you need to read data from a single source and write it to multiple destinations, such as different log files, network connections, or in-memory buffers. This can be achieved by combining io.MultiWriter with io.Copy, directly copying the data from the source to multiple writers without intermediate storage or multiple reads.</p><h3>Step-by-Step Implementation</h3><h4>1. Define the Data Source</h4><p>This could be any object that implements the io.Reader interface, like a file reader, network data stream, or buffer.</p><pre>dataSource := bytes.NewBufferString(&quot;Hello, Gophers! Broadcasting data to multiple writers.&quot;)</pre><h4>2. Set Up Destination Writers</h4><p>These are the targets where you want to duplicate the data. They must implement the io.Writer interface.</p><pre>var buf1, buf2 bytes.Buffer<br>logFile, err := os.Create(&quot;log.txt&quot;)<br>if err != nil {<br>    panic(err)<br>}<br>defer logFile.Close()</pre><h4>3. Create a MultiWriter</h4><p>Use io.MultiWriter to combine all destination writers into a single writer interface.</p><pre>multiWriter := io.MultiWriter(&amp;buf1, &amp;buf2, logFile)</pre><h4>4. Copy Data from the Source to the MultiWriter</h4><p>Utilize io.Copy to read from the source and write to all destinations simultaneously.</p><pre>if _, err := io.Copy(multiWriter, dataSource); err != nil {<br>    panic(err)<br>}</pre><h3>Benefits and Considerations</h3><ul><li>Efficiency: This method reads the data once and writes it to all destinations, minimizing I/O operations and memory usage.</li><li>Simplicity: The Go standard library abstracts the complexity, offering a concise, readable way to implement data duplication.</li><li>Flexibility: Easily add or remove destinations by adjusting the MultiWriter setup.</li></ul><h3>Another Practical Example: Counting Bytes and Duplication Using ‘io.TeeReader</h3><p>Now let’s look at a simpler example involving io.TeeReader where we read input from a file, process the data (in this case, simply count the number of bytes), and simultaneously write a copy of the data to another file for logging or backup purposes. This example demonstrates the basic use of io.TeeReader to perform two operations on the stream: processing (counting bytes) and duplicating the stream to a file.</p><p>First, we’ll create a simple text file named input.txt as our data source. This file could contain any text you wish to process. For this example, let&#39;s assume it contains the following text: ‘Hello, Gophers!’</p><p>Now, here’s how you can use io.TeeReader in a Go program:</p><pre>package main<br><br>import (<br>    &quot;bytes&quot;<br>    &quot;fmt&quot;<br>    &quot;io&quot;<br>    &quot;os&quot;<br>)<br><br>func main() {<br>    // Open the input file<br>    inputFile, err := os.Open(&quot;input.txt&quot;)<br>    if err != nil {<br>        fmt.Printf(&quot;Error opening input file: %v\n&quot;, err)<br>        return<br>    }<br>    defer inputFile.Close()<br><br>    // Create the output file for duplication<br>    outputFile, err := os.Create(&quot;output.txt&quot;)<br>    if err != nil {<br>        fmt.Printf(&quot;Error creating output file: %v\n&quot;, err)<br>        return<br>    }<br>    defer outputFile.Close()<br><br>    // Create a buffer to count the bytes<br>    var buf bytes.Buffer<br><br>    // Create a TeeReader that reads from inputFile and writes to buf<br>    tee := io.TeeReader(inputFile, outputFile)<br><br>    // Read from the TeeReader (which also writes to outputFile)<br>    n, err := io.Copy(&amp;buf, tee) // buf here is just used to consume the data<br>    if err != nil {<br>        fmt.Printf(&quot;Error reading data: %v\n&quot;, err)<br>        return<br>    }<br><br>    // Output the number of bytes read<br>    fmt.Printf(&quot;Processed %d bytes\n&quot;, n)<br>}</pre><p>In this example:</p><ul><li>We open an input.txt file for reading and an output.txt file for writing.</li><li>We use io.TeeReader to create a reader (tee) that will read from inputFile and simultaneously write the same data to outputFile.</li><li>We use io.Copy to read from the tee and write to a buffer. While io.Copy reads the data, io.TeeReader ensures that a copy of this data is written to outputFile. The buffer (buf) is used here simply to consume the data from tee; in a real application, this could be replaced with any processing logic.</li><li>Finally, we print the number of bytes processed, which is returned by io.Copy.</li></ul><p>This simple yet effective example demonstrates how io.TeeReader can be used to both process and duplicate data streams with minimal hassle, showcasing the power of Go&#39;s I/O primitives for handling real-world data manipulation tasks efficiently.</p><h3>Conclusion</h3><p>Go’s io.TeeReader and io.MultiWriter offer powerful, straightforward solutions for duplicating data streams. By understanding and utilizing these functions, developers can create efficient, clean, and maintainable I/O operations in their applications. Whether for logging, monitoring, or processing, these tools enable scalable and versatile data handling strategies that can meet the demands of various use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7afe0e7727a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering ‘ io.Pipe ’ in Go]]></title>
            <link>https://medium.com/@pskshksh/mastering-io-pipe-in-go-ca8686150b5e?source=rss-78511046581e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8686150b5e</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[golang-development]]></category>
            <dc:creator><![CDATA[Ayoub Idel]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 17:52:43 GMT</pubDate>
            <atom:updated>2024-02-21T20:46:06.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*v0W2_Gj-3gzUBqFe.png" /></figure><p>Once upon a time in the vast landscapes of Go, developers embarked on quests to bridge the realms of data producers and consumers without the burdens of temporary storage or the complexities of manual buffer management. Their journey led them to discover a powerful artifact: io.Pipe. This story unfolds the mysteries of io.Pipe, guiding you through its practical uses, hidden secrets, and how it empowers seamless data streaming in Go applications.</p><h3>The Genesis of io.Pipe</h3><p>In the beginning, there was data — lots of it. Data that needed to flow from one part of an application to another, sometimes transformed, sometimes untouched. Yet, managing this flow efficiently was a challenge that many faced. Then came io.Pipe, a construct provided by Go&#39;s standard library within the io package, designed to create a synchronous in-memory pipeline.</p><h3>Okay, but what Exactly is io.Pipe?</h3><p>At its core, io.Pipe creates a pair of connected streams: a PipeReader and a PipeWriter. What&#39;s written to the PipeWriter can be read from the PipeReader. This connection is direct and in-memory, meaning there&#39;s no intermediary storage or file system involved, making data transfer efficient and immediate.</p><pre>r, w := io.Pipe()</pre><p>With this simple incantation, you conjure a pipe that acts as a conduit for bytes, ready to transport data across your application’s components.</p><h3>The Art of Streaming Data</h3><p>The true power of io.Pipe shines in scenarios where data needs to be produced and consumed simultaneously. Imagine you&#39;re reading data from a network connection and want to process it as it arrives, or you&#39;re generating log files in real-time and wish to analyze these streams on the fly. io.Pipe is your ally, enabling these operations without waiting for the data production to complete.</p><h3>A Practical Spell: Streaming File Compression</h3><p>Consider a spell where you wish to compress data on the go, reading from a source and writing a compressed version to the destination without intermediate storage.</p><pre>import (<br>   “compress/gzip”<br>   “io”<br>   “os”<br>)<br><br>func compressData(src io.Reader, dest io.Writer) error {<br> r, w := io.Pipe()<br><br> // Compress data and write to pipe in a separate goroutine<br> go func() {<br>   gz := gzip.NewWriter(w)<br>   _, err := io.Copy(gz, src)<br>   gz.Close()<br>   w.CloseWithError(err)<br> }()<br><br> // Read from pipe and write to destination<br> _, err := io.Copy(dest, r)<br> return err<br>}</pre><p>In this enchantment, data flows from the source, through a compression algorithm, and out to the destination — all in a seamless stream, thanks to our magical io.Pipe.</p><h3>Navigating the Perils of Deadlocks</h3><p>However, with great power comes great responsibility. When using io.Pipe, one must be wary of deadlocks. These occur if both the reading from and writing to the pipe happen in the same goroutine, leading to a standstill where each operation waits for the other to complete. The key to avoiding this peril is concurrency—employ goroutines to ensure that reading and writing can occur simultaneously without blocking each other.</p><pre>go func() {<br>    // Write to the pipe here<br>}()<br>// Read from the pipe in the main goroutine</pre><h3>The Treasure Trove of Use Cases</h3><p>Beyond streaming transformations, io.Pipe finds its valor in a multitude of scenarios:</p><ul><li>Logging: Stream logs to a processing function that filters or formats them in real-time.</li><li>Network Communication: Relay data between different network connections, enabling proxy-like behavior.</li><li>Inter-process Communication (IPC): Facilitate data exchange between different parts of an application or between different applications running concurrently.</li></ul><h3>Epilogue: The Legacy of &#39; io.Pipe &#39;</h3><p>As our journey concludes, the legacy of io.Pipe in the Go realm stands as a testament to efficient, elegant data streaming. It empowers developers to craft applications that handle large volumes of data gracefully, with minimal overhead and maximal flexibility.</p><p>Embrace io.Pipe in your Go applications, and you too can weave the magic of seamless data streams, bringing efficiency and simplicity to your data handling tasks. Remember, the power of io.Pipe is not just in its ability to transport data but in its capacity to connect different parts of your application in a fluid, dynamic dance of bytes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8686150b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>