<?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 Aryan Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Aryan Srivastava on Medium]]></description>
        <link>https://medium.com/@distroaryan?source=rss-31f9f3175c80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZYX57MsQMsziIbFPSDnkww.jpeg</url>
            <title>Stories by Aryan Srivastava on Medium</title>
            <link>https://medium.com/@distroaryan?source=rss-31f9f3175c80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:11:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@distroaryan/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[Redis Caching — Everything you need to know about using redis as a cache db]]></title>
            <link>https://medium.com/@distroaryan/redis-caching-everything-you-need-to-know-about-using-redis-as-a-cache-db-cc8d640b4fb0?source=rss-31f9f3175c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc8d640b4fb0</guid>
            <dc:creator><![CDATA[Aryan Srivastava]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 02:50:21 GMT</pubDate>
            <atom:updated>2026-06-14T19:20:53.400Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Redis caching</strong> looks simpler from the high level but in reality it is one of the most complex and marvel’s of engineering. Here we will not dive into code but I will try to cover every problem that you might encounter when adding redis as a cache dB in your product. Here’s a famous quote from a very famous engineer. Let’s begin -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qj9YO1GhLc1MXHeCT7HXqA.png" /></figure><p><strong>Caching</strong>, in general, is used to reduce the load on our primary database and improve the response time of our read operations. <strong>Databases</strong> like <strong>MongoDB</strong> and <strong>Postgres</strong> don’t perform very well under high loads because they are designed more for consistency than raw speed. Redis, on the other hand, is built for speed since it serves data from memory<strong> (RAM)</strong> instead of reading it from disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48SBEAjar8LyYQf8qQM_Kg.png" /></figure><h3>Caching Patterns</h3><p>In software engineering there is no perfect or correct universal pattern for everything, every pattern has a <strong>tradeoff</strong> and understanding that tradeoff helps us decide on a better strategy best suited for the situation.</p><h3>1. Cache aside pattern (lazy-loading)</h3><p>This is the most common pattern used in redis. When requesting any data, the application checks the cache first. On a miss, it loads from the database and populates the cache. During a <strong>write operation</strong> we simply delete the associated cache key in our redis db so that during the time of read it will fetch the newly updated data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4galVgOx8Z-D4uPSG2Dyw.png" /></figure><p>This is used when we want to optimise the system for <strong>read heavy operations</strong>. But the first request for any data will be relatively slow since we will be querying 2 databases (cache + primary) so 2 network hops.</p><h3>2. Write-through pattern</h3><p>This pattern is used when we want <strong>strong consistency</strong> between our cache and primary database. During a write operation, we write the new values to both the primary database and the cache simultaneously.</p><p>Because of this, write latency takes a hit since we’re writing to two systems. The read operation remains fast since the cache is always up to date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hu30bWEcHRIsp1qeWkTP2w.png" /></figure><p>This pattern is useful in systems where we can tolerate slightly higher write latency in exchange for consistent reads.</p><h3>3. Write back pattern (Write-behind)</h3><p>This pattern is rarely used and you will see why. During a write operation we only write our new values to the cache dB and a background worker is used to sync the primary db and cache db.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhRDLuXuytD-hN2sHMWpTQ.png" /></figure><p>The obvious downside are -</p><ul><li>If redis goes down before the worker can sync our primary db we will experience data loss</li><li>Extra worker overhead needed.</li><li>Less consistency between the cache and primary database</li></ul><p>This is mainly used when write operations are heavy and directly writing to the main database is not feasible.</p><p>These are generally the most famous pattern you will find on the internet .Now let’s recap till here —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AC2SzxOwzxjPgDiOFeFEA.png" /></figure><p>Now we have seen the famous cache pattern, let’s dive deeper and try to understand the scenarios where these scenarios will break and in some worst cases it bring down our primary database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYGiPzyXzxOsca769FS79g.png" /></figure><h3>1. Cache Penetration</h3><p>Let’s say we are building a user service, we store the user data in redis using a user key.</p><p>If the user with the user key is not present in our primary database and someone requests this user info, our server will first perform the lookup in cache then in primary and then return null.</p><p>It looks harmless but let’s say 10k non existent keys are requested, those 10k requests will essentially bypass our cache and will reach the primary db, the main reason for introducing the redis to absorb the spike is failed. So how do we solve this, well there are several methods depending upon at which scale we are operating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAZCUawK9skXdmjx7n3PrA.png" /></figure><h3>A. Cache non existent keys</h3><p>It’s simple and effective, whenever a request for a key comes, just cache that non existent as null in our redis db with a relatively smaller TTL (time to live), so the next time the request comes the redis will return the request and our primary db will be safe.</p><p>Every non existent key first reaches our primary database and then redis caches that as non existent to return null the next times it gets requested. So to explain with our above scenario if 10k different non existent key comes they will still reach our primary db and only then they will be cached.</p><p>This works fine at a load of about 1M records because non existent keys can be cached with very less TTL so the read write speed will be fast along with our storage. But let’s say the scale reaches Billions, where the processing those requests in redis can be expensive, then we need our second approach.</p><h3>B. Bloom Filters (BF)</h3><p>It is only used at Billions of scale like Google, X. Where the scale is so high that even redis cannot absorb it. Explaining bloom filter in depth is an article in itself and how it is used, but to give you some context.</p><p>Bloom filter is a data structure which gives you a probabilistic answer whether the key is present in dB or not.</p><p>When using bloom filters with redis it gives us false positives that a key is present in our dB to which sometimes it is not.</p><p>In actual production, just caching the null values works at millions scale but when we reach the scale higher than that we use a hybrid approach where in the first layer we use bloom filters and then employ null caching as well.</p><h3>2. Cache breakdown</h3><p>In every platform there are certain data that is being requested very often for eg. a celebrities instagram page, it’s having millions of hits every second, in technical term we refer it to as <strong>hot key</strong>, signifying that this key is being requested again and again.</p><p>When we store a hot key in our redis, we do not store it permanently. We store it with the TTL. Let’s say a hot key being expires and in the next 100 ms 10k request comes, each will penetrant the dB and reach our primary db requesting the same key, causing a <strong>thundering herd</strong> on our database.</p><h3>A. Request Coalescing</h3><p>The problem that we have is each of those 10k requests are requesting an entry which is not present in cache, so each of those request will try to fetch from primary db to rebuild the cache, which is redundant.</p><p>Ideally we want only one request to rebuild the cache, while the other request can either just wait or serve the stale data (this approach is often referred as <strong>stale while revalidate</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HytJz6j3_MRhbpr-MARksg.png" /></figure><p>Now for a single node instance if multiple requests for the same key comes in we can store the request in an in memory map and handle it accordingly, but if there mutliple node instances we have to use a shared lock something like distributed lock by redis which uses heddison algorithm</p><h3>2. Logical Expiration</h3><p>When someone said Math is magic, they weren’t that far off. Someone came up with this formula,</p><p>to put it simply if your key ttl is 300 ms start refreshing that key from 270ms to 300ms giving it a good period to refresh. Stripe as we know heavily uses this method of logical expiration, if there ttl is 5 minute they start refreshing the key at 2 or 3 minute.</p><h3>3. Mutex or Semaphore</h3><p>This is actually similar to locking, use mutex and semaphore to limit the number of cache build</p><h3>Cache Avalanche</h3><p>Like you guessed avalanche means storm, so if a lot of keys expire at the same time the redis and primary db is doomed 🎇.</p><h3>1. Jittered TTL</h3><p>The more synchronized our cache is the more devastating the thundering herd will be, so the solution is to spread the TTL so the keys don’t expire at the same time, adding random numbers to the TTL with some math logic can be used to avoid this problem to a certain extent.</p><h3>2. Multi level Caching</h3><p>Cache avalanche is not just a problem it is a situation, what happens when a lot of keys expire at the same time. So to properly address this is to be prepared for this problem. In actual production patterns we do not use just one layer of caching, there are several layers of caching involved</p><p>Browser<br> ↓<br>HTTP Cache (Browser)<br> ↓<br>CDN / Edge Cache<br> ↓<br>Load Balancer<br> ↓<br>API Gateway Cache (optional)<br> ↓<br>Application Cache (in-memory)<br> ↓<br>Distributed Cache (Redis/Memcached)<br> ↓<br>Database Cache<br> ↓<br>Database</p><p>That’s it from my side, I hope you had fun reading this article and gained something new to learn and explore. I have linked a few article which explain these along with python code so feel free to explore 🙂. Happy Learning!!!</p><ol><li><a href="https://shayne007.github.io/2025/06/10/Redis-Cache-Problems-Penetration-Breakdown-and-Avalanche/">https://shayne007.github.io/2025/06/10/Redis-Cache-Problems-Penetration-Breakdown-and-Avalanche/</a></li><li><a href="https://oneuptime.com/blog/post/2026-01-25-python-distributed-locks-redlock/view">https://oneuptime.com/blog/post/2026-01-25-python-distributed-locks-redlock/view</a></li><li><a href="https://arpit.substack.com/p/thundering-herd-problem-and-addressing">https://arpit.substack.com/p/thundering-herd-problem-and-addressing</a></li><li><a href="https://oneuptime.com/blog/post/2026-03-31-redis-how-to-use-bloom-filters-for-cache-penetration-prevention-in/view">https://oneuptime.com/blog/post/2026-03-31-redis-how-to-use-bloom-filters-for-cache-penetration-prevention-in/view</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc8d640b4fb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Payment Reconcilation Systems]]></title>
            <link>https://medium.com/@distroaryan/payment-reconcilation-systems-d0cfd0148838?source=rss-31f9f3175c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0cfd0148838</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Aryan Srivastava]]></dc:creator>
            <pubDate>Thu, 21 May 2026 23:27:59 GMT</pubDate>
            <atom:updated>2026-05-21T23:32:20.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s first understand why reconciliation systems are necessary and why payment backends cannot function without them.</p><p>Let’s say you built an email notification service that uses Resend, which in turn delivers via Gmail or Outlook so there are 3 systems involved in a single process <em>(your system → Resend → Gmail)</em>. For everything to work correctly, all 3 systems must agree on what happened. If they don’t, you have inconsistency.</p><p><strong>Why is this a problem in payments specifically, and not in other systems?</strong></p><p>Let’s say you sent an email and your system marked it as sent, but due to some exception, the email never actually went out ,Resend or the email provider silently failed. In email, that’s annoying. In payments, that’s catastrophic.</p><p>Imagine Google Pay showing ₹1,000 debited but your bank account still shows the original balance. That’s not a UI bug <em>that’s a payment disaster waiting to happen.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsAjJLE64_J_98gy2m7bjg.png" /></figure><p>To work with the analogy, Resend becomes a PSP (Payment Service Provider) like GPay or PhonePe, and the email provider becomes an actual bank like ICICI or SBI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQoF2YxuXJ5o3ASi4-Vkmw.png" /></figure><p>Most payment bugs do not happen when the user taps Pay.</p><p>They happen later.</p><p>The app says the payment succeeded. The PSP has one record. The bank has another. Your internal system has its own event. Now someone has to answer the uncomfortable question:</p><p><em>Did the money actually settle correctly?</em></p><p>That is what reconciliation systems exist for.</p><p>I recently built a payment backend and integrated reconciliation into it. It follows these steps —</p><ul><li>stores internal payments</li><li>ingests PSP and bank files</li><li>normalizes records into one format</li><li>runs matching logic across all three systems</li><li>creates exceptions (errors with more context and info) for anything that does not line up</li></ul><h3>The Real Problem</h3><p>A payment system has at least three views of the same transaction:</p><ul><li>your internal payment record</li><li>the PSP settlement record</li><li>the bank settlement record</li></ul><p>If all three agree, life is easy.</p><p>If one is missing, delayed, duplicated, or inconsistent, someone has to investigate before money goes out of balance.</p><p>That is why reconciliation is not a reporting feature. It is a correctness system.</p><h3>How it actually works</h3><p>You take receipts from your PSP, actual bank records, and your own ledger entries, then match them to confirm they are consistent. If they are not, you investigate further: checking ledger entries, contacting the PSP, or flagging the transaction for manual review.</p><p>The shape is practical.</p><p>First, internal transactions are written into our internal database</p><p>Then external files from PSPs and banks are ingested and stored on disk, parsed, and converted into <strong>normalized records</strong></p><p>After that, a reconciliation run compares internal rows, PSP rows, and bank rows line by line for a given provider and date range.</p><p>That comparison produces two outputs:</p><ul><li>reconciliation results</li><li>reconciliation exceptions</li></ul><p>That is the core loop.</p><h3>Why Normalization Matters</h3><p>Every PSP and bank records stores data in there own data format, for example a user is referred to as candidates, merchants, subscribers, customer, visitor etc… in different systems. We need a system or a layer that normalizes this into one shared structure</p><p>Once everything looks the same, matching becomes possible.</p><p>Without normalization, reconciliation logic turns into a mess of one-off parsers and special cases.</p><h3>File Idempotency</h3><p>As discussed in the previous part of the blog, Idempotency is one of the real fundamentas things when building a payments, so our system needs duplicate-file handling.</p><p><em>If you haven’t read part one yet, start here:</em> <a href="https://medium.com/@distroaryan/payment-backend-101-from-a-beginner-perspective-7228c9a08fbb">Payment Backend 101 — From a Beginner’s Perspective</a></p><p>Every uploaded file is saved, hashed with SHA-256, and checked against previous ingests using the checksum.</p><p>If the exact same file arrives again, the system does not ingest it twice. Because essentially we are comparing thousands if not millions of records across different systems, so we cannot just do it every time we want.</p><p>And that matters more because pipelines retry all the time:</p><ul><li>someone uploads the same file again accidentally or intentionally.</li><li>an operator is unsure whether the first import worked</li></ul><p>If you do not make file ingestion idempotent, your reconciliation results become noisy very quickly.</p><h3>What a Reconciliation Produces</h3><p>If it produces 0 mismatches then perfect, but we all know nothing is that perfect ;). If it encounters any inconsistency, it produces the exceptions.</p><p><strong>Here are some common reasons:</strong></p><ul><li><strong>Timing differences</strong>: Sometimes, a transaction might appear in your accounting system before it shows up on the bank statement (or vice versa).</li><li><strong>Data entry errors:</strong> Typos or mistakes during data entry can lead to discrepancies that needs to be resolved.</li><li><strong>Missing transactions:</strong> A transaction might be missing from one set of records but exist in the other.</li><li><strong>Bank fees or interest:</strong> These need to be accounted for and may not be reflected in your internal records initially.</li></ul><p>After identifying the reason for the mismatch, you can take corrective action. For example updating your software, contacting the bank or PSP team for investigations etc…</p><p><em>Real systems are not failing in dramatic ways all the time. They are drifting in small, operationally expensive ways.</em></p><h3>Exceptions Are a First-Class Output</h3><p>One thing people miss when they first learn reconciliation is this:</p><p>The goal is not to eliminate exceptions, the goal is to surface them clearly, classify them correctly, and make them resolvable because you cannot avoid it, they are guranteed to happen.</p><p>We are dealing with 3 independent systems here (our own backend -&gt; PSP -&gt; Bank), inconsistencies are bound to happen at some point, the real thing is how we handle them.</p><p>It is important that exceptions are separately with exception type, status, note, and resolved timestamp.</p><p>That is important because a reconciliation engine is only half the system.</p><p>The other half or how we resolve the exceptions generated from reconcilations is the operational workflow around it.</p><p><em>Simply detecting a mismatch without a resolving it is just a log line with better branding.</em></p><h3>A Clean Mental Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47wt9ZOzcfmMuHVRHm8AtA.png" /></figure><p>If you want the entire system in a few lines, it looks like this:</p><ul><li>Internal payments enter the system.</li><li>PSP and bank files arrive through upload.</li><li>Files are deduplicated by checksum.</li><li>Rows are normalized into one schema.</li><li>A run compares internal, PSP, and bank records.</li><li>Matches are stored.</li><li>Mismatches become exceptions for follow-up.</li></ul><p>That is reconciliation. Not easy to build, not easy to maintain. But absolutely necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G__lG_PIpe41hWAgJ4PyHw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0cfd0148838" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Payment Backend 101 — From a Beginner Perspective]]></title>
            <link>https://medium.com/@distroaryan/payment-backend-101-from-a-beginner-perspective-7228c9a08fbb?source=rss-31f9f3175c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/7228c9a08fbb</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Aryan Srivastava]]></dc:creator>
            <pubDate>Tue, 19 May 2026 20:08:25 GMT</pubDate>
            <atom:updated>2026-05-19T20:08:25.787Z</atom:updated>
            <content:encoded><![CDATA[<p>In most software systems, a bug costs you uptime. A wrong calculation might show a weird number on a dashboard, trigger an alert, and it will get fixed in the next deploy.</p><p>In fintech, a bug costs real money.</p><p>Every decision in a payment system carries weight. Rounding errors, race conditions, missing retries — these aren’t edge cases to handle someday. They are the system. Get them wrong and you lose user’s money.</p><blockquote>In fintech system failures are expected from day one and systems are designed to handle all kinds of failures so no money is lost. Reliability is everything here.</blockquote><h4><strong>Chapter 1: Never Use Floating-Point Numbers for Money</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Dnnbwo85anCVNxVIsvKlw.png" /></figure><p>If you have worked with numbers in code, using a float or double feels completely natural. It&#39;s what most languages default to, it&#39;s fast, and it works fine in most contexts.</p><p>But in fintech systems, this habit can silently introduce errors that compound into real money loss. Let’s understand how -</p><p>Floating-point numbers store values in binary. The number 0.1 cannot be stored precisely in binary — it becomes an infinitely repeating fraction, similar to how 1/3 can’t be written precisely in decimal.</p><p>A simple example:</p><p>0.1 + 0.2</p><p>You’d expect 0.3. What you actually get:</p><p>0.30000000000000004</p><p>In isolation, this looks harmless. A tiny, almost invisible error.</p><p>But real payment systems process millions or billions of transactions every day. Even a drift of ₹0.01, repeated a million times becomes ₹10,000 in unexplained discrepancy.</p><p><strong>The fix</strong></p><p>Never use unguarded or undefined floating-point types for money.</p><p>There are two common approaches:</p><p><strong>1. Store amounts as integers in the smallest unit</strong></p><p><strong>2. Use fixed-precision decimal types</strong></p><p>For most systems, integer storage in the smallest unit is simpler, because if you use fixed -precision, then that fixed precision value becomes a variable which needs to be managed across different systems.</p><p>To wrap up, if you simulate adding ₹0.01 one million times:</p><ul><li>Using float → you will see drift</li><li>Using integer → exact result</li><li>Using precise decimal → exact result</li></ul><h4>Chapter 2: The Append-Only Ledger</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-g2C5Vr7zMXuosHw7PGOuA.png" /></figure><p>Consider a payment of ₹500 that was processed ten days ago and later updated today. If the original state is overwritten, the historical record is effectively lost. During debugging, developers are forced to reconstruct events based on assumptions rather than reliable data.</p><p>In fintech systems, this is not merely a minor bug — it reflects a fundamental flaw in system design. Financial systems must preserve accurate historical state at all times, because in domains involving real money, data integrity and traceability are non-negotiable.</p><p><strong>Currency is a real sensitive data and we should track every change of it, a single number in row is definitely not the most secure way of doing it.</strong></p><p>So instead of updating existing records, every financial event is written as a new entry. Each one becomes a permanent record in the ledger.</p><p>Most fintech systems follow the principle of <strong>double-entry accounting</strong>. Every transaction creates two ledger entries:</p><ul><li>A <strong>debit</strong> from one account</li><li>A corresponding <strong>credit</strong> to another account</li></ul><p>Money never simply “appears” or “disappears” inside the system — it always moves from one ledger account to another. This guarantees that the books remain balanced and makes inconsistencies significantly easier to detect.</p><p>For example:</p><ul><li>User Wallet → <strong>Debit ₹500</strong></li><li>Merchant Settlement Account → <strong>Credit ₹500</strong></li></ul><p>Every movement has an equal and opposite entry.</p><p><strong>What this gives you</strong></p><p><strong>Audit trail.</strong> Every event is preserved exactly as it is occurred. Teams can trace every rupee through the system at any point in time and the current state of any account is derived from the complete history of events, not from a single number.</p><p><strong>Reconciliation.</strong> It is the process of comparing the company’s internal transaction history with actual bank records (for example ICICI or SBI bank statements) to ensure that every payment, refund, and balance is consistent and accounted for.</p><p>Without a complete and immutable ledger history, reliable reconciliation and event sourcing becomes impossible, making it extremely difficult to detect discrepancies, investigate failures, or maintain financial accuracy.</p><h4>Chapter 3: Idempotency: Handling Retries Safely</h4><p><em>I ran out of memes ideas ;)</em></p><p>Network requests fail. A request times out, the client retries, and now the same payment has been sent twice. Without any protection, both go through and the client will be charged twice if not handled correctly.</p><p>Idempotency is how you prevent this. Idempotency means the same action can be performed multiple times and the results remains the same. For example fetching something from the db is idempotent, fetch it once or 10 times the result remains the same but adding a new entry in the db is not.</p><p><strong>How it works</strong></p><p>The client generates a unique key before sending the request and includes it in the header, typically as Idempotency-Key. This key travels with the request every time it is sent, including retries.</p><p>On the server side, the payment gateway checks this key against a cache typically Redis before doing anything. If the key has been seen before, it returns the original result immediately without processing the request again. If it hasn’t, it processes the payment and stores the key along with the result.</p><p>This means the client can retry as aggressively as it needs to. The gateway ensures the operation happens exactly once.</p><p><strong>Inside the database</strong></p><p>Idempotency does not stop at the payment gateway. When ledger entries are created, the idempotency key is persisted alongside the transaction itself. This becomes critical because the creation of new operations may still encounter concurrency issues, especially in scenarios where traditional row-level locking cannot fully prevent duplicate writes.</p><p>This stored idempotency key acts as a second layer of protection. Even if a duplicate request bypasses the cache or retry protection at the gateway layer, the database can still detect that the operation has already been processed and reject the duplicate entry.</p><p>Two layers, one guarantee: <em>regardless of how many times the same request arrives, the transaction is recorded exactly once.</em></p><h3>Chapter 4: Where Strings Come In</h3><p>You might notice that many payment APIs represent amounts as strings:</p><p>{ &quot;amount&quot;: &quot;100.50&quot; }</p><p>This often causes confusion. Why a string? Why not just send a number?</p><p>The answer is about what happens at system boundaries. When data is serialized into JSON and sent over a network, numbers can lose precision depending on the language or runtime parsing them. JavaScript, for example, cannot safely represent all large integers or precise decimals natively — a float slips in at the parsing stage before your code even sees the value.</p><p>A string carries no such risk. &quot;100.50&quot; arrives exactly as &quot;100.50&quot;, in every language, on every platform, every time.</p><p>This is purely a transport concern. Strings are used at the boundary in the request and response — not internally. The moment the value enters the backend, it is converted into an integer in the smallest unit, paise or cents, and that is what every subsequent operation works with.</p><h3>A Simple Mental Model</h3><p>A typical flow in a payment system looks like this:</p><ul><li>API receives amount as a string</li><li>Backend converts it into an integer (smallest unit)</li><li>Two ledger entries are created (debit and credit)</li><li>Entries are appended to the ledger</li><li>Idempotency is checked to avoid duplicates</li><li>Balance is computed from the ledger</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G__lG_PIpe41hWAgJ4PyHw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7228c9a08fbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a DHT in Go from Scratch: A Deep Dive into Kademlia Paper]]></title>
            <link>https://medium.com/@distroaryan/building-a-distributed-hash-table-dht-in-go-from-scratch-a-deep-dive-into-kademlia-6895c406dc9b?source=rss-31f9f3175c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/6895c406dc9b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Aryan Srivastava]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 10:42:49 GMT</pubDate>
            <atom:updated>2026-03-04T14:22:52.197Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey everyone! 👋, Have you ever wondered how decentralized systems like BitTorrent, IPFS, or blockchain networks manage to find and store data without a centralized server? The secret sauce is almost always a <strong>Distributed Hash Table (DHT)</strong>.</p><p>Today, we’re not just going to talk about theory. We are going to <strong>build a functional, minimal DHT from scratch in Go</strong>. By the end of this read, you’ll have a working peer-to-peer network routing data intelligently using the famous <strong>Kademlia architecture</strong>.</p><p>Grab a coffee ☕, fire up your code editor, and let’s dive deep into distributed systems engineering!</p><blockquote><strong><em>Prerequisite:</em></strong><em> To code along, you should have a basic understanding of RPCs (Remote Procedure Calls). We will use </em><strong><em>gRPC over TCP</em></strong><em> for ease of debugging, but you are free to use any transmission protocol of your choice (like HTTP, WebSockets, or plain UDP as referenced in the original paper). If you want to brush up on gRPC, </em><a href="https://dev.to/pixperk/learn-grpc-completely-from-unary-to-bi-directional-rpcs-2dnl"><em>read this excellent guide</em></a><em>.</em></blockquote><blockquote><em>💻 </em><strong><em>Source Code:</em></strong><em> You can find the complete, runnable code for this project on GitHub: </em><a href="https://github.com/Aryan123-rgb/go-dht"><strong><em>Aryan123-rgb/go-dht</em></strong></a><em>.</em></blockquote><h3>Table of Contents</h3><ul><li><a href="https://markdown-to-medium.surge.sh/#1-what-exactly-is-a-dht-and-how-is-it-different">1. What Exactly is a DHT? (And How is it Different?)</a></li><li><a href="https://markdown-to-medium.surge.sh/#2-the-core-concepts-of-kademlia">2. The Core Concepts of Kademlia</a></li><li><a href="https://markdown-to-medium.surge.sh/#3-project-setup">3. Project Setup</a></li><li><a href="https://markdown-to-medium.surge.sh/#4-step-1-the-protocol-grpc-definitions">4. Step 1: The Protocol (gRPC Definitions)</a></li><li><a href="https://markdown-to-medium.surge.sh/#5-step-2-the-math-engine-routing_tablego">5. Step 2: The Math Engine (routing_table.go)</a></li><li><a href="https://markdown-to-medium.surge.sh/#6-step-3-the-passive-server-servergo">6. Step 3: The Passive Server (server.go)</a></li><li><a href="https://markdown-to-medium.surge.sh/#7-step-4-the-network-client-clientgo">7. Step 4: The Network Client (client.go)</a></li><li><a href="https://markdown-to-medium.surge.sh/#8-step-5-wiring-it-all-together-maingo">8. Step 5: Wiring it all together (main.go)</a></li><li><a href="https://markdown-to-medium.surge.sh/#9-demo-time-">9. Demo Time! 🎉</a></li><li><a href="https://markdown-to-medium.surge.sh/#10-concepts-not-implemented-production-considerations">10. Concepts Not Implemented (Production Considerations)</a></li><li><a href="https://markdown-to-medium.surge.sh/#conclusion">Conclusion</a></li></ul><h3>1. What Exactly is a DHT? (And How is it Different?)</h3><p>Before writing anything, let’s clear up what a DHT actually is and what makes it special.</p><p>If you’ve worked with databases like Redis, you know them as “Distributed Key-Value Stores.” You send a key (&quot;user:123&quot;) and get a value (&quot;Alice&quot;). If you haven&#39;t heard of them, that&#39;s fine just picture that the data is not stored in a single server but is split up and stored across multiple servers. In traditional distributed stores, however, there&#39;s usually a central coordinator or a highly consistent cluster that handles the routing, storing, and fetching of key-values.</p><p>A <strong>Distributed Hash Table</strong> does the exact same thing (stores and retrieves data), but operates in a <strong>peer-to-peer (P2P)</strong> environment where:</p><ul><li>There is <strong>no master node</strong> or central coordinator.</li><li>Nodes can join and leave the network freely at any time (we call this environment “high churn”).</li><li>No single node has the full map of the network. A node only knows about a tiny fraction of its peers.</li></ul><h3>2. The Core Concepts of Kademlia</h3><p>To code Kademlia, we need to understand its three foundational pillars:</p><h3>The Unified 160-bit ID Space</h3><p>In Kademlia, <em>everything</em> is located using a 160-bit identifier (we will use SHA-1 to generate it). This applies to both nodes and data keys! We store nodes using their SHA-1 hash, but we represent the secret keys as simple strings before hashing them under the hood. Why? Because it makes the CLI much easier to use. 😅</p><p>Because both nodes and data live in the <em>exact same mathematical space</em>, it means a node and a piece of data can be mathematically “close” to one another.</p><h3>The XOR Distance Metric</h3><p><em>Pay a little attention here. The original paper describes this using a binary tree, but in actual code implementations, you won’t find a literal binary tree data structure!</em> 😅</p><p>So how do we know which node should store which piece of data? Kademlia says:</p><blockquote><strong><em>Data should be stored on the nodes whose IDs are mathematically closest to the data’s ID</em></strong></blockquote><p>But how do you measure “distance” between two 160-bit hashes? They aren’t physical locations like latitude and longitude.</p><p>Kademlia uses the bitwise <strong>XOR operator </strong>to define distance. The distance between Node A and Key B is: <strong>Distance = Node_ID ^ Key_ID</strong></p><p>XOR is a magical operator for this specific use case because:</p><ol><li><strong>Distance to yourself is zero</strong>: A ^ A = 0</li><li><strong>It’s symmetric</strong>: <strong>A ^ B = B ^ A</strong> (distance from A to B is the same as B to A).</li><li><strong>It obeys the triangle inequality</strong>: Logically, distances act like straight lines.</li></ol><h3>Routing Tables &amp; Buckets</h3><p>Because the ID space is 160 bits long, Kademlia maintains a routing table organized into exactly 160 “buckets.”</p><ul><li><strong>Bucket 0</strong> stores nodes whose XOR distance is 1 bit away.</li><li><strong>Bucket 159</strong> stores nodes whose XOR distance is on the total opposite side of the ID space.</li></ul><p>Because of this structure, a node knows <em>a lot</em> about its immediate mathematical neighbors, and only a <em>little</em> about nodes far away.</p><p>If you are reading the original Kademlia paper, do not get scared by the complex bucket tree diagrams! In code, it simply means: Nodes whose IDs differ at the 0th bit (from the left/Most Significant Bit) get stored in routing_table[0]. Nodes whose bits differ at the 1st bit are stored at routing_table[1], and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bm1E7hKj93jsrkbMCV9EPg.png" /></figure><h3>Communication Across Nodes</h3><p>Kademlia dictates that nodes only need four Remote Procedure Calls (RPCs) to operate the entire network:</p><ol><li><strong>Ping</strong>: Used to check whether a peer is alive or not.</li><li><strong>Store (key, value)</strong>: Hashes the key and stores the data to the peers mathematically closest to that hash according to the XOR metric.</li><li><strong>Find_Node (node_id)</strong>: Asks a peer to find all known nodes closest to the target Node ID.</li><li><strong>Find_Value (key)</strong>: Asks a peer for the data corresponding to a key. If they don’t have it, they act exactly like Find_Node and return the closest known nodes.</li></ol><p>During these gRPC calls, the receiver <strong>always</strong> saves the sender’s ID. This is how peer-to-peer passive discovery works!</p><p>In simple terms: when Node A calls Node B, Node B remembers Node A. When a new Node C comes along and calls Node A, Node A learns about Node C. This organic gossip is how inter-node network mapping functions.</p><h3>The Iterative Key Lookup (Finding Data Organically)</h3><p>Because we don’t use complete network “flooding”, we perform an <strong>Iterative Lookup</strong> to find data. Rather than a central coordinator sending you the data, you traverse the network by asking peers who they know.</p><p>Let’s look at a practical example. Imagine this network state:</p><ul><li><strong>Node A’s Routing Table (Buckets):</strong> knows about Node B and Node C.</li><li><strong>Node B’s Routing Table (Buckets):</strong> knows about Node A.</li><li><strong>Node C’s Routing Table (Buckets):</strong> knows about Node A.</li><li><strong>Data Storage:</strong> A key-value pair {key1, val1} is stored locally on <strong>Node C</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*qPLAHClGoEaEPS1Eqmz-vQ.png" /></figure><p><strong>The Query Flow:</strong> If a client connects to <strong>Node B</strong> to query key1, here is how Kademlia routes the request without any central directory:</p><ol><li><strong>Query Node B:</strong> The client asks Node B for key1.</li><li><strong>Node B Checks Local Storage:</strong> Node B does not have it. It looks in its routing table and returns the closest peer it knows: <strong>Node A</strong>.</li><li><strong>Query Node A:</strong> The client uses this new information and asks Node A for key1.</li><li><strong>Node A Checks Local Storage:</strong> Node A does not have it. It looks in its routing table and returns the closest peers it knows: <strong>Node B</strong> and <strong>Node C</strong>.</li><li><strong>Query Node C:</strong> Since the client already asked Node B, it now routes the query to <strong>Node C</strong> and asks for key1.</li><li><strong>Node C Checks Local Storage:</strong> Node C looks in its database, finds {key1, val1}, and returns the value to the client!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1i1d11cuZhoRD7JXzYi3A.png" /></figure><p>Through this process, the client “homes in” on the target data by jumping closer and closer mathematically across the buckets until it hits the final destination node storing the data.</p><h3>3. Project Setup</h3><p>Let’s start coding.</p><p>Our ideal project layout looks like this:</p><pre>/go-dht<br>├── proto/             # gRPC definitions<br>│   └── dht.proto<br>├── server.go          # The passive listener &amp; storage<br>├── client.go          # The active worker (Network routing)<br>├── routing_table.go   # XOR distances and Bucket logic<br>└── main.go            # Entrypoint and CLI UI</pre><h3>4. Step 1: The Protocol (gRPC Definitions)</h3><p>Kademlia dictates that nodes only need four Remote Procedure Calls (RPCs) to operate the entire network. Let’s define them in proto/dht.proto.</p><p>Instead of one giant block, let’s look at the service definition first:</p><pre>syntax = &quot;proto3&quot;;<br>package dht;<br>option go_package = &quot;./proto&quot;;</pre><pre>service DHT {<br>    rpc Ping(PingRequest) returns (PingResponse);<br>    rpc Store(StoreRequest) returns (StoreResponse);<br>    rpc FindNode(FindNodeRequest) returns (FindNodeResponse);<br>    rpc FindValue(FindValueRequest) returns (FindValueResponse);<br>}</pre><ul><li>FindNode asks a peer: <em>&quot;Look in your routing table. Who do you know that is mathematically closest to this target ID?&quot;</em></li><li>FindValue asks: <em>&quot;Do you have the data for this key? If not, act exactly like FindNode and give me someone closer.&quot;</em></li></ul><p>To support these, every message should include the sender’s information for peer to peer to node discovery: A node will have to two fields</p><ol><li>id — used for identifying the field over the network</li><li>ipAddress — used for connecting via gRPC</li></ol><pre>message Node {<br>    bytes id = 1; // 160 bit SHA-1 Hash<br>    string ip_address = 2; // network address to connect via gRPC<br>}</pre><pre>message FindValueRequest {<br>    Node sender = 1;      // Let the receiver know who we are!<br>    string key = 2;       // The key we are looking for<br>}</pre><pre>message FindValueResponse {<br>    bytes value = 1;         // Populated if data is found<br>    repeated Node nodes = 2; // Populated with closer nodes if data NOT found<br>    bool found = 3; <br>}</pre><p><em>(You can scaffold </em><em>StoreRequest, </em><em>PingRequest, etc., using the same logic—just ensure </em><em>Node sender = 1 is included!)</em></p><p>Compile the proto file using:</p><pre>protoc --go_out=. --go-grpc_out=. proto/dht.proto</pre><h3>5. Step 2: The Math Engine (routing_table.go)</h3><p>We need a way to hash inputs to 160 bits and slot nodes into 160 distinct buckets.</p><p>First, standardizing the ID generation:</p><pre>const IDLength = 20             // 160 bits = 20 bytes<br>const MaxBuckets = IDLength * 8 // 160 buckets<br><br>type NodeId [IDLength]byte<br><br>func GenerateID(data string) NodeId {<br>    return sha1.Sum([]byte(data)) // Converts any string into a 160-bit hash!<br>}</pre><h3>The Bucket Math</h3><p>To place discovered nodes into our 160 buckets, we calculate the highest differing bit (the most significant bit that differs between our ID and the newly discovered node’s ID).</p><pre>func BucketIndex(id1, id2 NodeId) int {<br>    for i := range IDLength {<br>        xor := id1[i] ^ id2[i]<br>        if xor != 0 {<br>            leadingZeros := bits.LeadingZeros8(xor)<br>            return (IDLength-1-i)*8 + (8 - 1 - leadingZeros)<br>        }<br>    }<br>    return 0 // IDs are exactly identical<br>}</pre><p>If the IDs differ completely at the very first bit, it goes into Bucket 159. This organically sorts peers: distant nodes fall into one massive high-level bucket, and close nodes are tightly coupled into lower buckets.</p><p>If it’s difficult to understand take two examples id1 = 0000 and id2 = 0001, now count from the left the first bit difference is at index = 3, and in this case the IDLength = 4, do the dry run yourself and you’ll see how the algorithm is working (or just ask chatgpt to dry run it for you ;)</p><h3>Saving the Nodes</h3><p>Our RoutingTable is just an array of subsets (buckets):</p><pre>type RoutingTable struct {<br>    mu      sync.Mutex<br>    SelfId  NodeId<br>    Buckets [MaxBuckets][]*proto.Node<br>}<br><br>func (rt *RoutingTable) AddNode(node *proto.Node) {<br>    rt.mu.Lock()<br>    defer rt.mu.Unlock()<br><br>    // Find the mathematical distance bucket<br>    var id NodeId<br>    copy(id[:], node.Id)<br>    bucketIndex := BucketIndex(rt.SelfId, id)<br><br>    // Append them if they aren&#39;t completely identical to us or already present!<br>    // (Omitted duplicate check for brevity)<br>    rt.Buckets[bucketIndex] = append(rt.Buckets[bucketIndex], node)<br>}</pre><h3>6. Step 3: The Passive Server (server.go)</h3><p>Every peer runs a gRPC server to answer queries.</p><p>The most elegant feature here is <strong>Passive Discovery</strong>. Remember how every request in our protobuf file included the sender’s info? Because of this, nodes organically build a map of the network just by servicing normal traffic. There is no central registry!</p><pre>type DHTServer struct {<br>    proto.UnimplementedDHTServer<br>    Self         *proto.Node<br>    RoutingTable *RoutingTable<br>    Storage      map[string][]byte  // Our &quot;Database&quot;<br>    storageMu    sync.Mutex<br>}</pre><p>Let’s look at FindValue. The absolute first thing the RPC does is record the sender, then check it’s own storage to find the key, if the key exists then we return the value, otherwise we return the closest nodes to continue the discovery, in production you would return only alpha closest nodes but for simplicity I am returning all the nodes here.</p><pre>func (s *DHTServer) FindValue(ctx context.Context, req *proto.FindValueRequest) (*proto.FindValueResponse, error) {<br>    // 1. Passive Discovery! We learn about the sender for free.<br>    if req.Sender != nil {<br>         s.RoutingTable.AddNode(req.Sender) <br>    }<br><br>    // 2. Check our Database<br>    s.storageMu.Lock()<br>    val, isExists := s.Storage[req.Key]<br>    s.storageMu.Unlock()<br><br>    if isExists {<br>        // We have the data!<br>        return &amp;proto.FindValueResponse{Value: val, Found: true}, nil<br>    }<br><br>    // 3. We don&#39;t have it. Return our closest known peers to the target!<br>    nodes := s.RoutingTable.GetClosestNode()<br>    return &amp;proto.FindValueResponse{Nodes: nodes, Found: false}, nil<br>}</pre><p>In a similar way, try to write the PING function yourself, first check the sender and add it to the routing table and just return the ping response.</p><p>The STORE function is also similar first check the sender and add it to the routing table and store the key value in the storage, don’t forget to use lock.</p><p>And FindNode is also similar just remove the checking key part and simply return the closest node, and you have successfully created your server</p><h3>7. Step 4: The Network Client (client.go)</h3><p>This is where the complex action happens! While the server passively listens, the Client actively hunts the network.</p><h3>Bootstrapping</h3><p>How does a new node discover the whole network? You provide it just <strong>one</strong> known address (a bootstrap peer). The node connects to it and performs a FindNode request <em>looking for its own ID</em>.</p><p>By asking the network &quot;Who is closest to me?&quot;, the peers return the nodes mathematically surrounding our new node, organically populating our empty routing table!</p><p>In simple terms just call FindNode to our bootstrap node, this will allow the bootstrap node to store info about our node and it will return it’s closest node which we will add in our routing table.</p><pre>func (c *Client) Bootstrap(bootstrapAddr string) {<br>    conn, _ := grpc.NewClient(bootstrapAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))<br>    grpcClient := proto.NewDHTClient(conn)<br><br>    // Query for our OWN ID!<br>    req := &amp;proto.FindNodeRequest{Sender: c.Self, TargetId: c.Self.Id}<br>    resp, _ := grpcClient.FindNode(context.Background(), req)<br><br>    // Add discovered peers to our table<br>    for _, node := range resp.Nodes {<br>        c.RoutingTable.AddNode(node)<br>    }<br>}</pre><h3>Implementing Iterative Lookup</h3><p>Now that we understand the core concept of iterative lookups from earlier, let&#39;s map the conceptual flow into actual Go code.</p><p>This is somewhat like a BFS traversal if you’ve heard of, more like a mutli-source BFS.</p><p><strong>Phase 1: Setup</strong> We first check if the value is locally present and if yes then we return it simply, but if not</p><p>Then we create a map queried or you can call it visited, this is used to make sure we are not querying the same node multiple times. We then find the closestNode to our current node (you can pick any random node here if you want, but it’s more technically correct to find the node closest to our own node)</p><pre>func (c *Client) FindValueNetwork(key string) {<br>    // Check locally first...<br>    targetId := GenerateID(key)<br>    queried := make(map[string]bool)<br>    shortList := c.RoutingTable.GetClosestNode()<br>    // ...</pre><p><strong>Phase 2: The Loop</strong> This is the heart of the mathematical routing computation. Inside an infinite loop, we sort our shortList. The custom sorting function calculates the XOR distance from each node&#39;s ID to the targetId. This forces the nodes mathematically &quot;closest&quot; to the data to the 0th index! We then iterate through the sorted list, skipping the ones we&#39;ve already queried, and pick the optimal nextNode.</p><p>Again if you want to keep it simple just iterate on the normal list, all this is done so that the convergence quickly and we can find the node in the shortest time.</p><pre>for {<br>        sort.Slice(shortList, func(i, j int) bool {<br>            // Sort based on XOR distance to the TargetId<br>            return isCloser(xorDistance(IdI, targetId), xorDistance(IdJ, targetId))<br>        })<br><br>        var nextNode *proto.Node<br>        for _, n := range shortList {<br>            if !queried[string(n.Id)] {<br>                nextNode = n<br>                break<br>            }<br>        }</pre><p><strong>Phase 3: The Query</strong> Once we select the best unqueried node, we mark it as queried in our map to ensure we don&#39;t ask it again. We call it via gRPC using FindValue. Essentially now we are talking to that node to check if that node has the value of our key</p><p>If it has the data (Found: true), we exit the loop! If it doesn&#39;t, it returns a list of <em>closer nodes</em> from its own routing table. We parse those new nodes, add them to our own shortList (if they aren&#39;t already there), and the loop starts entirely from the beginning—re-sorting the newly expanded list so we inch closer and closer to the target until we zero in!</p><pre>queried[string(nextNode.Id)] = true<br>        resp, _ := grpcClient.FindValue(ctx, &amp;proto.FindValueRequest{Sender: c.Self, Key: key})<br><br>        if resp.Found {<br>            log.Printf(&quot;Success! Value: &#39;%s&#39;&quot;, string(resp.Value))<br>            return<br>        }<br><br>        // Add newly discovered closer nodes to our shortlist!<br>        for _, n := range resp.Nodes {<br>            c.RoutingTable.AddNode(n)<br>            if !containsNode(shortList, n) {<br>                shortList = append(shortList, n)<br>            }<br>        }<br>    } // end for<br>}</pre><p>To summarise it one more time, we find the closest node to our own node first, and then in a bfs logic we query each node to check if they have the key or not (by calling FindValue on each node) and if they don’t have they return a bunch of nodes which we add in our list and start it again. Here’s the full code</p><p>You can checkout the full code in my repo inside server.go, file (if i paste it here it becomes too long)</p><p><em>(Note: Storing data uses the exact same </em><em>for loop routing logic. You iterate to find the closest node mathematically, and once you can&#39;t find anyone closer, you break the loop and send a </em><em>Store RPC instead of querying </em><em>FindValue.)</em></p><h3>8. Step 5: Wiring it all together (main.go)</h3><p>To test our distributed system, we wrap everything in main.go. We initialize our Node Identity, spin up the background gRPC server, bootstrap if necessary, and launch a blocking CLI scanner to issue store/get commands.</p><pre>func main() {<br>    port := flag.String(&quot;port&quot;, &quot;5001&quot;, &quot;Port to listen on&quot;)<br>    bootstrap := flag.String(&quot;bootstrap&quot;, &quot;&quot;, &quot;Address of bootstrap node&quot;)<br>    flag.Parse()<br><br>    address := fmt.Sprintf(&quot;127.0.0.1:%s&quot;, *port)<br>    selfId := GenerateID(address)<br>    selfNode := &amp;proto.Node{Id: selfId[:], IpAddress: address}<br><br>    rt := NewRoutingTable(selfId)<br>    server := NewDHTServer(selfNode, rt)<br>    client := NewClient(rt, server, selfNode)<br><br>    // Background listener<br>    lis, _ := net.Listen(&quot;tcp&quot;, address)<br>    grpcServer := grpc.NewServer()<br>    proto.RegisterDHTServer(grpcServer, server)<br>    go grpcServer.Serve(lis)<br><br>    if *bootstrap != &quot;&quot; {<br>        client.Bootstrap(*bootstrap)<br>    }<br><br>    // CLI Loop (omitted for brevity)<br>    // Listens for: `store key value`, `get key`, etc.<br>}</pre><h3>9. Demo Time! 🎉</h3><p>We’ve built it! Let’s watch logarithmic routing in action over an actual network. Open three separate terminal windows in the project directory.</p><p>(Note that I have added lot’s of log statements and some ascii art to make it look beautifull, if you want to do the same clone my repo)</p><p><strong>Terminal 1 (Node A — Genesis Node):</strong> Starts the network. It knows nobody.</p><pre>go run . --port 5001</pre><p><strong>Terminal 2 (Node B):</strong> Connects to our network by bootstrapping to Node A (port 5001).</p><pre>go run . --port 5002 --bootstrap 127.0.0.1:5001</pre><p><strong>Terminal 3 (Node C):</strong> Also bootstraps via Node A (port 5001). Because of Kademlia’s bootstrapping and passive discovery, Node A now knows about B and C, and B and C both know about A!</p><pre>go run . --port 5003 --bootstrap 127.0.0.1:5001</pre><p>Now, in <strong>Terminal 3 (Node C)</strong>, instruct it to store a key-value pair. We will simulate storing {key1, val1} locally on Node C:</p><pre>[Node C] ➜ store key1 val1</pre><p>The client will hash key1, find the node ID mathematically closest to it across the three terminal networks, and execute the storage operation exactly there! Check the logs on the three terminals to see who actually stored it.</p><p>Then in <strong>Terminal 2 (Node B)</strong>, try to fetch it, mirroring our earlier iterative lookup example:</p><pre>[Node B] ➜ get key1</pre><p>Watch the terminal output closely. Node B will realize it doesn’t have the data locally. It will ask the network, querying Node A first. Once Node A points it closer to the target, it will process its shortlists, jump to the correct peer mathematically, and retrieve {key1, val1} securely! ✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNPFZks_LII3ybdzwpLJvA.png" /></figure><h3>10. Concepts Not Implemented (Production Considerations)</h3><p>If you take this code and deploy it to a BitTorrent swarm right now, it will work beautifully… until nodes start violently crashing.</p><p>To keep this tutorial clean for education, we omitted a few heavy production features:</p><ol><li><strong>k-buckets with LRU Eviction</strong>: Our RoutingTable holds unlimited nodes. Real Kademlia constrains buckets strictly to a max of <strong>k </strong>nodes (often <strong>k=20</strong>) using Least-Recently Used (LRU) rules to ensure fast <strong>O(log n)</strong> lookup complexity without bloating memory.</li><li><strong>UDP Protocol instead of TCP</strong>: We used gRPC, which operates over TCP. Production DHTs (like Mainline DHT) almost exclusively use lightweight UDP packets. Connecting to hundreds of peers involves massive connection handshakes and socket limits under TCP. UDP is fire-and-forget, making routing lookups blazing fast.</li><li><strong>Data Replication (k value)</strong>: Currently, we Store data to the <em>single</em> closest node. Real implementations replicate the Store command to the 20 nodes mathematically closest to the target hash. If someone unplugs their computer, the data survives.</li><li><strong>TTL and Periodic Republishing</strong>: Nodes churn. The original publisher of the keyword must periodically run .Store() every hour to keep the data alive in the network before nodes flush it from their caches.</li><li><strong>Alpha Concurrency (alpha=3)</strong>: During our Iterative Lookup, we query the closest nodes sequentially. Production P2P clients query up to <strong>alpha </strong>(usually 3) nodes concurrently using multi-threading to vastly speed up discovery speeds.</li></ol><h3>Conclusion</h3><p>Congratulations! Building a DHT from scratch teaches you some of the most fascinating engineering patterns in existence. You’ve just shifted logic from tightly-coupled master/slave database relationships into chaotic, decentralized mathematical routing.</p><p>If you found this helpful, let me know in the comments! You can grab all the source code for this project and start tweaking the math yourself.</p><p>Happy coding, and go build the decentralized web! 🌐</p><p><strong>Personal Note:</strong> Let’s connect! I share more deep dives on building distributed systems and backend engineering on X. Follow me: <a href="https://x.com/distroaryan">@distroaryan</a></p><p><em>(Drop your thoughts or questions below — have you ever built or worked with a P2P system before?)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6895c406dc9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>