<?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 Shubham Anand on Medium]]></title>
        <description><![CDATA[Stories by Shubham Anand on Medium]]></description>
        <link>https://medium.com/@alwayswannaly?source=rss-5af7ccb22803------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hYoMPtYGi58ROfxUUBbUvQ.jpeg</url>
            <title>Stories by Shubham Anand on Medium</title>
            <link>https://medium.com/@alwayswannaly?source=rss-5af7ccb22803------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:24:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alwayswannaly/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[Architecting High-Performance 5GB+ File Transfers over Raw TCP in Go]]></title>
            <link>https://medium.com/@alwayswannaly/architecting-high-performance-5gb-file-transfers-over-raw-tcp-in-go-9a1e9b685245?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a1e9b685245</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 11:11:04 GMT</pubDate>
            <atom:updated>2026-10-24T11:11:04.447Z</atom:updated>
            <content:encoded><![CDATA[<p>Moving a 5 MB JSON payload over HTTP is a solved problem. Moving a <strong>5 GB+ binary artifact</strong> over a raw TCP socket without spiking RAM, burning CPU cycles on redundant memory copies, or starting from scratch when a connection drops at 94% is a completely different systems engineering challenge.</p><p>Naive approaches — like calling os.ReadFile or accumulating incoming bytes into a bytes.Buffer—trigger immediate Out-Of-Memory (OOM) crashes. To build a production-grade transfer engine, we have to treat the network as an unbounded byte stream and design around OS kernel primitives.</p><p>In this post, we’ll walk through the end-to-end architecture of a high-performance, constant-memory 5GB+ file transfer engine in Go — starting from basic socket pitfalls and scaling up to kernel zero-copy (sendfile), crash-resumable state machines, and lock-free parallel chunking.</p><blockquote><em>🔗 </em><strong><em>Want to jump straight to the code?</em></strong><em> You can find the full reference implementation across all milestones in my GitHub repository here: </em><a href="https://github.com/neverwannafly/go-playground/tree/main/001-tcp">https://github.com/neverwannafly/go-playground/tree/main/001-tcp</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFzrzL0IpqRuVC-_ClvqWQ.png" /><figcaption>project workspace</figcaption></figure><h3>1. Core Mental Models: Why Raw TCP is Unforgiving</h3><h3>TCP is a Byte Stream, Not a Message Queue</h3><p>Unlike HTTP, gRPC, or WebSockets, a raw TCP socket (net.Conn) has zero awareness of message or file boundaries.</p><p>If the sender executes conn.Write(100 bytes) followed by conn.Write(200 bytes), the receiver is <strong>not</strong> guaranteed to receive 100 bytes on its first conn.Read() and 200 on its second. Intermediate routers, OS socket buffers, and Maximum Transmission Units ($\text{MTU} \approx 1500\text{ bytes}$) fragment and coalesce packets arbitrarily.</p><p><strong>The Consequence:</strong> The receiver has no idea what the file is named or when the file ends unless we define an explicit <strong>Application-Layer Framing Protocol</strong> at the very start of the stream.</p><h3>The Two Cardinal Rules of io.Reader</h3><p>Go abstracts files (*os.File), network sockets (*net.TCPConn), and cryptographic hashers (hash.Hash) behind io.Reader and io.Writer. When streaming multi-gigabyte files through a fixed 32 KB buffer, two subtle edge cases in the Read(p []byte) contract will corrupt your data if ignored:</p><ol><li><strong>The Dirty Buffer Trap (</strong><strong>p[:n]):</strong> Read populates up to len(p) bytes into slice p and returns n (the actual byte count placed in p). It <strong>does not</strong> zero out the remaining indices p[n:]. Passing p directly to your writer instead of slicing p[:n] injects stale bytes from previous loop iterations straight into your file.</li><li><strong>Simultaneous Data + </strong><strong>io.EOF:</strong> A Read call reaching the end of a stream is legally permitted to return n &gt; 0 <strong>AND</strong> err == io.EOF in the exact same call. Always process if n &gt; 0 <em>before</em> evaluating if err != nil, or you risk dropping the final chunk of the file.</li></ol><h3>Guarding Against Short Reads &amp; Over-Reads</h3><ul><li><strong>Exact-Length Headers (</strong><strong>io.ReadFull):</strong> A standard r.Read(headerBuf) might only return 3 bytes of a 10-byte header if a TCP segment splits mid-flight. Always use io.ReadFull when parsing fixed-size protocol headers, filenames, or checksum trailers—it loops internally until the buffer is completely filled or returns io.ErrUnexpectedEOF.</li><li><strong>Boundary Isolation (</strong><strong>io.LimitReader):</strong> Wrapping the connection in io.LimitReader(conn, bodySize) ensures your body-reading loop reads <em>at most</em> N bytes and then synthesizes an io.EOF—preventing the file writer from accidentally consuming the 32-byte trailing checksum that follows the file payload.</li><li><em>Gotcha:</em> If the client crashes after sending only 1 GB of a 5 GB file, LimitReader still returns io.EOF when the socket closes. Always verify lreader.(*io.LimitedReader).N == 0 after the loop to confirm all promised bytes actually arrived.</li></ul><h3>Integer Sizing for 5GB+ Files</h3><p>Watch your integer bounds! A signed 32-bit integer (int32) overflows at $\approx 2.14\text{ GB}$, and an unsigned 32-bit integer (uint32) overflows at $\approx 4.29\text{ GB}$. For a 5 GB ($5,368,709,120\text{ bytes}$) transfer, your protocol&#39;s BodySize field <strong>must</strong> be a 64-bit integer (uint64).</p><h3>2. Designing the Wire Protocol (v1)</h3><p>Suppose we want to stream a 5 GB file and verify its SHA-256 integrity. If we put the checksum in the <em>header</em>, the client has to read the entire 5 GB file from disk twice — once to calculate the hash, and once to transmit it over the network.</p><p>To achieve <strong>single-pass streaming</strong>, we place the <strong>Metadata Header</strong> at the front of the stream, compute the SHA-256 hash on the fly as chunks flow through Go’s io.MultiWriter, and append a <strong>32-Byte Checksum Trailer</strong> immediately after the body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOPwSmqvcT7YPL4puSQbWg.png" /></figure><h3>Packet Layout on the Wire (Big-Endian)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*UEbdFlvE7AwO5YpchRV04A.png" /></figure><h3>The Handshake &amp; Streaming Flow</h3><ol><li><strong>Header Exchange:</strong> Client sends the 10-byte fixed header + $N$-byte filename.</li><li><strong>Constant-Memory Streaming:</strong> Client streams the file in reusable 32 KB chunks, multiplexing writes to both the TCP socket and a local SHA-256 hasher via io.MultiWriter.</li><li><strong>On-the-Fly Server Hashing:</strong> The server reads up to BodySize bytes using io.LimitReader, writing simultaneously to disk and its own SHA-256 hasher.</li><li><strong>Trailer Verification:</strong> Client sends its 32-byte digest. The server reads the trailer via io.ReadFull, compares it against its computed digest, and replies with 0x01 (ACK) or 0x00 (NACK, deleting the corrupted artifact).</li></ol><h3>3. The 4 Engineering Milestones to Production</h3><p>The implementation is broken down into four progressive milestones. Here is the engineering progression and the production traps solved at each stage:</p><p><strong>Milestone 1: The Echo Pipe &amp; Short-Read Trap</strong></p><ul><li><em>Focus:</em> Mastering the io.Reader contract, slicing buffers strictly to [:n], processing data before io.EOF, and preventing file descriptor exhaustion (ulimit -n) via strict defer conn.Close() lifecycles.</li></ul><p><strong>Milestone 2: Length-Prefixed Binary Framing</strong></p><ul><li><em>Focus:</em> Implementing Big-Endian binary serialization (encoding/binary), preventing 32-bit integer overflows with uint64, and eliminating partial-header reads with io.ReadFull.</li></ul><p><strong>Milestone 3: Constant-Memory Disk Streaming &amp; SHA-256 Integrity</strong></p><ul><li><em>Focus:</em> Keeping RAM usage flat at <strong>32 KB</strong> whether transferring 10 MB or 50 GB. Using io.MultiWriter to tee streams into disk files and crypto/sha256 simultaneously, and cleaning up orphaned files on checksum mismatch.</li></ul><p><strong>Milestone 4: 5 GB Scale, Progress Tracking &amp; Resilience</strong></p><ul><li><em>Focus:</em> Plugging a custom ProgressWriter into io.MultiWriter (throttled to 200ms UI updates so terminal I/O doesn&#39;t bottleneck network throughput) and enforcing <strong>rolling idle deadlines</strong> (conn.SetReadDeadline / SetWriteDeadline refreshed on every chunk) so silent network drops don&#39;t leak goroutines forever.</li></ul><p>Once you have reached these milestones, to make it production grade, we can delve into the following optimizations —</p><h3>4. Deep Dive I: Kernel Zero-Copy (sendfile &amp; splice)</h3><h3>Why Standard User-Space Loops Burn CPU</h3><p>Even with a constant 32 KB memory footprint, moving 5 GB from disk to a network card (NIC) in a user-space loop requires <strong>163,840 loop iterations</strong>. Look at what happens under the hood for every single chunk:</p><ol><li><strong>DMA Copy:</strong> NVMe SSD copies data into the OS Kernel Page Cache.</li><li><strong>CPU Copy (</strong><strong>read syscall):</strong> Kernel copies data from Page Cache into your Go user-space []byte buffer.</li><li><strong>CPU Copy (</strong><strong>write syscall):</strong> Kernel copies data from your Go user-space []byte buffer into the Kernel Socket Send Buffer (sk_buff).</li><li><strong>DMA Copy:</strong> NIC reads from the Socket Buffer onto the wire.</li></ol><p>Across a 5 GB transfer, that translates to <strong>655,360 context switches</strong> and <strong>10 GB of redundant CPU memory copies</strong> across the user/kernel boundary.</p><h3>The sendfile(2) Zero-Copy Path</h3><p>Modern kernels solve this with the sendfile(2) syscall. Instead of copying bytes into Go&#39;s user-space RAM, the kernel instructs the NIC (via DMA Scatter-Gather) to read packet payloads directly from the Kernel Page Cache descriptors. Zero bytes ever touch user space, and CPU utilization drops to near zero.</p><h3>How Go Triggers sendfile Automatically (And How Wrappers Break It!)</h3><p>In Go’s net package, *net.TCPConn implements the io.ReaderFrom interface. When you call io.Copy(dst, src), Go checks if dst implements io.ReaderFrom:</p><ul><li>If dst is a raw *net.TCPConn and src is an *os.File (or an *io.LimitedReader wrapping an *os.File), Go automatically bypasses user-space buffers and invokes the OS sendfile(2) syscall!</li></ul><p><strong>The Hidden Trap:</strong> Wrapping conn in io.MultiWriter(conn, hasher, progress) hides *net.TCPConn&#39;s ReadFrom method behind a generic struct, silently disabling zero-copy and forcing every byte back into user-space RAM!</p><p><strong>How to Preserve Zero-Copy in Production:</strong> If you rely on TLS 1.3 or pre-computed file hashes for integrity, you can preserve <strong>100% kernel </strong><strong>sendfile(2) zero-copy</strong> <em>while still keeping rolling deadlines and progress bars</em> by looping in 16 MB increments using io.CopyN(conn, file, 16*1024*1024). Because io.CopyN wraps file in an *io.LimitedReader—which Go&#39;s sendfile path explicitly recognizes—every 16 MB chunk transfers entirely inside the kernel.</p><h3>5. Deep Dive II: Resumable Transfers (Crash Recovery)</h3><p>When transferring 5 GB over an unstable WAN link, a dropped connection at 4.7 GB shouldn’t destroy the 4.7 GB already written to disk.</p><p>To make the protocol crash-recoverable (Protocol v2), we introduce two architectural changes:</p><ol><li><strong>Staging Suffix (</strong><strong>.part) &amp; Retention Policy:</strong></li></ol><ul><li>While a transfer is active, the server writes to received_&lt;filename&gt;.part.</li><li>If a <strong>network drop or timeout</strong> occurs mid-stream, the server <strong>keeps</strong> the .part file on disk.</li><li>If the final <strong>checksum mismatches</strong>, the server <strong>deletes</strong> the .part file.</li><li>Only when the final checksum matches does the server atomically promote the file via os.Rename(&quot;...part&quot;, &quot;...final&quot;).</li></ul><p><strong>2. Two-Way Offset Handshake:</strong></p><ul><li><strong>Step 1:</strong> Client sends the v2 Header (BodySize = 5 GB).</li><li><strong>Step 2:</strong> Server runs os.Stat on the .part file. If 4 GB is already on disk, the server replies with an 8-byte uint64 <strong>Resume Offset</strong> (4,000,000,000) and opens the .part file in os.O_APPEND mode (never os.Create, which truncates!).</li><li><strong>Step 3:</strong> Client reads the offset, calls file.Seek(offset, io.SeekStart) in $O(1)$ time, and streams only the remaining 1 GB slice along with the SHA-256 digest of that transmitted slice.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rjtc8UrsexVljK6eg9xpaA.png" /></figure><h3>6. Deep Dive III: Concurrency &amp; Lock-Free Parallel Chunking</h3><p>Scaling a file transfer server requires solving concurrency at two orthogonal layers:</p><h3>1. Bounded Server Worker Pools</h3><p>Spawning an unbounded goroutine per connection works fine in toy benchmarks, but a sudden burst of 2,000 concurrent uploads will exhaust OS file descriptors (ulimit -n) and thrash disk IOPS. In production, we gate incoming connections behind a buffered channel semaphore (e.g., sem := make(chan struct{}, 16)) paired with a sync.WaitGroup and SIGINT/SIGTERM listener so in-flight transfers drain cleanly during deployments.</p><h3>2. Single-File Parallel Chunking (pread &amp; pwrite)</h3><p>Over a long-distance WAN link (e.g., 150 ms RTT), a single TCP stream is throttled by the <strong>Bandwidth-Delay Product (BDP)</strong> and TCP congestion window scaling. Splitting a single 5 GB file across 4 to 8 parallel TCP streams multiplies throughput.</p><p><strong>The Concurrency Trap:</strong> Never share file.Seek() + file.Read()/file.Write() across goroutines! An OS file descriptor only has a single cursor offset—two goroutines calling Seek concurrently will race and corrupt the file.</p><p>Instead, we use positional syscalls (pread and pwrite) that bypass the OS file cursor entirely and require <strong>zero mutex locks</strong>:</p><ul><li><strong>Client-Side (</strong><strong>io.NewSectionReader):</strong> Wraps *os.File using ReadAt (pread(2)). Four worker goroutines can read four distinct 1.25 GB sections of the exact same *os.File handle simultaneously without locking.</li><li><strong>Server-Side (</strong><strong>OffsetWriter via </strong><strong>file.WriteAt):</strong> The server pre-allocates the 5 GB file on disk using outfile.Truncate(totalSize). Each incoming stream gets a lightweight OffsetWriter wrapper around outfile.WriteAt(p, offset) (pwrite(2)), writing its assigned byte range directly into the pre-allocated file in parallel.</li></ul><h3>7. Quick Reference: Linux CLI Testing &amp; Benchmarking Cheatsheet</h3><p>When benchmarking your own implementation, these five commands are invaluable for testing edge cases without waiting on real-world network failures:</p><pre># 1. Generate a 5 GB sparse/zero file instantly (tests pure TCP + disk write speed)<br>fallocate -l 5G sample.bin<br># (Or on macOS): mkfile -n 5g sample.bin<br><br># 2. Generate a 1 GB random binary file (tests incompressible data + SHA-256)<br>dd if=/dev/urandom of=sample.bin bs=1M count=1024<br># 3. Verify syscalls (confirm sendfile vs read/write loops on Linux)<br>strace -c ./client<br># 4. Simulate realistic WAN packet loss &amp; latency on localhost (Linux tc netem)<br># Adds 50ms RTT latency and 0.1% packet loss to loopback interface:<br>sudo tc qdisc add dev lo root netem delay 50ms loss 0.1%<br># Remove simulation when done:<br>sudo tc qdisc del dev lo root netem<br># 5. Manually verify SHA-256 digests match outside Go<br>sha256sum sample.bin received_sample.bin</pre><h3>Wrapping Up</h3><p>Building a high-throughput file transfer system over raw TCP forces you to respect the boundaries between user space, the Go runtime, and the OS kernel. By combining deterministic binary framing, composable io streams, sendfile(2) zero-copy optimizations, and lock-free positional I/O (pread/pwrite), you can saturate multi-gigabit links while keeping memory usage completely flat.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a1e9b685245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strainers, Swamps, and Survival: Kayaking Kali the Hard Way]]></title>
            <link>https://medium.com/@alwayswannaly/strainers-swamps-and-survival-kayaking-kali-the-hard-way-3bf938afdf53?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf938afdf53</guid>
            <category><![CDATA[adventure]]></category>
            <category><![CDATA[kayaking]]></category>
            <category><![CDATA[rivers]]></category>
            <category><![CDATA[karnataka]]></category>
            <category><![CDATA[kali]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 14:29:19 GMT</pubDate>
            <atom:updated>2025-03-28T14:29:19.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Date: March 1st, 2025</h3><p>The morning air was crisp as I strapped on my gear, excitement bubbling within me. My GoPro was ready to capture every heart-pounding moment. I had managed to hit almost all my rolls yesterday, and the confidence was surging through me. It had been a long time since I had kayaked, and this was my second river after the mighty Ganga. But Kali — oh, Kali was something else. This river was wilder, more unpredictable, and, to my absolute surprise, infested with crocodiles. Definitely not something I had on my 2025 bingo card.</p><p>Yesterday’s practice ended with an adrenaline-pumping rapid that looked like a massive waterslide — so, naturally, I dubbed it the <em>Waterslide Rapid</em>. It had a big, menacing rock smack in the middle, a real gut-check moment for me. Fear gripped me for a second, but I pushed through, conquering it and refining my ferry skills. My mentor and comrade, Jogi, shared some wisdom that stuck with me: kayaking isn’t just about paddling — it’s about navigating your way, reading the river, and as he put it, <em>“Kayaking is eddy hopping.”</em></p><p>Before I hit the rapid, Jogi had told me to relax about the rock and not worry too much. He explained all the different ways my kayak could hit it and still be fine. That reassurance helped, but as destiny would have it, that very rock had given him a nasty shoulder injury just the day before. So not as reassuring as it would seem :P</p><h3>The River Run Begins</h3><p>Jogi and I drove to the put-in point, where he gave me a deep dive into the theory of kayaking — rapid gradings, river reading, and tales of his wild adventures in Nepal and Leh. The guy is a legend. His passion for kayaking was infectious.</p><p>After a quick paddling warm-up and a roll, we set off, beginning the river run with none other than the Waterslide Rapid. As I launched myself into it, I felt a funny drop in my stomach — the kind you get on roller coasters. But I breezed through it, the rush of adrenaline sharpening my senses as we ventured further into the heart of the Kali.</p><p>Unlike the Ganga, where the rapids had clear, well-defined paths, Kali was unpredictable. There were no obvious routes — only the river’s raw, untamed force. The banks, too, were elusive. Jogi educated me on ‘strainers’ — branches, trees, or debris that could trap a kayaker if they weren’t careful. I listened, intrigued but not overly concerned. After all, I had yet to experience their true menace firsthand.</p><p>And with that, we officially began our exploration of River Kali.</p><h3>The Strainers Strike</h3><p>The first few rapids went smoothly, my confidence growing with each one. Then, while trying to catch an eddy, I unexpectedly found myself tangled in some rogue branches. To avoid a direct hit to my face, I instinctively dunked my head underwater and rolled out. It was wild, but I shook it off. Little did I know, that was just the beginning of my battles with the strainers.</p><p>We reached a section where a significant drop created a big, churning hole. Jogi’s only advice? <em>“Paddle hard.”</em> My heart pounded, but I powered through and made it safely. Sri, one of our companions, wasn’t as lucky — he flipped and had to swim. I grabbed his paddle and tried to catch an eddy, but then <em>bam</em> — I got snagged by another strainer. This time, Andrea, another experienced kayaker, had to push me free. That was when I really started to respect the deadly potential of these obstacles.</p><h3>A Battle Against the River</h3><p>Then came the moment that turned my blood cold. I got tripped by a strainer and was violently smashed against rocks and scratched by a thousand branches. I tried to roll up, but there was no space. Somehow, I broke free — but in the chaos, I lost my paddle and was heavily disoriented. Andrea spotted it and retrieved it for me. As soon as I got it back and tried to push forward, I found myself trapped again — this time in an even worse situation. The full force of Kali’s current rammed my kayak against a log, pinning my chest so tightly that I couldn’t even eject. The pain was unbearable. I struggled to breathe, completely immobilized. The river wasn’t just playing with me now — it was holding me hostage.</p><p>Andrea reached me again, guiding me on how to eject. He managed to pull my kayak just enough to create space for me to escape. But as I got out, I was left stranded, gripping onto a lone log with all my strength. The current was merciless, pounding against my face. If I lost my grip, I knew I’d be swept into the chaos of strainers, jagged rocks, and untamed waters. I clung on for what felt like an eternity — ten to twenty minutes — just battling to stay alive.</p><p>Meanwhile, Jogi attempted a rescue but got caught under a strainer himself, forcing him to eject. In the process, he lost his paddle. He somehow threw me a rope bag, and I grabbed on for dear life, finally making it to the bank beside him. But our ordeal wasn’t over yet.</p><h3>The Trek Through the Swamp</h3><p>Now paddle-less, exhausted, and stranded in an unfamiliar part of the river, we had to reunite with Andrea and Sri. What lay ahead was an arduous trek through a swamp. And to top it off — I was barefoot. Every step was a gamble between sharp rocks, unseen obstacles, and my mind racing about lurking crocodiles and hidden dangers. When we finally rendezvoused, a major dilemma faced us: what next?</p><p>We still had 5 kilometers left to kayak, but we were now in an unknown creek, slightly disoriented, and our best kayaker, Jogi, had no paddle. We debated our options:</p><ol><li>Andrea and Jogi could push ahead to the finish line, retrieve an extra paddle, and come back for us. But that would leave Sri and me — both beginners — alone in an unpredictable stretch of the river.</li><li>Jogi or Andrea could continue paddling without a paddle, using only their hands.</li></ol><p>Jogi, the absolute beast that he is, chose option two. And man, I have never seen anything like it. He paddled through the rapids <em>better with his hands</em> than I did with my paddle. Watching him power through fired us all up. Our spirits soared, and our confidence returned. The rest of the journey, while still intense, felt exhilarating rather than terrifying.</p><p>If Jogi could tackle the Kali without a paddle, surely we could navigate the rest of the run with renewed confidence.</p><p>The remainder of the journey was smooth — perhaps the river had tested us enough for one day. We reached our take-out point, exhilarated and exhausted, our bonds forged stronger by the trials we had faced together.</p><h3>The Booty Beer Tradition</h3><p>At the end of every great kayaking expedition comes the ritual: the Booty Beer. Tradition dictates that one drinks beer from their kayaking shoe as a toast to the adventure. But, given that I had spent the day barefoot and didn’t had boots of my own, we settled for the bottle instead, laughing as we clinked them together in celebration.</p><p>The River Kali had thrown everything it had at us — fear, thrill, pain, and triumph. It had tested my limits, taught me respect, and left me with an unforgettable story. And as I took that last sip, I knew one thing for sure: this was only the beginning of my journey as a kayaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4t3qv0ts784RI82wkl5uQ.jpeg" /><figcaption>Andrea, Me, Jogi and Sri</figcaption></figure><p>Check out my Instagram for some cool footage from Kali ^_^</p><ul><li><a href="https://www.instagram.com/p/DGvBPqLMiAc/">https://www.instagram.com/p/DGvBPqLMiAc/</a></li><li><a href="https://www.instagram.com/p/DHJKuMSSvuf/">https://www.instagram.com/p/DHJKuMSSvuf/</a></li><li><a href="https://www.instagram.com/p/DHd53UpyGL7/">https://www.instagram.com/p/DHd53UpyGL7/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf938afdf53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dijkstra’s Algorithm — Implementation Essentials]]></title>
            <link>https://medium.com/@alwayswannaly/dijkstras-algorithm-implementation-essentials-c23db1d687b6?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/c23db1d687b6</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[dijkstra]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 13:14:50 GMT</pubDate>
            <atom:updated>2023-12-02T13:14:50.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dijkstra’s Algorithm — Implementation Essentials</h3><p>In the realm of graph algorithms, Dijkstra’s Algorithm stands as a pivotal solution for finding the shortest path between two points in a weighted graph. It’s perhaps one of the most important algorithms when it comes to the Graph data structure. Let’s delve into the core of this algorithm to comprehend its practical implementation.</p><p>Before going deep into Dijkstra’s, one of the cornerstones to getting the algorithm right is understanding more about PriorityQueues. This data structure is a queue but instead of following first in first out, it follows a priority order dictated by the end user. Since Dijkstra’s is a greedy algorithm that tries to use edges with the least distance, this data structure immensely helps in efficiently maintaining edges with the least distances and efficient retrieval for our operations.</p><h3>Priority Queue</h3><p>We’ll need the following operations to be supported by our priority queue class (we’ll be using a binary heap to implement our priority queue, for most practical purposes, a binary heap will be pretty performant) —</p><pre>// Inserts an Element E with some key K and priority P<br>void Heap::push(std::pair&lt;int, int&gt; node) {}<br><br>// Returns the smallest element in our queue (in case of min priority queue)<br>std::pair&lt;int, int&gt; Heap::top() {}<br><br>// Deletes the top element in our queue<br>void pop() {}<br><br>// Tells whether our priority queue is empty or not<br>bool Heap::empty() {}</pre><p>Before jumping to the implementation of our priority queue to implement the Dijsktra’s, let’s look at the following visualization to get some understanding of a few concepts that will be useful</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHfQdVkkryf4nGDFVJd7yA.png" /><figcaption>Heap Representation</figcaption></figure><h4>Implementation (Min Priority Queue)</h4><pre>class Heap {<br>public:<br>  Heap();<br>  bool empty();<br>  std::pair&lt;int, int&gt; top();<br>  void pop();<br>  void push(std::pair&lt;int, int&gt; node);<br>private:<br>  // private helper function to ensure element idx follows the heap property<br>  // given the subtrees below it satisfy the heap property<br>  void heapify(int idx);<br>  // current size of the heap<br>  int currSize;<br>  // Our vector that will contain the heap<br>  std::vector&lt;std::pair&lt;int, int&gt;&gt; Q;<br>};<br><br>// Constructor, sets current size to 0 and initialises heap vector to a sufficient enough size<br>Heap::Heap() {<br>  currSize = 0;<br>  Q.resize(30000);<br>}<br><br>bool Heap::empty() {<br>  return this-&gt;currSize == 0;<br>}<br><br>std::pair&lt;int, int&gt; Heap::top() {<br>  return this-&gt;Q[0];<br>}<br><br>void Heap::pop() {<br>  if (this-&gt;currSize == 0) throw &quot;Heap Underflow&quot;;<br>  // Swap the first element of the heap with the last element and <br>  // decrease the size of our heap<br><br>  std::swap(this-&gt;Q[0], this-&gt;Q[currSize - 1]);<br>  currSize -= 1;<br><br>  // Except the first element, every other element follows the Heap property,<br>  // hence to rectify the issue, we call our private heapify function on the<br>  // item on 0th index<br>  this-&gt;heapify(0);<br>}<br><br>void Heap::push(std::pair&lt;int, int&gt; node) {<br>  // Assign the new element to end the of our vector and increase the size<br>  this-&gt;Q[this-&gt;currSize] = node;<br>  this-&gt;currSize += 1;<br><br>  // After this operation, only the last element doesnt satisfy the heap property.<br>  // We&#39;ll do a similar operation as heapify but in reverse order, i.e., <br>  // Instead of correcting the siblings, we&#39;ll correct the parent nodes so<br>  // our vector satisfies the heap property<br><br>  int currIdx = currSize - 1;<br>  int parent = (currIdx - 1) / 2;<br><br>  while (currIdx &gt; 0 &amp;&amp; this-&gt;Q[parent].second &gt; this-&gt;Q[currIdx].second) {<br>    std::swap(this-&gt;Q[parent], this-&gt;Q[currIdx]);<br>    currIdx = parent;<br>    parent = (currIdx - 1) / 2;<br>  }<br>}<br><br>void Heap::heapify(int idx) {<br>  // Get left and right siblings of idx node<br>  int leftIdx = 2 * idx + 1;<br>  int rightIdx = 2 * idx + 2;<br><br>  int resIdx = idx;<br><br>  if (leftIdx &lt; this-&gt;currSize &amp;&amp; this-&gt;Q[resIdx].second &gt; this-&gt;Q[leftIdx].second) {<br>    resIdx = leftIdx;<br>  }<br>  if (rightIdx &lt; this-&gt;currSize &amp;&amp; this-&gt;Q[resIdx].second &gt; this-&gt;Q[rightIdx].second) {<br>    resIdx = rightIdx;<br>  }<br><br>  // In min heap, given that on right and left, we have subtrees that satisfy the<br>  // heap property, we would like to select the smallest element out of the three indexes.<br>  // if no such index exists, we stop; but in case such an index exists, we correct the<br>  // elements through a swap and redo our heapify operation down the subtree recursively<br>  // until the whole subtree below idx follows the heap property.<br>  if (idx == resIdx) return;<br>  <br>  std::swap(this-&gt;Q[resIdx], this-&gt;Q[idx]);<br>  this-&gt;heapify(resIdx);<br>}</pre><h4>Questions to strengthen the concept</h4><p>You can refer to the below-mentioned questions to get a strong grasp on priority queues —</p><ol><li><a href="https://leetcode.com/problems/top-k-frequent-elements/description/">https://leetcode.com/problems/top-k-frequent-elements/description/</a></li><li><a href="https://leetcode.com/problems/reorganize-string/description/">https://leetcode.com/problems/reorganize-string/description/</a></li><li><a href="https://leetcode.com/problems/design-twitter/description/">https://leetcode.com/problems/design-twitter/description/</a></li></ol><h3>Dijkstra’s Algorithm</h3><p>Now, that we know what a priority queue is, we’re in a position to implement Dijsktra’s Algorithm. First, let’s go through the basic pseudo algorithm —</p><pre># Initialize takes a Graph and source vertex and sets distances of all<br># vertexes to INF from source while setting distance of source to source as 0<br><br>Initialize(G, source) {<br>  for vertex v ∈ G.Vertexes {<br>    distances[v] = INF;<br>  }<br>  distances[start_vertex] = 0<br>}<br><br><br># Takes in two vertexes u and v and the distance/weight between them<br># If the new distance from u is smaller than distance(s-&gt;v),<br># we update the distance(s-&gt;v) and insert this edge in our priority queue<br># with the new distance to be processed<br><br>Relax(u, v, w) {<br>    if (distances[u] + w(u,v) &lt; distances[v]) {<br>        distances[v] = distances[u] + w(u,w);<br>    }<br>    Q &lt;- { v, distances[v] }<br>}<br><br><br># Main Algorithm<br># G -&gt; Graph Data structure, adjancy list<br># w -&gt; weight function that tells weight between two edges<br># source -&gt; source vertex from where to find smallest distance<br><br>Dijsktra(G, w, source) {<br>    Initialize(G, source);<br>    visited = {};<br>    <br>    Q = { source, 0 }; # Q is our priorty queue<br><br>    while Q is not empty {<br>        u = Q.top() and Q.pop()<br>        <br>        visited[u] = true;<br>        <br>        for each vertex v ∈ G.Adj[u] {<br>            continue if visited[v] == true<br>            <br>            Relax(u, v, w);<br>        }<br>    }<br>}</pre><h4>Implementation</h4><p>We’ll represent our Graph as an adjacency list. To represent it, we’ll use the following STL container std::map&lt;int, std::vector&lt;std::pair&lt;int,int&gt;&gt;&gt;</p><p>If this looks daunting think of it this way —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkZaptqNlnPJw9vteN05iw.png" /><figcaption>STL for our Graph</figcaption></figure><p>Similarly, we’ll define the weights of our graphs using the following STL container std::vector&lt;std::vector&lt;int&gt;&gt; . The inner vector will contain three elements,</p><ul><li>[0] contains the “from” edge</li><li>[1] contains the “to” edge</li><li>[2] contains the weight edge, i.e. the cost to go from [0] to [1].</li></ul><pre>// Our function solve takes four parameters<br>// Total number of nodes in the Graph, graph G, the weights between the edges and the source vertex<br>// And returns a vector with size equal to number of edges in the graph which contains<br>// shortest distance of node i from source<br><br>#define INF 1e9+7<br><br>std::vector&lt;int&gt; solve(int N, std::map&lt;int, std::vector&lt;std::pair&lt;int, int&gt;&gt;&gt; G, std::vector&lt;vector&lt;int&gt;&gt; weights, int source) {<br>  std::vector&lt;bool&gt; visited(N, false);<br><br>  // Similar to initialize function in our psuedocode<br>  std::vector&lt;int&gt; distances(N, INF);<br>  distances[source] = 0;<br><br>  Heap priorityQueue = Heap();<br>  priorityQueue.push({ source, 0 });<br><br>  while (!priorityQueue.empty()) {<br>    std::pair&lt;int, int&gt; top = priorityQueue.top(); priorityQueue.pop();<br><br>    int currentNode = top.first;<br>    visited[currentNode] = true;<br><br>    std::vector&lt;std::pair&lt;int, int&gt;&gt; neighbours = G[currentNode];<br><br>    for (int idx = 0; idx &lt; neighbours.size(); idx += 1) {<br>      int destinationNode = neighbours[idx].first;<br>      int distance = neighbours[idx].second;<br><br>      if (visited[destinationNode]) continue;<br><br>      // Similar to Relax step in our pseudocode<br>      if (distances[currentNode] + distance &lt; distances[destinationNode]) {<br>        distances[destinationNode] = distances[currentNode] + distance;<br>        priorityQueue.push({ destinationNode, distances[destinationNode] });<br>      }<br>    }<br>  }<br><br>  return distances;<br>}</pre><p>You can go through the following solution for the problem <strong>“Network Delay Time” </strong>to better understand how things fit if there’s some unclarity regarding implementation —</p><p><a href="https://leetcode.com/problems/network-delay-time/submissions/1110818305">https://leetcode.com/problems/network-delay-time/submissions/1110818305</a></p><h4>Questions to strengthen the concept</h4><ol><li><a href="https://leetcode.com/problems/design-graph-with-shortest-path-calculator/description/">https://leetcode.com/problems/design-graph-with-shortest-path-calculator/description/</a></li><li><a href="https://leetcode.com/problems/network-delay-time/description/">https://leetcode.com/problems/network-delay-time/description/</a></li><li><a href="https://leetcode.com/problems/path-with-maximum-probability/description/">https://leetcode.com/problems/path-with-maximum-probability/description/</a></li></ol><h3>Analysis of Dijsktra’s Algorithm</h3><h4>Time Complexity Analysis</h4><ol><li><strong>Building the Graph:</strong><br>Assuming n nodes and m edges in the graph, constructing the graph has a time complexity of O(m) to iterate through all edges.</li><li><strong>Initializing Data Structures:</strong><br>Initializing the arrays or data structures to store distances and visited nodes takes O(n) time.</li><li><strong>Main Loop:</strong><br>The main loop of the algorithm runs for all nodes. In each iteration, it explores neighboring nodes and updates their distances if a shorter path is found.<br>In the worst case, each edge might be relaxed once for each node, leading to a time complexity of O(n + m) for the main loop.</li><li><strong>Priority Queue Operations:</strong><br>The time complexity of inserting an element into the priority queue is O(log n) in a binary heap-based implementation.<br>Overall, the total time complexity for all insertions into the priority queue is O(m * log n) considering all edges.</li><li><strong>Overall Time Complexity:</strong><br>Combining all the steps, the overall time complexity of Dijkstra’s Algorithm with a priority queue implementation is typically O((n + m) * log n).</li></ol><h4>Limitations</h4><ul><li>While the Dijkstra algorithm can work on graphs that have cycles, it doesn’t work with Graphs that have <strong>negative weights</strong>.</li><li>Dijsktra’s algorithm can only work in connected graphs, i.e. it can only calculate shortest paths for connected nodes.</li></ul><p>Hope this article gave you a good idea and cleared some doubts about the implementation details of Dijsktra’s Algorithm 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c23db1d687b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Simplified Guide to Data Replication | Part 1]]></title>
            <link>https://medium.com/@alwayswannaly/the-simplified-guide-to-data-replication-part-1-f0689bda6530?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0689bda6530</guid>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 17:24:53 GMT</pubDate>
            <atom:updated>2023-11-25T17:24:53.777Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever made a copy of something important? That’s what data replication is about — making copies of important stuff in different places to keep it safe.</p><p>Imagine your favorite photo. You don’t want to lose it, right? So, you might make copies and keep them in different folders or devices. That’s what one might want to do with information in databases. They make copies in different places so that if something breaks, they still have the information.</p><p>In this article, we’ll explore the essence of replication, why is it important, and some of its challenges.</p><h3>The Need for Data Replication</h3><p>There are three main reasons why one might be interested in replicating their data —</p><ol><li>Keeping the data geographically closer to your end users.</li><li>Horizontally scaling out your database to take on better loads.</li><li>Being resilient to complete downtime during faults in the database.</li></ol><p>If we assume our data to not change over time, then replication is an easy task. But that is rarely the case, often times our data is ever-changing and that is what makes replication such a difficult problem. The difficulties arise mainly due to the fundamental constraints in networking and handling failures.</p><h3>Single Leader-based Replication</h3><p>All applications of replications should satisfy the following requirement on the database — all the replicas must eventually come to the same state, i.e., they should be <strong>eventually consistent</strong>. If the value of a row with id 7 on some Node 1 is 10, it should also be read as 10 on other replicas eventually.</p><p>One of the simplest models for data replication is the single leader (master-slave, active-passive) replication. The idea is straightforward, we have multiple nodes, and out of those nodes, one node is designated as the <strong>leader</strong>.</p><ol><li>All write queries are routed to the <strong>leader</strong> node while the read queries can be served by any node in the system.</li><li>When a leader node receives a write request, it first makes the corresponding change to its own local storage and then transmits the changes to the other replicas.</li><li>Each follower/replica takes the log from the leader and updates its local copy of the data accordingly, by applying writes in the same order as the leader.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8o7vLfk2kbAQf38nE5C4w.png" /><figcaption>Setup for Single Leader-based Replication</figcaption></figure><p>This mode of replication is a built-in feature of many relational DB’s like PostgreSQL and MySQL. It’s also used in some NoSQL DB’s like MongoDB, RethinkDB, etc.</p><p>Workloads that consist of mostly reads and only a small percentage of writes ( A very common pattern on the web), Single leader replication is an attractive option.</p><h4>Synchronous vs Asynchronous Replication</h4><p>The replication stream can be sent via two modes, either in a synchronous fashion or an asynchronous fashion. Let’s briefly discuss both the modes of propagating changes from leaders to followers.</p><p>In sync replication, the leader will wait until its followers have confirmed that they have received and applied the writes before the leader reports success to the client/end-user, while in async-replication, the leader will not wait for a response from its followers. The following figure tries to explain the difference between sync and async replication — Read Replica 1 is operating with synchronous replication whereas Read Replica 2 is operating with asynchronous replication. As you can see, the leader waits for RR1’s response while it doesn’t wait for RR2’s response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gxgDeSwMDxvF0L21msBCQ.png" /></figure><p>Normally replication is quite fast, but there’s no guarantee. most DB systems apply changes to their replicas in fraction of seconds. However, there can be circumstances when followers might fall behind the leader by several minutes or even hours (in cases when the follower is recovering from a fault or there are network issues)</p><p>Synchronous Replication has the obvious advantage that the followers are guaranteed to have an up-to-date copy of the leader. If the leader suddenly fails, we can be sure that the data is available to the followers. The disadvantage is that one single bad follower can bring the whole system down. The leader will simply block all writes until all synchronous replicas are available again.</p><p>That is why, it&#39;s highly impractical to have all replicas as synchronous. In practice, at most, one replica is designated as synchronous, and other replicas are in asynchronous mode. This makes sure that you have up-to-date data on at least 2 nodes — The Leader and the synchronous Replica. This configuration is called <strong>semi-synchronous</strong></p><p>In practice, we’ll often see that all replicas operate in an async fashion only. In this fashion, leader failure can mean some writes that were not propagated to other followers as being lost. This weakens the durability of write operations. This may seem like a bad tradeoff, but async replication is nevertheless widely used as it can handle much higher traffic at lower latency.</p><h3>Setting up New Followers</h3><p>Often, we might want to add additional replicas/nodes to our cluster, either to cater to the increased traffic or to replace failed nodes. Let’s see how we can ensure that the new node will have an up-to-date copy of the leader without incurring any downtime —</p><ol><li>Take a consistent snapshot of the leader’s DB at some point in the time.</li><li>Copy the snapshot to the follower node</li><li>The follower connects to the leader and requests all the changes that have happened since the snapshot was taken. This information is often identified by checking the snapshot’s exact position in the leader’s replication log.</li><li>After a follower is done processing the backlog of data changes, it can now continue to process data changes from the leader.</li></ol><h3>Handling Node Outages</h3><p>The biggest advantage of replication is that we can tolerate outages of single or several nodes. In a single leader, outages are mainly of two types, failure of a follower and failure of a leader.</p><ol><li>Follower Failure<br>It’s pretty straightforward for a follower to recover from a crash. Once they are back, they can simply request changes from the leader that happened when they were down. Once they are done processing the backlog, they can start processing the stream of changes from the leader.</li><li>Leader Failure<br>This is a tricky thing to deal with, often, one of the followers needs to be promoted as a leader, clients need to be reconfigured to send their writes to the new leader, and the other followers need to start consuming data changes from the new leader. This process is called a failover.</li></ol><h3>Issues with Replication Lag</h3><p>The difference between the state of a follower node with respect to the leader is called the replication lag. Often is the case, DB systems have a replication lag of under a second but sometimes, during peak, these lags can increase to several seconds, minutes, or in case of failures, even hours.</p><p>Let’s explore some of the issues that can arise due to replication lags in our systems —</p><h4>Reading your own Writes</h4><p>In many systems, end users can submit some data through a form. Let’s say, you updated your profile, and immediately refreshed the page to view it again. The request to update your profile data will go to the leader, while the request to view your profile might go to a replica. Let’s assume the replica is behind the leader, so you’ll see stale data. This constitutes a bad UX for the user to see stale data when they just updated their profile. It’s fine though, if a user sees some comments, or the new like count on his post a bit later.</p><p>For such situations, we need <strong>read-after-write consistency</strong>. This is a guarantee that if a user reloads their page, they will always see any updates they submitted themselves. It, however, makes no promises about other user’s updates.</p><p>One way to achieve something like this would be to read something that the user may have modified from the leader itself. This requires that we have some way to identify whether something might have been modified without any additional calculations/querying. One simple approach is to always track the time of the last update and for one minute, make all reads from the leader. You can also prevent queries on any followers where the replication lag is more than 1 minute.</p><p>This problem, of course, becomes more complicated once multiple devices are involved or multiple data centers are involved.</p><h4>Monotonic Reads</h4><p>The second anomaly that can occur when reading from asynchronous followers is that it’s possible for users to see things moving backward in time.</p><p>Let’s say the user requests comments on a post. The request hits a replica that is sufficiently up to date with the replica and returns 2 comments. Let’s say the user refreshed and now the request went to a replica with some replication lag and we only get back 1 comment. The user can get confused, as he first saw 2 comments, and now he’s suddenly seeing only 1 comment. Monotonic reads are a guarantee that such anomalies don&#39;t happen. It’s a stronger guarantee than eventual consistency but a weaker guarantee than strong consistency</p><p>One simple way to achieve monotonic reads is to always make sure one user always reads from the same replicas. We can hash the user’s ID to map it to some replica without any expensive computation or bookkeeping.</p><h3>References</h3><ul><li>Designing Data-Intensive Applications, Martin Kleppmann</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0689bda6530" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep dive into Ruby’s Object Model, Pt 2]]></title>
            <link>https://medium.com/@alwayswannaly/a-deep-dive-into-rubys-object-model-pt-2-3b2711607f7d?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b2711607f7d</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 09:12:56 GMT</pubDate>
            <atom:updated>2023-03-11T09:13:54.209Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@alwayswannaly/a-deep-dive-into-rubys-object-model-pt-1-6dcddfba37b4">previous part</a>, we put up a very basic model to visualize ruby’s object model. We read about objects and classes in detail and discovered how classes are nothing but just objects. In this part, we’ll be looking at how ruby is able to find which method to call through an object.</p><h3>Ancestory Chain for Objects</h3><p>Objects in ruby have what we can call an ancestry chain. In simple terms, ruby objects inherit methods from other objects either via class inheritance or by including modules. For eg, in the IRB, let’s explore the Array class and ask it for its list of ancestors,</p><pre>Array.ancestors<br>=&gt; [Array, Enumerable, Object, Kernel, BasicObject]</pre><p>If you remember from the last blog, Kernel is a module that provides us with methods like print available everywhere in our ruby code. Enumerable, Object and BasicObject are classes.</p><p>Let’s try to understand how ruby finds a method. Taking the example of the Array class only, let’s say we call some method on an instance of Array. First, ruby will check if the method is available in the Array class. If it’s not, it’ll go up the ancestry chain to try and find the method. Let’s look at the following diagram to understand this better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqdFnBl64sR7yMNjOCIwIg.jpeg" /></figure><pre>obj = []<br>obj.method_name()</pre><p>Let’s assume the following lines of code. obj is an instance of Array . We call method_name on obj. First, ruby will go into the respective class of obj . If it can find this method there, it’ll run it else it’ll go up the ancestor chain. It’ll look in the superclass Enumerable , followed by Object and finally BasicObject . You’ll notice Kernel module in between. It’s not a superclass relation but a module inclusion. When a module is included in a class, it gets added to the object’s ancestry chain.</p><p>We can include modules inside classes using prepend and include methods. Let’s briefly look into the differences between the two.</p><h4>Prepend vs Include</h4><pre>class MyClass<br>  include ModuleA<br>  include ModuleB<br>end</pre><p>If we check the ancestry chain of MyClass , we’ll find that module B comes above module A in the chain. The ancestry chain for MyClassis as follows: [MyClass, ModuleB, ModuleA, Object, Kernal, BasicObject] .</p><p>Let’s see what happens to the ancestry chain if we use the prepend instead of include.</p><pre>class MyClass<br>  prepend ModuleA<br>  prepend ModuleB<br>end</pre><p>The ancestry chain for MyClass is now [ModuleB, ModuleA, MyClass, Object, Kernal, BasicObject] . ModuleBand ModuleAcome before MyClass now. So now the method lookup will first check in the modules before checking the class of the object.</p><p>I hope this helped you understand a better idea of how method calls work under the hood in ruby. In the next part, we’ll dive even deeper in the idea of classes and modules.</p><h3>Previous Part</h3><p><a href="https://medium.com/@alwayswannaly/a-deep-dive-into-rubys-object-model-pt-1-6dcddfba37b4">A Deep dive into Ruby’s Object Model, Pt 1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b2711607f7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep dive into Ruby’s Object Model, Pt 1]]></title>
            <link>https://blog.devops.dev/a-deep-dive-into-rubys-object-model-pt-1-6dcddfba37b4?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dcddfba37b4</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[object-model]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 22:42:40 GMT</pubDate>
            <atom:updated>2023-03-11T09:15:07.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby is a dynamic, interpreted, object-oriented programming language.</p><p>One of the defining features of Ruby is its object-oriented nature. In Ruby, everything is an object, including data types like integers and strings. This means that you can treat these types just like any other object in Ruby, which makes the language highly flexible and expressive. Ruby is duck typed, meaning we don&#39;t check for types on objects rather, we check which methods they respond to. This is an important distinction as types in ruby can change on the fly in runtime ;)</p><p>This core strength and flexibility ruby provides comes from the object model. In this article, we’ll explore what exactly is this object model that makes ruby so powerful and flexible</p><h3>Runtime vs Compile Time</h3><p>Before we dive into the object model, let’s first understand the core differences between languages like C++ and Ruby. In compiled languages, language constructs, i.e. functions, variables, etc lose their existence once the compiler is done compiling the code and they become just some location on the memory. At runtime, there’ll be very few language constructs available.</p><p>However, in languages like ruby, the runtime is filled with language constructs. At any point of time during code execution, you can ask a class for its list of instance methods, or ask it about itself. This is called <strong>introspection</strong>. You can even change how a method behaves at runtime! This behavior, a code that can manipulate itself at runtime is known as <strong>metaprogramming.</strong></p><p>The amount of support ruby provides for metaprogramming and introspection is unreal. This is all possible cause there’s no distinction between language constructs that are available at runtime and compile time since ruby has no compile time at all.</p><h3>Object in Ruby</h3><p>The very basic entity in ruby is an object. You can also say, everything in the ruby world is an object. Let’s try to understand this by an example.</p><pre>class Greeter<br>  def initialize(locale)<br>    @locale = locale<br>  end<br><br>  def name=(name)<br>    @name = name<br>  end<br>end<br><br>greeter_obj = Greeter.new(&quot;EN&quot;)<br>greeter_obj.class                 # =&gt; &quot;Greeter&quot;<br>greeter_obj.instance_variables    # =&gt; [:@locale]<br>greeter_obj.name = &quot;Shubham&quot;<br>greeter_obj.instance_variables    # =&gt; [:@locale, :@name]<br>greeter_obj.methods.grep(/name/)  # =&gt; [:name=]</pre><p>If we open greeter_obj and look into IRB, we can see the object has instance variables. The instance variable @name came into existence as soon as we called the name method. Instance variables can be thought of as a simple key-value pair in a Hash that can be different for different objects. Along with instance variables, objects also have methods. We can use Object#methods to check for the list of methods. Most objects will inherit a number of common methods like [:instance_variables, :to_s, is_nil?, ...] . If we use Array#grep to filter our method name, we’ll see its presence. However, if we were to look into the actual internals of ruby interpreter, we’ll realize that this greeter_obj does not carry any list whatsoever for methods. An object only carries its own instance variables and a reference to the class since every object belongs to a class (or is an instance of a class). If we think about this for a minute, objects that are sharing the same class, i.e, all objects initialized via Greeter#new will share the same methods as defined in Greeter , hence methods must be stored in Greeter and not instances of Greeter . Paraphrasing this, we can say</p><blockquote>Objects that share the same class also share the same methods, so the methods must be stored in the class, not the object.</blockquote><p>Let’s look at the diagram below to get a better understanding and take a look at the very basic understanding of our ruby object model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DD1oQDmjgQzFTVHGTg-eg.jpeg" /></figure><ul><li>To summarize, greeter_obj is an object that references class Greeter .</li><li>greeter_obj maintains its own instance variables, and the method name= is defined in Greeter class. In ruby terminology, we call such a method <strong>instance method</strong> of Greeter class, meaning we need an instance of the class like greeter_objto actually execute the method.</li><li>With respect to greeter_obj , name= would just be called <strong>method</strong> of the object.</li></ul><p>Let’s take a look at this example to hammer down this concept</p><pre>Array.instance_methods == [].methods  # =&gt; returns true<br>Array.methods == [].methods           # =&gt; returns false</pre><h3>Classes in Ruby</h3><p>Now that we understand what an object is, let’s look at what a class in ruby is. Oh, wait, didn&#39;t I say before that everything in the ruby world is an object? So wouldn&#39;t that mean that a class is also an object? Yes absolutely!<br>A class in ruby is nothing but just an Object ;)</p><p>So since classes are also objects, everything that is applied to objects will also apply to classes. They will also reference a class just like objects. If you were to enquire about Greeter.class in IRB, you’ll see that its class is called Class . Methods of an object, in this case Greeter are nothing but instance methods of their class, i.e. Class</p><p>If we check instance methods of Class , we’ll find the following methods are available — [:new, :allocate, :superclass] . We regularly use Class#new to initialize objects from a class. Class#superclass is related to the concept of inheritance. Calling a superclass on a ruby class will tell you from which class it was inherited. With this newfound wisdom, let’s turn on the IRB and try to infer the superclass relations between these different objects.</p><pre>Greeter.class          # =&gt; Class<br>Class.superclass       # =&gt; Module<br>Module.superclass      # =&gt; Object<br>Object.superclass      # =&gt; BasicObject<br>BasicObject.superclass # =&gt; nil</pre><p>We see a bunch of new stuff here. First let’s discuss Module, which is the superclass of Class . A Class is nothing but just a module with 3 extra methods which we saw just above — [:new, :allocate, :superclass] which allows us to create objects. You might be wondering, why bother having a Module class, when Class is already there? Well, the idea behind having a distinction between Modules and Classes is to provide better clarity while organizing code. Usually, we pick a Module if we want it to be included somewhere but we’ll pick a class if it needs to be initialized or if we need to provide some form of hierarchy through inheritance.</p><p>Object is the default root of all ruby objects. It inherits from BasicObject which was recently introduced in ruby 1.9. It includes even lesser methods than Object and is often ideally used as a bare-bones class if we need to keep our classes unpolluted from ruby standard methods. Object class includes an important Kernel module into itself that provides methods like puts as an instance method. Since ruby code is always executed in, you guessed it right, an Object, (writing self.class in IRB console will give back “Object”), putslooks like it’s a reserved keyword whereas it’s just a method available to all objects of Object class. You can even define your own methods in Kernel module and they will be available everywhere in your ruby environment.</p><h3>Wrapping Up</h3><ul><li><strong>Object: </strong>It has its own instance variables and a reference to the class that initialized it. The object’s methods aren’t part of the object but they are defined in the object’s class, where they are called instance methods of the class.</li><li><strong>Class: </strong>It’s an object (instance of Class ), having instance methods (we also call instance methods of a class as class methods) and a reference to the superclass. Also like any object, classes must be accessed by references. We already have a constant reference to each class, the class name.</li></ul><p>Let’s present the rudimentary object model, based on our current knowledge. This is still incomplete but forms the core of Ruby’s Object Model and is a good point to deepen our understanding of how ruby works under the hood, and yes, a Class ‘s class is Class itself ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T92g82YeF_pb5yBr5MjlLA.jpeg" /></figure><p>In the next article, we’ll actually look at how method calls happen in ruby using this Object Model. If you liked this content, you can follow me to know when the next article is out 🥳</p><h3>Next Part</h3><p><a href="https://medium.com/@alwayswannaly/a-deep-dive-into-rubys-object-model-pt-2-3b2711607f7d">A Deep dive into Ruby’s Object Model, Pt 2</a></p><h3>References</h3><ul><li>Metaprogramming (Ruby) by Paolo Perrotta</li><li><a href="https://dev.to/adamlombard/ruby-class-methods-vs-instance-methods-4aje">https://dev.to/adamlombard/ruby-class-methods-vs-instance-methods-4aje</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dcddfba37b4" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/a-deep-dive-into-rubys-object-model-pt-1-6dcddfba37b4">A Deep dive into Ruby’s Object Model, Pt 1</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied Event-driven programming with C++]]></title>
            <link>https://medium.com/@alwayswannaly/applied-event-driven-programming-with-c-b2f6977f0b72?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f6977f0b72</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[callback]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 18:03:17 GMT</pubDate>
            <atom:updated>2023-02-21T18:03:17.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_kOimgiWFWuf9f-D" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaryanphoto?utm_source=medium&amp;utm_medium=referral">Joshua Reddekopp</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Event-driven programming is a popular programming model where instead of the usual execution of instructions in sequential order, the flow control of the code is determined via events. Event-driven programs should be able to detect and react to events in near real-time.</p><p>One of the most popular examples of an event-driven model is our web browser. We make extensive use of event listeners on the web to respond to browser or user events for delivering an immersive experience for the end users. The event-driven model can easily break down complex application logic into simple instructions.</p><p>Most of the event-driven models work on the concept of callbacks. If you’re from the domain of web development, you might already be familiar with what a callback is. Let’s take a dive into how an event-driven programming model functions at its core. We’ll borrow some basic STLs from C++ to help implement us a simple but very powerful EventManager Interface.</p><h3>EventManager Interface</h3><p>We’ll implement a very basic EventManager interface in C++. Before we can start, let’s understand and iron out the basic things we’ll be needing.</p><p>Just like javascript, functions in C++ are first-class citizens. This fancy term means that functions can be stored in variables and can also be passed around to other functions! In C/C++ we can use a pointer to a function to store a reference to the function. Let’s say we want to store a reference to a function in fptr , which returns an integer and takes two float arguments, our syntax for the same would be int (*fptr)(float, float) . You can learn more about function pointers <a href="https://www.scaler.com/topics/cpp/function-pointer-cpp/">here</a>.</p><p>We’ll be using std::map STL for storing all registered events and their listeners. Our events object would store “event_name” as the key and std::vector of function pointers as value. Below is a sample structure of our events object, where f1, f2, f3, f4, and f5 are pointers to functions.</p><pre>{<br>  &quot;event1&quot;: [fp1, fp2, fp3],<br>  &quot;event2&quot;: [fp4, fp5]<br>}</pre><p>For this tutorial, we’ll be assuming our callbacks will have the signature of void (*callback)(int) . You can even have variable arguments to a callback :)</p><p>We’ll have two member functions in our EventManager interface:</p><ul><li>EventManager *on(std::string event_name, void (*callback)(int)) <br>This method will take in an event_name along with a callback and register this callback as one of the listeners to the event. It’ll return a pointer to itself. This will help us chain the method calls. Eg -&gt; event_manager-&gt;on(..)-&gt;on(..)-&gt;emit(..)</li><li>bool emit(std::string event_name, int arg) <br>This method will take an event_name and an argument. This will invoke all the listeners that are associated with this event and will return true if emitting succeeded. It’ll pass the arg to our callback functions.</li></ul><p>Now, we’re ready to look at the implementation,</p><pre><br>// app/event_manager.hpp<br><br>#ifndef EVENT_MANAGER<br>#define EVENT_MANAGER<br><br>#include &lt;algorithm&gt;<br>#include &lt;vector&gt;<br>#include &lt;map&gt;<br><br>class EventManager {<br><br>private:<br>    std::map&lt;std::string, std::vector&lt;void (*)(int)&gt; &gt; events;<br><br>public:<br>    EventManager() {}<br><br>    EventManager *on(std::string event_name, void (*callback)(int)) {<br><br>        // we&#39;re using a pointer to reference `events[event_name]` so as<br>        // to get reference to original object and not the copy object.<br>        std::vector&lt;void (*)(int)&gt; *listeners = &amp;events[event_name];<br><br>        // if this listener is already registered, we wont add it again<br>        if (std::find(listeners-&gt;begin(), listeners-&gt;end(), callback) != listeners-&gt;end()) {<br>          return this;<br>        }<br><br>        listeners-&gt;push_back(callback);<br><br>        return this;<br>    }<br><br>    bool emit(std::string event_name, int arg) {<br>        std::vector&lt;void (*)(int)&gt; listeners = events[event_name];<br><br>        if (listeners.size() == 0) return false;<br><br>        // Run all the listeners associated with the event<br>        for (int idx = 0; idx &lt; listeners.size(); idx += 1) {<br>            listeners[idx](arg);<br>        }<br><br>        return true;<br>    }<br>};<br><br>#endif</pre><h3>Testing our Interface</h3><p>Let’s use the following simple snippet to test out our interface</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.interviewbit.com%2Fembed%2Fsnippet%2Faf91e5153bea5d556b96&amp;display_name=Interviewbit&amp;url=https%3A%2F%2Fwww.interviewbit.com%2Fsnippet%2Faf91e5153bea5d556b96%2F&amp;image=https%3A%2F%2Fibassets.s3.us-west-2.amazonaws.com%2Fstatic-assets%2Fpractice-page-og.webp&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=interviewbit" width="700" height="375" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bf10a9064dcc579828b5857437f0df8/href">https://medium.com/media/2bf10a9064dcc579828b5857437f0df8/href</a></iframe><p>We’re able to attach multiple listeners to a single event which gives us immense flexibility in what we want to do when a particular event is fired. In fact, by using a priority queue instead of an array, we can even define an order in which event execution should occur post-firing of the event.</p><p>EventManager interface could be used to create global event managers as well. So you can fire events from multiple files and define callbacks that should be executed on certain events. A few of the use cases of this powerful pattern are as follows</p><ul><li><strong>Modeling Lifecycle Methods: </strong>Designing lifecycle methods in your program like “before_end”, “after_end”, and “after_render” can be very simple by leveraging event-driven programming.</li><li><strong>Reacting to User Events: </strong>Events like mouse clicks, keystrokes, and other user actions are best modeled by event-driven programming</li></ul><h3>References/Further Reading</h3><ul><li><a href="https://www.scaler.com/topics/cpp/function-pointer-cpp/">https://www.scaler.com/topics/cpp/function-pointer-cpp/</a></li><li><a href="https://aiven.io/blog/introduction-to-event-based-programming">https://aiven.io/blog/introduction-to-event-based-programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f6977f0b72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pub/Sub Streams in Ruby using Redis]]></title>
            <link>https://medium.com/@alwayswannaly/redis-pub-sub-streams-in-ruby-f87c86dbc4c2?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/f87c86dbc4c2</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 21:55:11 GMT</pubDate>
            <atom:updated>2023-02-18T23:31:24.324Z</atom:updated>
            <content:encoded><![CDATA[<p>The publisher/subscriber pattern (pub/sub for short) is an asynchronous and scalable way to deliver messages to clients from various sources. A message is not sent to a specific receiver but rather is broadcasted out to certain channels irrespective of the number of subscribers. In a similar way, subscribers express interest in specific channels and receive messages from those channels only irrespective of publishers.</p><p>Let’s go step by step on how you can leverage pub-sub streams using redis for your ruby applications.</p><h3>Implementing a PubSub Interface</h3><p>We’ll be creating a PORO (plain old ruby object), so you can plug and play with it in any ruby application you want. There will be a few prerequisites for our interface, we’ll de requiring the <a href="https://github.com/redis/redis-rb">redis-rb</a> gem and optionally the <a href="https://github.com/ruby/logger">logger</a> gem (for logging to STDOUT or STDERR).</p><p>We’ll have two methods for our interface PubSub . You can refer the code for our interface below</p><ul><li>PubSub.subscribe(channel_name, &amp;block) This method will call redis’s <em>psubscribe</em> method to establish a blocking connection. You can subscribe to as many channels as you want but we’ll be doing that on separate threads so as to not block our application’s main thread.</li><li>PubSub.publish(channel_name, message) This method will publish a message to a channel. This is NOT a blocking connection and will effectively return 1 when the publish is successful and return 0 if the publish fails (Eg, no active subscribers for the channel).</li></ul><pre># app/pub_sub.rb<br><br>require &#39;redis&#39;<br>require &#39;logger&#39;<br><br>class PubSub<br>  class ParamsMustBeStringError &lt; StandardError<br>    def initialize<br>      super(&quot;Params passed to publish must be string&quot;)<br>    end<br>  end<br><br>  class &lt;&lt; self<br><br>    # You can pass the channel name or use pattern for channel name<br>    # to subscribe method. `pattern` will point to the pattern<br>    # that was used in subscribe method, `event` will contain the<br>    # actual event name and data will contain the data associated with<br>    # the event. Please not that this WILL BE A blocking connection<br><br>    def subscribe(channel_name)<br>      logger.info(&quot;Subscribing to #{channel_name}&quot;)<br><br>      connection.psubscribe(channel_name) do |on|<br>        on.pmessage do |pattern, event, data|<br>          yield(pattern, event, data)<br>        end<br>      end<br>    end<br><br>    # Returns 1 if publish was successful else will return 0<br>    # Will raise error if message is not of type String<br><br>    def publish(channel_name, message)<br>      raise ParamsMustBeStringError unless message.is_a?(String)<br><br>      connection.publish(channel_name, message)<br>    end<br><br>    private<br><br>    # We should use a connection_pool here<br>    # instead of directly calling Redis.new<br><br>    def connection<br>      Redis.new(url: redis_uri)<br>    end<br><br>    def redis_uri<br>      return @redis_uri unless @redis_uri.nil?<br><br>      @redis_uri = ENV[&#39;REDIS_URI&#39;] || &#39;redis://localhost:6379/&#39;<br>    end<br><br>    def logger<br>      @logger ||= Logger.new(STDOUT)<br>    end<br>  end<br>end</pre><h3>How to use PubSub Interface?</h3><p>We have our interface ready. Now let’s look at how we can use it for sending/receiving messages in our pub-sub model</p><h4>Publisher</h4><p>A publisher is a simple entity. It could be a function call PubSub.publish(channel_name, message) from anywhere in a ruby codebase, even an IRB session or rails console.</p><h4>Subscriber</h4><p>Below is a sample implementation of a subscriber.</p><pre># app/subscriber.rb<br>require_relative &#39;./pub_sub&#39;<br><br>logger = Logger.new(STDOUT)<br><br># Normally, output is not immediately written to STDOUT but<br># instead is buffered and is only written in bulk. For logs,<br># we would want the output to be immediately flushed to STDOUT<br># so we can write them to a file.<br>$stdout.sync = true<br><br>PubSub.subscribe(&#39;my_channel&#39;) do |pattern, event, data|<br>  begin<br>    logger.info(&quot;Received event: #{event} with arguments #{data}&quot;)<br>    <br>    # Handle the event as you like<br>  rescue =&gt; e<br>    logger.error(e.message)<br>  end<br>end</pre><p>It’s interesting to note that since PubSub.subscribe(channel_name, &amp;block) is a blocking call, we’ll need to handle calling this method in a different way. This method should ideally be running in its own thread, so if we have N subscribers, we’ll be spawning N threads to handle the subscriptions.</p><p>We’ll be using nohup , short for no hang-up, a command in Linux systems that keep processes running even after exiting the shell or terminal. Nohup prevents the processes or jobs from receiving the SIGHUP (Signal Hang UP) signal. Below is a script we can use to start our process as a daemon in its own thread and log the execution details to a file</p><pre>#!/usr/bin/env bash<br><br># app/pub-sub.sh<br><br># Start the subscriber as a daemon and write all logs to app/pub_sub.log<br>nohup ruby subscriber.rb &gt; pub_sub.log 2&gt;&amp;1 &amp;<br><br># Store the pid of the process in a file so you can find it easily<br># $! references to the pid of the child process<br>echo $! &gt; app/pubsub.pid<br></pre><h3>Testing our Interface</h3><p>Below is a simple demo to test things out. I’ll be using ruby 2.7.2</p><p>First, we’ll spin off our daemon process by running the bash script pub-sub.sh from our /app directory. When we’ll run this script, we’ll notice a log file pub_sub.log has been created for us.</p><p>Now, as publishers, we can use multiple IRB consoles or just call them out from any place in a ruby codebase. After starting an IRB session, we can write these lines of code to publish messages to our channels.</p><pre>&gt;&gt; require_relative &#39;./pub_sub&#39;<br>=&gt; true<br><br>&gt;&gt; PubSub.publish(&#39;my_channel&#39;, &#39;from irb1&#39;) # From Shell 1<br>=&gt; 1 # Successfully published the message<br><br>&gt;&gt; PubSub.publish(&#39;my_channel&#39;, &#39;from irb2&#39;) # From Shell 2<br>=&gt; 1 # Successfully published the message<br><br>&gt;&gt; PubSub.publish(&#39;new_channel&#39; &#39;should not reach&#39;)<br>=&gt; 0 # Since this channel doesn&#39;t exist, we get back 0 </pre><p>As a final thing, we’ll tail the log file created by our process to check whether we’re receiving these events or not via the tail command<br>tail -f pub_sub.log</p><pre>I, [2023-02-19T03:02:48.201224 #66178]  INFO -- : Subscribing to my_channel<br>I, [2023-02-19T03:03:11.576438 #66178]  INFO -- : Received event: my_channel with arguments from irb1<br>I, [2023-02-19T03:03:56.040073 #66178]  INFO -- : Received event: my_channel with arguments from irb2<br></pre><h3>Conclusion</h3><p>As you can see, this is a very powerful pattern that we can leverage across so many different types of ruby apps. Ruby on Rails would be one of the prime candidates that can leverage this pattern. This pattern can especially come in handy in multi-instance web servers for distributed messaging, secure RPC framework, data streaming from different applications, distributed cache invalidation, and many many more.<br>The possibilities are endless 🚀</p><h3>References</h3><ul><li><a href="https://cloud.google.com/pubsub/docs/overview">https://cloud.google.com/pubsub/docs/overview</a></li><li><a href="https://redis.io/docs/manual/pubsub/">https://redis.io/docs/manual/pubsub/</a></li><li><a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f87c86dbc4c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building DynamoDB to Redshift Ingestion Pipeline]]></title>
            <link>https://medium.com/@alwayswannaly/building-dynamodb-to-redshift-ingestion-pipeline-a7b82093a79f?source=rss-5af7ccb22803------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7b82093a79f</guid>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[kinesis-firehose]]></category>
            <dc:creator><![CDATA[Shubham Anand]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 16:33:31 GMT</pubDate>
            <atom:updated>2023-01-28T16:31:55.999Z</atom:updated>
            <content:encoded><![CDATA[<p>DynamoDB is a NoSQL fully managed database provisioned by Amazon. It provides high availability and can automatically scale up to any load thrown at it. While, DynamoDB is great when it comes to building low latency — high load systems, it’s not a great tool for running ad-hoc analytics queries. We would ideally want to complement dynamo DB with some other tool that will handle the analytics part. In this tutorial, we’ll be exporting data from dynamo DB to redshift using dynamo DB streams, lambda functions, and Kinesis Firehose without affecting the performance of DynamoDB in any way.</p><h3>Requirements</h3><p>Let’s first list down our requirements:</p><ul><li>It’s okay if data from DynamoDB is not available with redshift in real-time. We’ll be fine if it takes up to 30 mins for data to be available in redshift. We’ll be aiming for eventual synchronization.</li><li>We need to support all three operations — INSERT, MODIFY and REMOVE to be propagated to redshift and we must make sure that the order of these operations is maintained. Most tutorials that integrate with Kinesis firehose will only support INSERT operations to redshift and will not keep your tables in sync.</li></ul><h3>Sending Data from DynamDB to Kinesis Firehose</h3><h4>Enabling DynamoDB Streams</h4><p>First things first, we will need to enable DynamoDB streams. DynamoDB streams provide us with information whenever any operation takes place on the database. Eg, any item inserted/updated/deleted, will also be sent to this stream to be consumed by other services/processes. It is guaranteed that streams will deliver data in the same order it was performed on DynamoDB. This is an important requirement for us since we’re supporting different kinds of operations. Enabling streams on a dynamo DB table:</p><ul><li>Select your DynamoDB table from your AWS console.</li><li>Go to the “<em>exports and streams”</em> tab.</li><li>Scroll down till you can see DynamoDB stream details. From here you can enable the DynamoDB stream. Make sure to have the stream view type as either “New and Old Image” or “New Image”. This will ensure that you always have the whole record present in New Image.</li></ul><h4>Create a Kinesis Data Firehose Delivery Stream</h4><p>Next, we’ll create a Kinesis firehose data delivery stream. We’ll be sending our data here from our DynamoDB stream. Kinesis Firehose will buffer the data automatically for us and will provide us with consistent ordering. We’ll store this in an S3 bucket from where we’ll be constantly syncing the items to a redshift bucket. This will ensure that QPS on redshift due to our pipeline setup is as minimal as possible, i.e. API calls on redshift to insert/delete/update data are low. To create a delivery stream for kinesis firehose,</p><ul><li>Search for Kinesis firehose on your AWS console and click “<em>Create delivery stream”</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTO07iUrzdkHBGJmf2c9Qg.png" /></figure><ul><li>Select source as “Direct PUT” and destination as Amazon S3. Give a name to this stream. Select an s3 bucket and choose other settings according to your likening.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvKNyXbNEhfVqED8t9-oMQ.png" /></figure><ul><li>Finally, click on “Create delivery stream” at the bottom-most, and your delivery stream is ready to receive data.</li></ul><h4>Creating a Lambda Function</h4><p>Next, we need to create a lambda function that will process the data received in the dynamo DB stream and send it to the Firehose delivery stream.</p><ul><li>Go to Lambda Functions from your AWS console and click on create function. Here, you can author the function from scratch. Make sure to have your runtime set as Python 3.9 (This tutorial is following Python 3.9, feel free to have any runtime and make changes to your code accordingly)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHIEvaOCNdvuBU54QYtT_w.png" /></figure><ul><li>In the file, lambda_handler.pyadd the following code. This will process the batched data received from the stream and send it to the firehose delivery stream which will ultimately write the data to an S3 bucket. Note that we’re also storing the operation, INSERT/MODIFY/REMOVE in Firehose, this will help us with forming queries when we will ingest this data to redshift from the S3 bucket.</li></ul><pre>import json<br>import boto3<br>import logging<br>from deserializer import loads<br><br># Setup Logger<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br># Setup firehose client<br>firehose_client = boto3.client(&#39;firehose&#39;)<br><br># Constants<br>dynmodb_table_name = &quot;&lt;DYNAMODB_TABLE_NAME&gt;&quot;<br>delivery_stream_name = &quot;&lt;FIREHOSE_DELIVERY_STREAM_NAME&gt;&quot;<br><br>def lambda_handler(event, context):<br>    events = []<br>    <br>    for record in event[&#39;Records&#39;]:<br>        event_name = record[&#39;eventName&#39;]<br>        ddb_record = loads(record[&#39;dynamodb&#39;])<br>        kinesis_record = {<br>            &#39;keys&#39;: ddb_record.get(&#39;Keys&#39;),<br>            &#39;data&#39;: ddb_record.get(&#39;NewImage&#39;),<br>            &#39;timestamp&#39;: ddb_record.get(&#39;ApproximateCreationDateTime&#39;)<br>        }<br>        logger.info(&#39;Record: &#39; + json.dumps(ddb_record))<br>        events.append({ event_name: kinesis_record })<br><br>    firehose_client.put_record(<br>        DeliveryStreamName = delivery_stream_name,<br>        Record = { &#39;Data&#39;: json.dumps(events) + &#39;\n&#39; }<br>    )<br>    <br>    return &#39;processed {} records.&#39;.format(len(events))</pre><ul><li>Also, create a file deserializer.py and paste the contents of this <a href="https://github.com/Alonreznik/dynamodb-json/blob/master/dynamodb_json/json_util.py">file</a> there. This is a good python library for performing object conversion from DynamoDB object to JSON. We can also use lambda layers to include this library but this is much simpler to do.</li><li>Before we can run our lambda code or attach the trigger for invocation, we need to set up the appropriate permissions. Note that we should never give a lambda function access to all the permissions and only provide granular access.</li><li>Go to Configuration and select Permissions from the left panel. You’ll see your default execution role that must have been created while creating the lambda function. Click on the link below the Role Name. This will open the IAM permissions on your AWS console.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1At0fVis7nDWmlanlc9nTA.png" /></figure><ul><li>From the IAM console, click on Add permissions -&gt; Attach Policies. From here, click on Create Policy. Go to JSON editor. You’ll see a console like this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnLd22Db71Tp7cASX-cB6Q.png" /></figure><ul><li>Now we need to create 2 policies, one for allowing our lambda function to be able to interact with dynamo DB and one policy for allowing our lambda function to use PUT operation on Kinesis firehose. Following is the JSON version of the granular policy you can use, you can create two separate policies too.</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;dynamodb:DescribeStream&quot;,<br>                &quot;dynamodb:GetRecords&quot;,<br>                &quot;dynamodb:GetShardIterator&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:dynamodb:&lt;DYNAMODB_IDENTIFIER&gt;/*&quot; <br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;dynamodb:ListStreams&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;firehose:PutRecord&quot;,<br>                &quot;firehose:PutRecordBatch&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:firehose:&lt;FIREHOSE_IDENTIFIER&gt;&quot;<br>        }<br>    ]<br>}</pre><ul><li>Two things to note about the above policy definition, make sure to have a trailing /*after your dynamo DB arn since we have to give permission to the dynamo DB stream originating from your dynamo DB and not the database itself. You can also use Resource: &quot;*&quot; in the above configurations. Now go ahead and create your permissions.</li><li>The last thing to do is to create a trigger for our lambda function. Go to your lambda function and click on Add Trigger. Your source will be DynamoDB and select your table and batch size. After this, click on Add. This will set up your trigger and now your DynamoDB -&gt; Kinesis data pipeline is ready</li><li>To test the code, simply select test on your lambda console and click configure test event. In the template, you can search for “DynamoDB Update” and use it. Save this test event, deploy your code, and run the Test.</li></ul><p>Now we’ll get buffered data written to our designated S3 bucket via Kinesis Firehose on all operations done in our DB. We’re done with the first part of our tutorial. Now for the next part of the tutorial, we’ll be sending data from S3 to redshift.</p><h3>Syncing S3 Data to Redshift</h3><p>Now that we have dynamo DB streaming and persisting data to an s3 store, we can look towards syncing the data being written to s3. Here’s a sample GitHub repository that you can follow for setting up the syncing infrastructure: <a href="https://github.com/alwayswannaly/s3-redshift-bridge">https://github.com/alwayswannaly/s3-redshift-bridge</a></p><ul><li>We’ll be provisioning an EC2 instance to periodically dump the data from our s3 bucket into redshift in a predictable manner. We’ll be using <a href="https://www.npmjs.com/package/pm2">PM2</a>, a process manager for periodically running and monitoring our data dump, and will also integrate it with sentry for getting notified of any errors.</li><li>We’ll process all the entries inside an s3 item, and perform a batched operation on redshift. After successfully performing an operation, we’ll create and save some form of checkpoint to know till which record we have processed the data. Please note, the way we have set up the kinesis stream, we’ll get our data in an ordered way, since the items would be naturally ordered by the timestamp via their names.</li><li>We’ll need to assign an appropriate role to our EC2 instance to be able to interact with our s3 bucket. We can use the following fine-grained policy document to provide just the essential permissions.</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:ListBucket&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::&lt;S3_BUCKET_NAME&gt;/*&quot;,<br>                &quot;arn:aws:s3:::&lt;S3_BUCKET_NAME&gt;&quot;<br>            ]<br>        }<br>    ]<br>}</pre><ul><li>A sample ecosystem.config.js file for running our process as a cron is as follows. This will run our script periodically every 5 mins. You can adjust this time in accordance with your own needs.</li></ul><pre>module.exports = {<br>  apps: [{<br>    name: &quot;s3-redshift-bridge&quot;,<br>    script: &quot;python3 /home/ec2-user/s3-redshift-bridge/src/main.py&quot;,<br>    watch: true,<br>    env: {<br>      REDSHIFT_HOST: &quot;&lt;REDSHIFT_HOST&gt;&quot;,<br>      REDSHIFT_DATABASE: &quot;&lt;REDSHIFT_DATABASE&gt;&quot;,<br>      REDSHIFT_PORT: &quot;&lt;REDSHIFT_PORT&gt;&quot;,<br>      REDSHIFT_USER: &quot;&lt;REDSHIFT_USER&gt;&quot;,<br>      REDSHIFT_PASSWORD: &quot;&lt;REDSHIFT_PASSWORD&gt;&quot;,<br>      REDSHIFT_TABLE_NAME: &quot;&lt;REDSHIFT_TABLE_NAME&gt;&quot;,<br>      S3_BUCKET_NAME: &quot;&lt;S3_BUCKET_NAME&gt;&quot;,<br>      SENTRY_BACKEND_DSN: &quot;&lt;SENTRY_BACKEND_DSN&gt;&quot;<br>    },<br>    instances: 1,<br>    exec_mode: &#39;fork&#39;,<br>    cron_restart: &quot;*/5 * * * *&quot;,<br>    autorestart: false<br>  }]<br>}js</pre><p>NOTE: Make sure that the security group of your ec2 instance is whitelisted to interact with your redshift cluster</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7b82093a79f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>