<?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 Sohamsarkar on Medium]]></title>
        <description><![CDATA[Stories by Sohamsarkar on Medium]]></description>
        <link>https://medium.com/@sohamsarkar59?source=rss-15b0ae38e60d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WvukT87dhAl_GcwR</url>
            <title>Stories by Sohamsarkar on Medium</title>
            <link>https://medium.com/@sohamsarkar59?source=rss-15b0ae38e60d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:14:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sohamsarkar59/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[Agent workflows: LLMs propose, code enforces]]></title>
            <link>https://medium.com/@sohamsarkar59/agent-workflows-llms-propose-code-enforces-73314a72586c?source=rss-15b0ae38e60d------2</link>
            <guid isPermaLink="false">https://medium.com/p/73314a72586c</guid>
            <dc:creator><![CDATA[Sohamsarkar]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 05:54:20 GMT</pubDate>
            <atom:updated>2026-11-21T05:54:20.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ei73-cnnpG8B3k4aQeSRg.png" /></figure><p>Munshi is a team project.</p><p>Saurabh, Aditya, and I are building an AI support teammate for a Paytm Devsemble track: understand a case, plan the work, take the actions Paytm actually owns, and escalate when a human should decide.</p><p>This post is about one line we keep coming back to.</p><p>LLMs propose. Code enforces.</p><h3>The Tempting Agent</h3><p>The first version of this idea that lives in every engineer’s head is simple.</p><p>Let the model talk to tools.</p><p>Let it call refunds, tickets, lookups, whatever the prompt invents.</p><p>Cute.</p><p>Then you remember what a freeform plan looks like when money is nearby.</p><p>Sometimes the model invents a tool that does not exist.</p><p>Sometimes it binds an amount from the customer’s message instead of a system lookup.</p><p>Sometimes it skips the approval step because the prose sounded confident.</p><p>Sometimes a prompt injection asks it to “just reverse the UPI.”</p><p>And somehow everyone expects the bot to stay honest.</p><p>No silent money moves.</p><p>No tools that are not on the list.</p><p>No “the model said so.”</p><p>Just a plan that code will allow.</p><h3>What The Model Is Allowed To Do</h3><p>In Munshi, models classify, plan, reason, and draft.</p><p>They never execute anything.</p><p>That is not a slogan on a slide. It is principle one in the architecture notes, and the runtime follows it: the planner proposes a graph of steps, and deterministic code validates before anything runs.</p><p>Every tool has to exist.</p><p>Inputs have to type-check.</p><p>Risk has to fit what this case is allowed to do.</p><p>A write step without a gate does not pass.</p><p>Amounts and identifiers on a write have to come from system data, not from an unverified guess in the chat.</p><p>If validation fails, the plan does not become side effects.</p><h3>Desk Is Part Of Enforcement</h3><p>Early autonomy levels are blunt on purpose.</p><p>A new or demoted workflow can read.</p><p>Writes and the customer reply wait for a human at the desk.</p><p>In the worker, a policy hold parks the write intent for desk approval instead of calling the tool. The model can still draft what it wanted. The code decides whether that intent ever leaves the building.</p><p>That is the boring version of safety.</p><p>Boring is the point.</p><h3>What This Is Not</h3><p>Munshi is still design and early build.</p><p>The README is honest about that. Demo numbers in the docs are targets to validate, not trophies I can wave.</p><p>I am not claiming we invented “don’t let the LLM spend money.”</p><p>Existing agent stacks are full of that lesson.</p><p>I am claiming this codebase treats the model as a proposer, and treats validation, policy, and execution as code’s job, on a team project where that split has to survive more than one person’s taste.</p><h3>Next</h3><p>Proposing and enforcing is one refusal.</p><p>It does not answer what happens when a tool call times out and nobody knows if the bank saw it.</p><p>Next: unknown is not failure. Leases, fencing, idempotency, and the reconciler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73314a72586c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part-1 LLM routing: cascade failed its gates, so I left it off]]></title>
            <link>https://medium.com/@sohamsarkar59/part-1-llm-routing-cascade-failed-its-gates-so-i-left-it-off-8d10a7bc2bad?source=rss-15b0ae38e60d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d10a7bc2bad</guid>
            <dc:creator><![CDATA[Sohamsarkar]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 06:07:36 GMT</pubDate>
            <atom:updated>2026-11-20T06:07:36.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YP3wg138TjsN7xRientRxw.png" /></figure><p>I built a router that looks at a coding prompt and picks a model.</p><p>Not because the world needed another router.</p><p>Because I was tired of paying Claude prices for “rename this variable.”</p><h3>The Tempting Safety Net</h3><p>The plain router ranks candidates and picks a winner.</p><p>Cute.</p><p>Then the anxiety shows up.</p><p>What if the top pick is confident and wrong?</p><p>What if the cheap model looks good on paper and melts on the real task?</p><p>So I built a second idea on top: a Claude-default cascade.</p><p>Stay on Claude by default.</p><p>Only switch away when the challenger clears a confidence gate.</p><p>Same instinct as a seatbelt.</p><h3>How The Cascade Decides</h3><p>One version watches the score gap between first and second place.</p><p>If the gap is tiny, stay on Claude.</p><p>If the gap is huge, take the challenger.</p><p>Another version trains a pairwise “can this challenger beat Claude?” score and only switches when that probability clears a threshold.</p><p>Either way, the point is the same.</p><p>Claude is the floor.</p><p>The router has to earn the right to leave it.</p><h3>The Gates</h3><p>I did not want vibes. I wanted gates.</p><p>Before a cascade config can turn itself on, the calibration has to clear a checklist.</p><p>Enough switches to mean anything. Not one lucky flip.</p><p>Switch precision at least 0.55. When it leaves Claude, it should usually be right.</p><p>Positive lift. Beating Claude-only, not cosplaying confidence.</p><p>Positive mean gain on the switches it does make.</p><p>If those fail, the code takes the explicit no-switch path.</p><p>It does not force an unsafe cascade.</p><p>enabled stays false.</p><h3>What Calibration Actually Said</h3><p>I ran the gap cascade.</p><p>Best threshold it found still made zero switches.</p><p>Zero switches.</p><p>Zero precision.</p><p>Zero lift.</p><p>The pairwise artifact under the same experiment tree came back disabled the same way.</p><p>So the safety net never got permission to leave Claude.</p><p>Which means it was not a safety net.</p><p>It was a Claude costume with extra math.</p><h3>So I Left It Off</h3><p>The serving checklist still has that box unchecked: enable high-precision Claude-default cascade in serving.</p><p>When cascade config is missing or disabled, the router reports it and keeps the plain ranking pick.</p><p>No dropped requests.</p><p>No drama.</p><p>Just: cascade off.</p><p>The plain ranking router still ships. On the frozen production holdout it beats always-Claude on quality while cutting estimated cost hard. That part worked.</p><p>The cascade was the part that asked for more trust than the gates would give.</p><h3>What I Am Not Claiming</h3><p>I am not claiming cascades are a bad idea forever.</p><p>The code and experiment configs are still there.</p><p>I am claiming this one did not clear its own enable rules, and I refused to ship it anyway.</p><p>Also: I do not have a checked-in outer-test trophy saying “cascade would have saved X%.” What I have is disabled configs, zero-switch calibration on the gap path, and a README box still unchecked.</p><h3>Next</h3><p>Leaving the cascade off was the honest call.</p><p>It does not explain why the live numbers feel weaker than the holdout.</p><p>Next: why production-only numbers look so much weaker than the test set.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d10a7bc2bad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part-2 CRDT insert: weeks for one character]]></title>
            <link>https://medium.com/@sohamsarkar59/part-2-crdt-insert-weeks-for-one-character-986fb525f76b?source=rss-15b0ae38e60d------2</link>
            <guid isPermaLink="false">https://medium.com/p/986fb525f76b</guid>
            <category><![CDATA[crdt]]></category>
            <category><![CDATA[yj]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Sohamsarkar]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 07:04:51 GMT</pubDate>
            <atom:updated>2026-11-19T07:04:51.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCvxkn3OG2oqBNAUM2GtUw.jpeg" /><figcaption>Part-2 CRDT insert: weeks for one character</figcaption></figure><p>In Part 1 I said inserting one character took weeks to get right.</p><p>It sounds ridiculous.</p><p>It was not.</p><h3>What An Insert Even Is</h3><p>An insert is a letter sitting between two known letters.</p><p>Say Alice types a.</p><p>Bob, offline for a second, also types b after the same place.</p><p>When they reconnect, both replicas have to put those letters in the same order.</p><p>No duplicated text.</p><p>No missing characters.</p><p>No “works on my machine.”</p><p>Just the same string.</p><p>Weavo marks each insert with an id, the letter, the character on its left, and optionally the character on its right. Concurrent inserts after the same left character get ordered by clock, then by who typed them.</p><p>Cute.</p><p>Then the document already has other people typing inside that gap.</p><h3>The Walk</h3><p>When a new letter arrives, you do not slap it down right after its left neighbor and call it a day.</p><p>You walk forward from that neighbor and ask, for each letter you hit: do I stop here, or keep going?</p><p>Three answers.</p><p>Same left neighbor. You are siblings racing for the same spot. Compare ids. The earlier one goes left. Stop in front of anyone who sorts after you.</p><p>Hung off your neighbor. Someone typed after a letter that itself hangs off your left neighbor. Keep walking. That nested text has to stay glued to its parent, even if packets arrive in a weird order.</p><p>Past the cluster. Neither of the above. Stop. Insert here.</p><p>That is the whole algorithm.</p><p>Three cases.</p><p>Weeks.</p><h3>The Tests Lied Nicely</h3><p>Hand-written cases with two peers looked fine.</p><p>Three people inserting at the start of an empty doc, in every arrival order, still converged.</p><p>I celebrated.</p><p>Then the property tests started shuffling messier histories and demanding the same final text no matter the order.</p><p>That is when a wrong comparison stopped being a theory and became a counterexample on screen.</p><p>One version of the walk barely handled nesting.</p><p>Another broke in the wrong direction.</p><p>You fix it.</p><p>Celebrate.</p><p>Run the tests.</p><p>Something else explodes.</p><p>(Usually my fault.)</p><h3>I Was Wrong About The Right Neighbor</h3><p>I treated the right-hand character like optional flavor.</p><p>“Between A and B” sounded helpful. If B was not there yet, I figured A was enough.</p><p>It is not.</p><p>If the right neighbor is missing, the insert does not merge yet. It waits. Same as a missing left neighbor.</p><p>Without that bound, two replicas can disagree about how far the walk is allowed to run.</p><p>The field that looked optional was load-bearing.</p><p>Local typing even records whoever currently sits after the caret, so the gap on the wire matches the gap the user saw.</p><h3>Then The Keyboard Got Weird</h3><p>Browsers do not hand you finished characters while an input method editor is open.</p><p>They start composing.</p><p>They stream half-finished glyphs.</p><p>They end composing.</p><p>If you turn every intermediate glyph into an insert, peers see half-composed junk. A remote edit in the middle warps the caret under you.</p><p>So while composing, Weavo ignores those local updates.</p><p>On compose-end, it commits once.</p><p>That still is not enough.</p><p>Someone else can insert while you are composing.</p><p>The editor shifts the composition’s anchors instead of stomping the in-progress UI. The finished character lands where the gap moved to, not where the caret was before the remote letter arrived.</p><p>Deletes have their own tax.</p><p>Backspacing an emoji has to remove the whole thing humans see, not half a surrogate. Inside the CRDT, each node still stores one UTF-16 unit, and the wire keeps lone surrogates intact so emoji can reassemble on the other side.</p><p>Convergence cares about code units.</p><p>Humans care about graphemes.</p><p>Both have to stay honest.</p><h3>Diagram</h3><p>Box ROOT on the left.</p><p>Arrow to box a (Alice).</p><p>Arrow to box c nested under a (Alice typed after a).</p><p>Arrow to box b (Bob, same left neighbor as a).</p><p>Red scan arrow that stops between a and c (wrong).</p><p>Green scan arrow that walks a → c, then stops before b (right).</p><p>Three labels under the green path: same left neighbor · hung off neighbor · past the cluster.</p><p>Small muted bubble above the caret: IME… with a dashed arrow that only solidifies into a green insert after compose-end.</p><h3>What I Am Not Claiming</h3><p>I did not invent this family of algorithms.</p><p>Existing CRDT work is fantastic.</p><p>I built Weavo to understand why.</p><p>The interesting part was not the paper diagram.</p><p>It was the night the property test printed a divergence, the night I defended an optional right neighbor for too long, and the afternoon an IME taught me that “insert” is also an editor lifecycle problem.</p><h3>Next</h3><p>Inserting one character is solved enough to trust.</p><p>Syncing a late joiner over a pipe that refuses to help is not.</p><p>Next: reply storms, weighted backoff, and the setTimeout(Infinity) bug that should not have compiled in my brain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=986fb525f76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part-1  Building CRDT based Collaborative text-editing SDK]]></title>
            <link>https://medium.com/@sohamsarkar59/part-1-building-crdt-based-collaborative-text-editing-sdk-901c99b964c0?source=rss-15b0ae38e60d------2</link>
            <guid isPermaLink="false">https://medium.com/p/901c99b964c0</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[crdt]]></category>
            <dc:creator><![CDATA[Sohamsarkar]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 14:41:32 GMT</pubDate>
            <atom:updated>2026-07-06T14:41:32.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part-1 Building CRDT based Collaborative text-editing SDK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjcdsetM5tOcUBEzSCpz1g.gif" /><figcaption>Weavo demo</figcaption></figure><h3>Four Months, Thousands of Edge Cases, Two Lines of API</h3><pre>const weavo = createWeavo(&quot;ws://localhost:8080&quot;);<br>weavo.bind(textarea);</pre><p>That’s it.</p><p>Two lines.</p><p>That’s the API I spent four months building.</p><p>If you’re wondering where the other four months went… me too.</p><p>Real-time collaborative editing is one of those problems every engineer looks at and thinks:</p><p><em>“Yeah… that’s probably hard.”</em></p><p>I knew it was hard.</p><p>I just didn’t know it was <strong>“wake up at 2 AM because two users inserted the letter ‘a’ at the same position and somehow broke causality”</strong> hard.</p><p>So I did what any reasonable engineer would do.</p><p>I decided to build one from scratch.</p><h3>Why?</h3><p>Not because the world desperately needed another collaboration library.</p><p>It didn’t.</p><p>And definitely not because existing solutions are bad.</p><p>They’re fantastic.</p><p>I built <a href="https://www.npmjs.com/package/@weavo/client"><strong>Weavo</strong></a> because I wanted to understand <em>why</em> they’re fantastic. I didn’t want to know <em>how to use</em> a collaboration SDK. I wanted to know what happens after you call:</p><pre>weavo.bind(textarea);</pre><p>What magic turns a boring old &lt;textarea&gt; into something that feels like Google Docs?</p><p>As it turns out…</p><p>A lot.</p><h3>It Starts Innocently</h3><p>You think:</p><blockquote><em>“I’ll just sync text between browsers.”</em></blockquote><p>Cute.</p><p>Then you remember people type at the same time.</p><ul><li>Sometimes in the same place.</li><li>Sometimes one user deletes text while another is inserting into it.</li><li>Sometimes packets arrive late.</li><li>Sometimes they arrive out of order.</li></ul><p>Sometimes someone disappears from the internet for a minute, comes back, and expects everything to still work.</p><p>And somehow…</p><p>Everyone should end up with <strong>exactly the same document.</strong></p><ul><li>No duplicated text.</li><li>No missing characters.</li><li>No “works on my machine.”</li></ul><p>Just convergence.</p><h3>Welcome to the Rabbit Hole</h3><p>One paper leads to another.</p><p>Now you’re reading about CRDTs.</p><ul><li>Then Lamport clocks.</li><li>Then causal ordering.</li><li>Then state vectors.</li></ul><p>Then you’re staring at an insertion algorithm wondering why changing one comparison operator causes two replicas to permanently disagree with each other.</p><blockquote>You fix it.</blockquote><blockquote>Celebrate.</blockquote><blockquote>Run the tests.</blockquote><blockquote>Something else explodes.</blockquote><blockquote>Repeat for four months.</blockquote><h3>The Funny Part</h3><p>The public API kept getting smaller. The implementation kept getting bigger.</p><p>Every time I thought,</p><blockquote><em>“This should be easy for the developer,”</em></blockquote><p>future me had to invent another internal data structure to make that true. At some point I realized that’s basically infrastructure engineering. If users notice how clever your implementation is, you’ve probably exposed too much of it.</p><h3>This Series</h3><p>This isn’t going to be a “How CRDTs Work in 15 Minutes” article.</p><p>It’s the story of building one.</p><p>The bugs. The wrong assumptions. The moments where I was convinced the algorithm was broken…</p><p>…only to discover the bug was entirely my fault.</p><p>(Usually.)</p><p>In Part 2, we’ll look at the insert algorithm.</p><p>It sounds ridiculous to say “inserting one character” took weeks to get right.</p><p>By the end, I hope you’ll agree it was time well spent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=901c99b964c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PART 2: From Port Exhaustion to 8.2M Requests: Debugging a Production Performance Issue]]></title>
            <link>https://medium.com/@sohamsarkar59/part-2-from-port-exhaustion-to-8-2m-requests-debugging-a-production-performance-issue-2c5175e09660?source=rss-15b0ae38e60d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5175e09660</guid>
            <category><![CDATA[k6]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sohamsarkar]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-02-12T03:31:01.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Moment of Truth</h3><p>In <a href="https://medium.com/@sohamsarkar59/part-1-how-i-built-a-load-balancer-in-go-and-why-i-designed-it-this-way-1ebed3b9028e">Part 1</a> I built a production-grade load balancer in Go. The architecture <br>was clean. The code was thread-safe. Everything worked perfectly… in my tests.</p><p>Time to see what it could actually handle.</p><p>The Setup:<br>- Load testing tool: k6<br>- Virtual users: 1,500 concurrent<br>- Duration: 12 minutes<br>- Target backends: 10 servers (localhost:8081–8090)</p><p>I hit “run” and watched the metrics roll in.</p><p>The Results:</p><pre>checks_failed: 95.26% (12.8M failed requests)<br>checks_succeeded: 4.73% (640K successful requests)<br>http_req_duration p(95): 359ms<br>Max latency: 24.46 seconds</pre><p>95% failure rate. On a system with perfect code and no bugs.</p><p>What the hell happened?</p><p>This is the story of debugging that failure, finding the root cause, and <br>achieving a 12.8x performance improvement with ONE line of configuration.</p><h3>Step 1: Check the Obvious</h3><p>When 95% of requests fail, you check the basics:</p><p>Application Logs:</p><pre>[http://127.0.0.1:8081] dial tcp: can&#39;t assign requested address<br>[http://127.0.0.1:8082] dial tcp: can&#39;t assign requested address<br>[http://127.0.0.1:8085] dial tcp: can&#39;t assign requested address<br>...</pre><p>Thousands of these errors. All the same: “can’t assign requested address”</p><p>This isn’t a backend error. This is the load balancer failing to CONNECT to backends.</p><h4>My First Hypothesis: “I Have a Bug”</h4><p>I reviewed the code:<br>- Race detector: `go test -race ./…` → Clean<br>- Deadlocks: No mutex issues<br>- Goroutine leaks: WaitGroup properly used<br>- Memory leaks: No unbounded growth<br>- Logic errors: Algorithms working correctly</p><p>The code was fine.</p><h4>My Second Hypothesis: “Backend Capacity”</h4><p>Maybe the backends couldn’t handle the load? I checked backend logs: Barely any requests arriving. The load balancer was failing BEFORE reaching backends.</p><p>This was an infrastructure issue.</p><h3>Step 2: Understanding “can’t assign requested address”</h3><p>Time to Google. This error means:</p><p><em>&gt; The operating system cannot allocate an ephemeral port for a new TCP connection.</em></p><p><strong>What?</strong></p><p>Every TCP connection needs:<br>- Source IP + Source Port (client side)<br>- Dest IP + Dest Port (server side)</p><p>The load balancer was running out of SOURCE PORTS.</p><h3>Step 3: The Math</h3><p>Linux ephemeral port range:</p><pre>$ cat /proc/sys/net/ipv4/ip_local_port_range</pre><p><strong>Available ports: ~28,000</strong></p><p>At 18,781 req/s, how long until exhaustion?</p><pre>TCP connections stay in TIME_WAIT state for 60 seconds (default)<br>Required ports = 18,781 req/s × 60s = 1,126,860 ports<br>Available: 28,000<br>Required: 1,126,860<br>Time to exhaustion: 28,000 / 18,781 = 1.49 seconds</pre><p><strong>The load balancer was exhausting all ports in 1.5 seconds.</strong></p><p>After that, every new connection attempt failed with “can’t assign requested address.”</p><p>But why was it creating so many NEW connections?</p><p>[Continue investigation…]</p><h3>Digging Into Connection Behavior</h3><p>I checked active connections:</p><pre>$ netstat -ant | grep TIME_WAIT | wc -l<br>25,847 # Nearly all ephemeral ports!<br>$ netstat -ant | grep ESTABLISHED | grep 808[0–9] | wc -l<br>143 # Only 143 active connections to backends</pre><p>Wait. Only 143 ESTABLISHED connections, but 25,000 in TIME_WAIT?</p><p>That means:<br>- Most connections were being CREATED<br>- Used ONCE<br>- Then CLOSED<br>- Sitting in TIME_WAIT for 60 seconds</p><p><strong>Connections were not being reused.</strong></p><h4>The Smoking Gun</h4><p>I looked at my backend initialization code:</p><pre>func NewBackend(url *url.URL, failureThreshold int, timeout time.Duration) *Backend {<br> proxy := httputil.NewSingleHostReverseProxy(url)<br> <br> // ⚠️ NO TRANSPORT CONFIGURATION<br> <br> proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {<br> // error handling…<br> }<br> <br> return &amp;Backend{<br> URL: url,<br> ReverseProxy: proxy,<br> Timeout: timeout,<br> }<br>}</pre><p>`NewSingleHostReverseProxy` uses the DEFAULT `http.Transport`.</p><p>What are the defaults?</p><pre>// From Go source code<br>DefaultTransport = &amp;Transport{<br> MaxIdleConns: 100, // Total across ALL hosts<br> MaxIdleConnsPerHost: 2, // PER BACKEND<br> IdleConnTimeout: 90 * time.Second,<br> // …<br>}</pre><p><strong>MaxIdleConnsPerHost: 2</strong></p><p>With 10 backends, only 20 connections could be reused.</p><p><strong>The remaining ~18,760 requests per second were creating NEW TCP connections.</strong></p><p>Each connection:<br>1. Created (uses ephemeral port)<br>2. Used for one request<br>3. Closed<br>4. Enters TIME_WAIT for 60 seconds (port locked)</p><p>After 1.5 seconds: All 28,000 ports exhausted. Cascading failure.</p><p><strong>This was the bottleneck.</strong></p><p>[Explain why defaults are what they are, connection pooling concepts…]</p><h3>One Line That Changed Everything</h3><pre>func NewBackend(url *url.URL, failureThreshold int, timeout time.Duration) *Backend {<br> backend := &amp;Backend{<br> URL: url,<br> Timeout: timeout,<br> }<br>proxy := httputil.NewSingleHostReverseProxy(url)<br> <br> // ✅ THE FIX<br> proxy.Transport = &amp;http.Transport{<br> MaxIdleConns: 1000, // Increased global pool<br> MaxIdleConnsPerHost: 200, // 200 per backend = 2,000 total<br> IdleConnTimeout: 90 * time.Second,<br> DisableKeepAlives: false, // CRITICAL: Enable keep-alive<br> <br> DialContext: (&amp;net.Dialer{<br> Timeout: 5 * time.Second,<br> KeepAlive: 30 * time.Second,<br> }).DialContext,<br> }<br>// … rest of the code<br>}</pre><p>What this does:</p><p>- Each backend can keep 200 idle connections<br>- 10 backends × 200 = 2,000 reusable connections<br>- At 18K req/s, each connection handles ~9 req/s<br>- Connections are reused instead of recreated</p><p><strong>Changed: MaxIdleConnsPerHost from 2 → 200</strong></p><p>That’s it. One configuration parameter.</p><p>[Explain connection pooling, keep-alive, why this works…]</p><h3>Second Load Test</h3><p>Same parameters:<br>- 1,500 concurrent users<br>- 12 minutes duration<br>- 18,781 req/s (same k6 config)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sPhMrI5WARRPQaDKOo7qRA.jpeg" /></figure><p><strong>8,231,488 successful requests in 12 minutes.</strong></p><p>That’s:<br>- 685,957 requests/minute<br>- 11,433 requests/second sustained<br>- The entire population of New York City</p><p>From changing ONE number in a config.</p><h3>Connection State After Fix</h3><pre>$ netstat -ant | grep TIME_WAIT | wc -l<br>847 # Down from 25,000<br>$ netstat -ant | grep ESTABLISHED | grep 808[0–9] | wc -l<br>2,014 # Stable connection pool!</pre><p>Perfect. Connections are being reused.</p><h3>The Remaining 6.82% Failures</h3><p>603,045 requests still failed. Why?</p><p>Backend Capacity:</p><pre>Offered load: 12,269 req/s<br>Backend capacity: ~11,400 req/s<br>Overflow: 869 req/s<br>869 / 12,269 = 7.08% ≈ 6.82% failure rate ✅</pre><p>The math checks out. The remaining failures are LEGITIMATE backend overload.</p><p>This is exactly what load shedding should handle (future work).</p><h3>Key Takeaways</h3><h4>1. Build, Then Break</h4><p>I built a load balancer. Then I tried to destroy it with load testing.</p><p>This revealed a critical bottleneck that code review never would have found.</p><p><strong>Lesson:</strong> Test your systems under realistic load.</p><h4><strong>2. One Line Can Change Everything</strong></h4><pre>MaxIdleConnsPerHost: 2 → 200<br>Impact:<br>- 640K → 8.2M successful requests<br>- 1,270% improvement<br>- Port exhaustion eliminated</pre><p><strong>Lesson: </strong>Small configuration changes can have massive impact.</p><h4>3. Perfect Code Isn’t Enough</h4><p>My code was:<br>- Thread-safe ✅<br>- Well-architected ✅<br>- Bug-free ✅</p><p>But failed 95% of the time due to configuration.</p><p><strong>Lesson:</strong> Production success requires both good code AND good configuration.</p><h4><strong>4. Learn by Doing</strong></h4><p>Building this taught me:<br>- TCP/IP fundamentals (TIME_WAIT, ephemeral ports)<br>- HTTP connection pooling<br>- Load testing methodology<br>- Performance debugging<br>- System capacity planning</p><p>No tutorial could teach this. You have to build and break things.</p><h4>Final Thoughts</h4><p>If you’re learning distributed systems, build something like this:<br>1. Pick a complex system (load balancer, cache, queue)<br>2. Build a simple version<br>3. Load test it<br>4. Find the bottlenecks<br>5. Fix them<br>6. Learn from the process</p><p>You’ll struggle. You’ll hit walls. You’ll discover problems you didn’t <br>know existed.</p><p>That’s where the real learning happens.</p><p>— -</p><p>The code is on GitHub: <a href="https://github.com/soham0w0sarkar/LoadBalancerGo">https://github.com/soham0w0sarkar/LoadBalancerGo</a></p><p>Part 1 (Building): <a href="https://medium.com/@sohamsarkar59/part-1-how-i-built-a-load-balancer-in-go-and-why-i-designed-it-this-way-1ebed3b9028e">https://medium.com/@sohamsarkar59/part-1-how-i-built-a-load-balancer-in-go-and-why-i-designed-it-this-way-1ebed3b9028e</a></p><h4>Questions? Drop a comment below or reach out!</h4><p>Thanks for reading. Now go build and break something. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5175e09660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: How I Built a Load Balancer in Go (and Why I Designed It This Way)]]></title>
            <link>https://medium.com/@sohamsarkar59/part-1-how-i-built-a-load-balancer-in-go-and-why-i-designed-it-this-way-1ebed3b9028e?source=rss-15b0ae38e60d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ebed3b9028e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Sohamsarkar]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 07:44:50 GMT</pubDate>
            <atom:updated>2026-02-10T07:44:50.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>I didn’t start this project to build a production-grade load balancer.</p><p>I built it as a <strong>learning surface</strong> — a compact system that naturally stresses concurrency, shared state, failure handling, and modular design.</p><p>A load balancer is interesting not because it’s complex, but because it sits directly on the boundary between <em>everything is fine</em> and <em>everything is on fire</em>. Design shortcuts show up quickly. Bad assumptions don’t stay hidden.</p><p>This post is about <strong>how I built it</strong> — the decisions I made, in the order I made them, and what those decisions forced me to think about.</p><h3>Starting Small</h3><p>I began with a deliberately narrow goal:</p><blockquote><em>Accept HTTP requests and forward them to one of several backends.</em></blockquote><p>No health checks. No algorithms. No reloads.</p><p>Just enough code to force multiple goroutines to touch the same state.</p><pre>go mod init LoadBalancerGo</pre><p>From the start, I wanted design pressure — not features.</p><h3>The First Architectural Decision: Shared State</h3><p>Very early, everything revolved around one question:</p><blockquote><strong><em>What is the shared boundary in this system?</em></strong></blockquote><p>I chose a single <strong>backend pool</strong> as that boundary.</p><p>Every request reads from it.<br>Very few places are allowed to mutate it.</p><p>This decision did a few important things:</p><ul><li>It made concurrency explicit instead of implicit</li><li>It localized synchronization concerns</li><li>It forced discipline around mutation</li></ul><p>Conceptually:</p><pre>            ┌──────────────┐<br>Incoming →  │  Request     │<br>Requests    │  Path        │<br>            └──────┬───────┘<br>                   │ (read-only)<br>            ┌──────▼───────┐<br>            │ Backend Pool │<br>            └──────┬───────┘<br>                   │ (controlled mutation)<br>            ┌──────▼───────┐<br>            │  Config /    │<br>            │  Health      │<br>            └──────────────┘</pre><h3>Designing the Hot Path First</h3><p>Before adding features, I designed the <strong>request path</strong>.</p><p>The rule was simple:</p><blockquote><em>The hot path must stay small and predictable.</em></blockquote><p>Every incoming request needs to:</p><ol><li>Select a backend</li><li>Proxy the request</li><li>Get out of the way</li></ol><p>Anything that complicated this path had to justify itself.</p><h3>Backend Selection</h3><p>Backend selection happens for every request, so it cannot block.</p><p>Instead of locking, I used <strong>atomics</strong> to advance an index:</p><pre>idx := atomic.AddUint64(&amp;rrCounter, 1)<br>backend := backends[idx%uint64(len(backends))]</pre><p>Atomics here weren’t a performance trick — they were a <strong>forcing function</strong>.</p><p>They forced this path to remain:</p><ul><li>lock-free</li><li>side-effect free</li><li>trivial to reason about</li></ul><p>Once mutation was constrained elsewhere, everything here could safely operate on <strong>snapshots</strong>.</p><h3>Why I Avoided Locks in Request Routing</h3><p>Locking the part of the system that decides request flow effectively <strong>serializes concurrency</strong>.</p><p>That defeats the entire point of goroutines.</p><p>More importantly, locks tend to hide design problems:</p><ul><li>unclear ownership</li><li>excessive mutation</li><li>leaky abstractions</li></ul><p>Atomics did the opposite.<br>They made bad designs uncomfortable early.</p><p>Instead of asking:</p><blockquote><em>“Where do I lock?”</em></blockquote><p>I was forced to ask:</p><blockquote><em>“Why does this need to mutate at all?”</em></blockquote><h3>Adding Features Without Breaking the Model</h3><p>Once the request path was stable, I started layering features — carefully.</p><p>Each feature had one requirement:</p><blockquote><em>It must not complicate the hot path or leak assumptions into other modules.</em></blockquote><h3>Interfaces Everywhere</h3><p>Load-balancing algorithms, middleware, and proxy logic are all interface-driven.</p><pre>type Balancer interface {<br>    Select([]*Backend) (*Backend, error)<br>}</pre><p>This ensured modules could evolve independently.</p><h3>Backend Health Checks</h3><p>Health checks were added as <strong>signals</strong>, not switches.</p><p>A backend isn’t removed on a single failure.<br>Failures degrade confidence gradually.</p><p>This avoided flapping and made state transitions calmer under load.</p><h3>Graceful Backend Removal</h3><p>One of the more subtle parts of building this load balancer was handling <strong>backend removal</strong>.</p><p>Removing a backend is deceptively simple if you think in terms of configuration:</p><blockquote><em>“This backend is gone — delete it from the pool.”</em></blockquote><p>But in a live system, that approach is destructive. Requests don’t disappear just because state changed. If a backend is removed while requests are still in flight, those requests are dropped mid-execution.</p><p>What I wanted instead was <strong>draining</strong>, not deletion.</p><p>Here’s the implementation:</p><pre>func (sp *ServerPool) RemoveBackends(urls []string) {<br> sp.mux.Lock()<br> defer sp.mux.Unlock()<br><br> var targetsToRemove []string<br> var maxTimeout time.Duration<br><br> for _, target := range urls {<br>  index := slices.IndexFunc(sp.Backends, func(existing *Backend) bool {<br>   return existing.URL.String() == target<br>  })<br>  if index == -1 {<br>   continue<br>  }<br>  sp.Backends[index].SetAlive(false)<br><br>  targetsToRemove = append(targetsToRemove, sp.Backends[index].URL.String())<br>  if sp.Backends[index].Timeout &gt; maxTimeout {<br>   maxTimeout = sp.Backends[index].Timeout<br>  }<br> }<br><br> if len(targetsToRemove) == 0 {<br>  return<br> }<br><br> sp.mux.Unlock()<br> time.Sleep(maxTimeout)<br> sp.mux.Lock()<br><br> for _, t := range targetsToRemove {<br>  idx := slices.IndexFunc(sp.Backends, func(existing *Backend) bool {<br>   return existing.URL.String() == t<br>  })<br>  if idx != -1 {<br>   sp.Backends = append(sp.Backends[:idx], sp.Backends[idx+1:]...)<br>  }<br> }<br>}</pre><h4>What’s actually happening here</h4><p>This function intentionally separates <strong>logical removal</strong> from <strong>physical removal</strong>.</p><h4>Phase 1: Stop new traffic</h4><pre>sp.Backends[index].SetAlive(false)</pre><p>The backend is immediately marked unhealthy.<br> From this point on:</p><ul><li>it no longer receives new requests</li><li>the hot path remains unchanged</li><li>no locking is added to request routing</li></ul><p>Existing requests continue normally.</p><h4>Waiting: bounded, not guessed</h4><pre>time.Sleep(maxTimeout)</pre><p>Instead of using a fixed delay, the system waits for the <strong>maximum configured request timeout</strong> of the backends being removed.</p><p>This creates a clean upper bound:</p><ul><li>long enough for the slowest legitimate request</li><li>no longer than necessary</li></ul><p>There’s no attempt to track in-flight requests explicitly. The system already knows how long a request <em>can</em> live — it uses that knowledge.</p><h4>Phase 2: Remove state</h4><pre>sp.Backends = append(sp.Backends[:idx], sp.Backends[idx+1:]...)</pre><p>Only after enough time has passed is the backend actually removed from the pool.</p><p>At this point:</p><ul><li>no requests should still be using it</li><li>no traffic was dropped</li><li>no coordination with the hot path was required</li></ul><h4>Why this works so well</h4><p>What I like about this approach is that correctness comes from <strong>ordering</strong>, not from force.</p><p>There’s no:</p><ul><li>global pause</li><li>reference counting</li><li>request tracking</li><li>complex synchronization</li></ul><p>Instead:</p><ul><li>new work is redirected immediately</li><li>old work is allowed to finish naturally</li><li>state mutation happens only when it’s safe</li></ul><p>This mirrors how real systems drain traffic — by narrowing where new work is allowed to go until old work disappears on its own.</p><h3>Stress Testing: When the System Said “Yes” for Too Long</h3><p>Once the core pieces were in place, I load-tested the system.</p><p>Not to find peak throughput — but to understand how it behaves once it’s clearly overloaded.</p><p>The tests were gradual ramp-ups using <strong>k6</strong>, with:</p><ul><li>up to <strong>1500 concurrent virtual users</strong></li><li>long plateaus instead of short spikes</li><li>early runs with <strong>logging, keep-alives, and load shedding disabled</strong></li></ul><h4>Baseline behavior (no safeguards)</h4><p>Under load, the system attempted roughly <strong>16–18k RPS</strong>, but only <strong>~1.5–1.6k RPS</strong> completed successfully.</p><p>The rest failed.</p><p>What I observed:</p><ul><li><strong>~90% failure rate</strong></li><li><strong>Tail latencies of 10–20 seconds</strong></li><li>Requests piling up faster than they could be processed</li><li>OS-level network and timeout errors surfacing before any application-level backpressure</li></ul><p>At this point, the system wasn’t “slow” — it was overwhelmed.</p><p>It kept accepting work even when it had no capacity left to handle it.</p><h4>Optimizations increased pressure, not capacity</h4><p>I made several performance improvements:</p><ul><li>Removing per-request logging pushed attempted RPS to <strong>~20–24k</strong></li><li>Switching from localhost to an IP added another <strong>~13%</strong></li><li>Enabling connection reuse increased attempted RPS to <strong>~22k+</strong></li></ul><p>But the result was unexpected at first.</p><p>Despite ~40% higher incoming pressure:</p><ul><li>Successful RPS barely moved (<strong>~1.8–2.1k</strong>)</li><li>Failure rate stayed close to <strong>90%</strong></li><li>Tail latency still exploded (<strong>15–25s</strong>)</li></ul><p>Every optimization just helped the system fail faster.</p><h4>The real problem</h4><p>The system wasn’t failing because it was slow.</p><p>It was failing because it <strong>kept accepting work it had no chance of completing</strong>.</p><p>That led to:</p><ul><li>unbounded queues</li><li>timeout cascades</li><li>wasted CPU and memory</li><li>kernel-level failures surfacing before the application could react</li></ul><p>The load test made one thing clear:<br> throughput wasn’t the limiting factor — <strong>admission control was</strong>.</p><h3>What Building This Taught Me</h3><p>A few things surprised me:</p><ul><li>How quickly locks complicate reasoning</li><li>How calm the system felt once mutation was constrained</li><li>How architectural choices show up immediately under load</li></ul><p>Concurrency stopped feeling scary once responsibilities were clear.</p><p>Fewer locks.<br>Fewer assumptions.<br>Fewer “just in case” checks.</p><h3>Closing</h3><p>This post was about <strong>how I built the system</strong>.</p><p>The next phase was about breaking it harder — overload, failure modes, and what graceful behavior actually means under pressure.</p><p>That’s where most of the real lessons came from.</p><p>If you enjoy learning systems by building uncomfortable things, you might enjoy exploring the project here:</p><p>👉 <a href="https://github.com/soham0w0sarkar/LoadBalancerGo">https://github.com/soham0w0sarkar/LoadBalancerGo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ebed3b9028e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>