<?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"><channel><title><![CDATA[Ernest]]></title><description><![CDATA[Ernest]]></description><link>https://ernest-khas.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/67b4f489a46472f3ce729621/9963a2c9-ec75-4864-871b-cffed464476c.jpg</url><title>Ernest</title><link>https://ernest-khas.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 02:01:38 GMT</lastBuildDate><atom:link href="https://ernest-khas.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[SporeMachine: Building a Harmless Botnet in Go]]></title><description><![CDATA[Building a decentralized P2P swarm in Go with gossip, Merkle trees, peer discovery, and autonomous growth—without a central coordinator.]]></description><link>https://ernest-khas.hashnode.dev/sporemachine-building-a-harmless-botnet-in-go</link><guid isPermaLink="true">https://ernest-khas.hashnode.dev/sporemachine-building-a-harmless-botnet-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[p2p]]></category><category><![CDATA[networking]]></category><category><![CDATA[gossip protocol]]></category><category><![CDATA[merkle tree]]></category><dc:creator><![CDATA[Ernest Khasanzhinov]]></dc:creator><pubDate>Thu, 01 Oct 2026 10:30:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/9e1d1ff3-52a2-4930-9642-b7c1db1fb8b3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>1. Introduction</h2>
<p>As a kid, and later in college, I devoured technical articles about botnets and how their nodes communicate.</p>
<p>What fascinated me was how individual agents, each running on its own machine, could form something that felt like a living organism:<br />a network that grows, adapts, and spreads, with countless internal processes unfolding out of sight.</p>
<p>I've always been drawn to that hidden side of software, and it's shaped my whole career in backend engineering.<br />Small mechanisms, processes, and connections all working together to make something much bigger happen.<br />Once you start understanding how they fit together,<br />it feels a bit like gaining X-ray vision: you begin to see how things really work.</p>
<p>Eventually, I wanted to build an autonomous network of agents myself. Something like a botnet :)</p>
<p>But without the hacking and the harm. Let's just focus on the interesting part :)</p>
<h2>2. Main Idea</h2>
<p>That's how SporeMachine was born: an experimental network of volunteer agents with no single coordinator, and no hacking, no stealth install, no malicious payload.</p>
<p>The idea: a swarm of autonomous nodes that grows on its own.<br />One entry point launches the first node, and from there every node can decide for itself, based on its parameters, whether to give life to the next one. The network needed to actually do something, so I could put it to the test.<br />I decided the swarm should be able to execute commands signed by the owner (bash commands, for example) and store files across the network.<br />The owner can connect to any node, push files or commands onto that one node, and the network takes care of spreading them to every other node and making sure they end up everywhere.</p>
<p>Separately, I baked in a threat model from the start that surprises a lot of people: capturing a single node in this system is normal, not an incident.<br />Files, commands, metrics: an attacker gets all of it if they get their hands on a given node.<br />We're spreading this network across every device we can, and there's just no way to guarantee any single node's safety.<br />The swarm builds itself faster than it can hide.</p>
<h2>3. Technologies I wanted to use</h2>
<p>What excited me and what I wanted to use: P2P, gossip, Merkle trees, gRPC, SWIM, bbolt, content addressing, CRDT/grow-only sets.</p>
<table>
<thead>
<tr>
<th>Idea</th>
<th>What it is</th>
<th>Why I chose it</th>
<th>Why it beats the alternatives / what I compared it to</th>
</tr>
</thead>
<tbody><tr>
<td><strong>P2P</strong></td>
<td>A network with no single server/coordinator: nodes are peers, talking to each other directly</td>
<td>This is the whole premise of the project: a swarm with no center that keeps living without an owner</td>
<td>With a coordinator this would've been orchestration, not a network. An interesting problem, but a different one</td>
</tr>
<tr>
<td><strong>Raft</strong></td>
<td>The classic leader-based consensus protocol</td>
<td>Considered and deliberately rejected, but not just because Raft has a leader. The real reason: the network's data model (a grow-only set, objects only ever get added, nothing to conflict over) doesn't contain any global invariant that would even need consensus to protect. The one time we tried to introduce such a global invariant, a hard cap on the number of nodes (<code>max_node_count</code>), it turned out to be unenforceable in this model without a coordinator or some separate scarce/trusted resource. So we just dropped it instead of adding consensus to defend it</td>
<td>Rejected not in favor of some other consensus protocol, but in favor of dropping coordination altogether</td>
</tr>
<tr>
<td><strong>Gossip</strong></td>
<td>Nodes spread news to each other through random exchanges, no central broadcast</td>
<td>An interesting protocol in its own right. I'm implementing it myself instead of grabbing a library, specifically to understand how it actually works in practice</td>
<td>Comparing it against ready-made libraries (e.g. memberlist) is planned, but hasn't happened yet</td>
</tr>
<tr>
<td><strong>Merkle tree</strong></td>
<td>A hash tree for quickly comparing large data sets between nodes</td>
<td>Inspired by Dynamo (Amazon), that's where the whole idea of anti-entropy reconciliation via hash trees came from</td>
<td>The payoff is in the traversal protocol itself on divergence (details in the Node chapter), not just in having a tree; at the pilot's current scale it's barely noticeable, waiting for the file count to grow</td>
</tr>
<tr>
<td><strong>gRPC</strong></td>
<td>Transport for requests between nodes</td>
<td>Official Go support, typed code generated from <code>.proto</code>, integrates with <code>context</code> (deadlines/cancellation)</td>
<td>The implicit alternative, JSON/REST: expecting smaller messages thanks to binary Protobuf</td>
</tr>
</tbody></table>
<h2>4. Naming</h2>
<p>From my own experience as a developer, I've learned that naming things properly is a genuinely hard problem.<br />With variables, you want the name to reflect what the variable means.<br />But with a module or a microservice, trying to spell out the meaning in the name is often a mistake, and it leads to names like <code>aws_searcher_keeper_synchronizer</code>: something meant to make the code more readable that ends up doing the exact opposite.</p>
<p>For this project, I decided to base the naming on the Warhammer universe:</p>
<ul>
<li><p><strong>Primogenitor</strong> — the owner's process, the sole holder of the private key; it launches the first node and hands it the Genesis. Named after "Primogenitor": in Warhammer 40,000 lore, that's what they call one of the gene-seed organs, the one responsible for the original genetic material that every later generation is built from.<br />Same logic here: Primogenitor is the single source that all of the network's "genetics" come from (Genesis, keys, the first node), while staying outside the network itself.</p>
</li>
<li><p><strong>Norn</strong> — when I picked the name, I imagined it as an external companion service attached to each node, deciding whether a new node could be created and launching it if so (the naming logic below is about that role, the one who decides a new node's fate, regardless of how it's actually implemented under the hood).<br />The role matches almost literally: my Norn is the thing that decides whether a new node gets to come into being.</p>
</li>
<li><p><strong>Chronicle</strong> — an external, independent observer that pulls only metrics from any node and takes no part in running the network.<br />The name echoes the "Remembrancers" from Warhammer 40,000 lore, the chroniclers and artists who tagged along with the Great Crusade fleets.<br />My Chronicle has no power over the network either (it doesn't even need the owner's key); it just watches and records.</p>
</li>
</ul>
<p>And the project itself, accordingly, is <strong>SporeMachine</strong>:<br />"the spore machine," or in spirit, "the machine that grows a network."<br />Spore: a tiny beginning that a new organism grows out of. In this project, the image of new, independent nodes appearing.<br />Machine: a machine, a mechanism.<br />This growth happens by fixed rules, as part of a system that was designed on purpose.<br />What came out of it is an engineered system that grows like a living organism. It starts from a single node, gradually spreads, exchanges data, and keeps living without me sticking around.</p>
<h2>5. What I ended up planning to build in the pilot</h2>
<p>It all starts with launching Primogenitor: it gathers the network's initial parameters into a Genesis object and hands it to the first node.<br />After that it's optional: it might never run again, or it might come back from time to time to push a new file or command into the network, or to send a signal that makes the whole network self-destruct.<br />Either way, it doesn't control the network itself.<br />More on Primogenitor, and exactly what's inside Genesis, in the next chapter.</p>
<p>From that point on, the swarm lives on its own.<br />Nodes are equal peers with no coordinator: they periodically exchange with a few neighbors, check who's alive, and reconcile who has which data and metrics, pulling in whatever's missing.<br />The network grows without me too.<br />Every node has a built-in mechanism that occasionally proposes spawning a new node, and the decision to agree or not is made locally, by the node itself.</p>
<p>Separate from all that: independent observation.<br />Chronicle connects to any reachable node and pulls only the encrypted metrics,<br />without taking part in running the network, and turns that history into dashboards.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/ea4745be-b220-48f3-933e-38d161657ba8.svg" alt="" style="display:block;margin:0 auto" />

<p>What came out of it isn't quite a botnet and isn't a classic P2P framework either.<br />Something in between: a swarm with no single owner, where I, as the owner, only ever touch it when the network starts or when I need to check the metrics, and everything that happens in between is out of my control.</p>
<h2>6. Primogenitor</h2>
<p>Primogenitor is a standalone CLI with no persistent process: every call is one action, and the process ends right after. <code>start</code> launches the first node and hands it the Genesis. <code>submit-file</code> and <code>submit-command</code> sign and push a file or a bash command into the network through any reachable node; Primogenitor isn't tied to any particular one, it can reach out to whichever node it happens to know the address of.</p>
<p><code>terminate</code> broadcasts a signed self-destruct signal for the whole network. Between calls, Primogenitor doesn't need to be running at all: it's only needed for the moment of that one action.</p>
<p>The Genesis that <code>start</code> assembles and hands over contains: the network ID; the owner's public key (not for decryption, for verifying the signature on files and commands, since there's no encryption here at all, content stays readable, the signature only proves authorship); the public half of the metrics encryption key, so a node can encrypt its own metrics (the private half never reaches the nodes, it stays only with Primogenitor and Chronicle); and the network's growth rules: how deep it's allowed to grow (how many generations), how many children one node can spawn at a time, and at what interval.</p>
<p>The logic: only Primogenitor pushes files and commands into the network, and only Primogenitor and Chronicle can decrypt the metrics. Also, only Primogenitor can trigger the network's self-destruct.</p>
<p>For the first version, the network runs locally, each node its own process. Down the line, each node might end up in its own Docker container, maybe even its own machine.<br />But only Primogenitor and Norn decide how the network actually gets launched; the nodes themselves have no idea where they're running. That knowledge also travels through the Genesis.</p>
<h2>7. Node</h2>
<p>A node is a handful of ongoing responsibilities (membership, data and metrics exchange, command execution, norn) that run in parallel and share one local identity and state, rather than being split across independent components. The moment a node starts (the first one from Primogenitor, every next one from its parent's norn), it gets its own copy of the Genesis, its own identity, a generation number, and the addresses of its first contacts, and from then on it lives entirely on its own, with no dependency on whoever launched it.</p>
<p>Inside, a handful of persistent loops keep running:</p>
<ul>
<li><p><strong>Membership (SWIM)</strong> — its own goroutine that pings <strong>one</strong> random neighbor every few seconds, waits for an ack, falls back to indirect probing through other neighbors if needed, and gradually marks unreachable ones as suspect, then dead. Neighbor data lives only in memory. No tree hashes are involved here, just liveness checks.</p>
</li>
<li><p><strong>The unified exchange round</strong> — a separate goroutine: every interval, the node picks <strong>several</strong> random live neighbors and, in one pass, exchanges with each of them:</p>
<ul>
<li><p>the root hash of the data Merkle tree;</p>
</li>
<li><p>the root hash of the metrics Merkle tree;</p>
</li>
<li><p>the list of known neighbors (peer exchange).</p>
</li>
</ul>
<p>It's "unified" because all three of those travel in one round instead of three separate cycles. If any of the hashes disagree, that's what kicks off the actual Merkle walk, in its own short-lived goroutine for that specific mismatch; how the reconciliation itself works is explained in detail below.</p>
</li>
<li><p><strong>Metrics</strong> — its own goroutine, collects data about itself roughly every 3 minutes, packs it into an object, and drops it into the second tree (more on this in the Chronicle chapter).</p>
</li>
<li><p><strong>Norn</strong> — a companion that lives alongside the node and holds the spreading logic: it decides whether a new member can be born and launches it once approved. Right now it's just a goroutine of the same node, not a separate process.</p>
</li>
</ul>
<h3>How the Reconciliation Works</h3>
<p>The actual reconciliation mechanism for objects (files and commands) between nodes deserves its own explanation.<br />A Merkle tree (hash tree) is a structure where every leaf is a hash over a fixed group of objects, and every node above it is the hash of its children's hashes, all the way up to a single root hash that effectively "folds up" the contents of the whole subtree (<a href="https://en.wikipedia.org/wiki/Merkle_tree">Wikipedia</a>).</p>
<p>My own mechanism is inspired by Dynamo (Amazon): that's exactly where the idea of anti-entropy reconciliation between nodes via a Merkle tree comes from, compare the root hash first, and only descend deeper on a mismatch, instead of shuttling the whole object list back and forth.<br />But it's not a one-to-one copy: Dynamo builds a separate tree for each key range and compares it across a fixed set of replicas responsible for that range, and the data itself is mutable and versioned (conflicting writes get resolved via vector clocks).</p>
<p>In my case there's one tree per node (or rather two, data and metrics kept separate), reconciled against a random neighbor on every round instead of a fixed set of replicas, and the objects themselves are immutable and content-addressed, so there's nothing to conflict over, it's just a set union (see the table in chapter 3).</p>
<p>Specifically in my tree: the leaves aren't individual objects — they're 256 fixed groups, one for each possible first byte of an object's hash.<br />Every object's ID is the hash of its content, and it lands in the group matching that hash's first byte.<br />A leaf's hash is the hash of the sorted object IDs in its group; the parent above computes its hash as the hash of its children's hashes, and so on up to the root.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/1a6de59a-be08-48b8-9ac0-d09da791ad22.svg" alt="" style="display:block;margin:0 auto" />

<p>A node never broadcasts the full list of its objects, only a single root hash of the tree.<br />If it matches the neighbor's, there's nothing to reconcile on that tree, and the round is done.<br />If it doesn't match, the descent begins: request the children's hashes at the current level, see exactly where they diverge, and go deeper only down the branches that disagree, matching subtrees are never touched at all.</p>
<p>This works thanks to a specific property of bbolt: keys are stored sorted, so every object in a given branch (one of 256 groups keyed by the hash's first byte) can be read out with a single prefix range scan, no separate index needed on top of storage.<br />Once we reach the actual leaves, that's where we compare real object IDs and pull down whatever's missing.<br />The payoff of this approach shows up on large sets: the more objects a node has, the more expensive it gets to shuttle the full hash list back and forth every round, and the more noticeable the saving from never having to touch the part of the tree that already matched.</p>
<h3>Executing Commands and Handling Failures</h3>
<p>Command execution works in a similar spirit: there's no persistent loop, but every new signed command that passes verification gets launched in its own short-lived goroutine,<br />so that one long-running Bash command doesn't block new objects from coming in through the same exchange round that delivered it.<br />A byte-identical command delivered twice (say, arriving through gossip more than once) doesn't trigger a second execution, the node recognizes it by its already-computed <code>object_id</code> and simply doesn't hand it off to execution again.</p>
<p>If any of the persistent goroutines panics, the node tries to restart it up to three times; if that doesn't help either, the whole node shuts down rather than keep living in a half-broken state.</p>
<h2>8. Norn</h2>
<p>It's worth stressing again: at heart, this isn't a malicious botnet, but it still needs some mechanism for autonomous spreading.</p>
<h3>How Real Botnets Do It</h3>
<p>8.1. A node finds a suitable device on its own and launches a new node on it. In botnets this is self-propagation, or worm-like spreading. FritzFrog is an example. Members can still share target information with each other here: acting independently doesn't rule out coordination.</p>
<p>8.2. A node receives a target from outside and carries out the deployment. The device to host the new node is chosen by an external coordinator or by other members of the network. The functionality needed to do this is either already present in the executor or supplied by an additional module.</p>
<p>8.3. An external component deploys the new node on its own, after which it joins the existing network. The already-running nodes take no part in setting it up. The new member either connects to the network itself or gets introduced to it by the external component.</p>
<p>8.4. A node finds a suitable device, but a separate loader handles the actual deployment. Discovery and installation are split between different components. In the classic Mirai, bots found reachable devices and reported the results to infrastructure, where a separate loader installed the malware.</p>
<p>These patterns can combine within a single system.</p>
<h3>How Norn Actually Does It</h3>
<p>Since we're not actually infecting anything, only simulating it, ours ends up looking something like 8.3, and that's exactly what Norn does.<br />It proposes a candidate to the parent (just a generated ID, not an actual node yet), not a ready-made node; the parent, using its own spreading logic, approves or rejects the proposal, and only on approval does Norn actually spawn the new node.</p>
<p>Among other things, this keeps any single parent from ending up with too many children.<br />When the spawn does happen, Norn launches the new process with a <code>--parent-id</code> flag pointing back to itself, since without that Chronicle's growth graph would just see disconnected dots with no parent-child links,<br />and hands the new node the same Genesis, a computed generation number (its own plus one), and the list of neighbors it already knows about, so it doesn't start out in a complete vacuum.</p>
<h2>9. Chronicle - Monitoring</h2>
<p>We need metrics to keep an eye on the whole network and understand what's happening with it and where the problems are.<br />We can't poll every node directly: in theory, we don't have access to all of them at once.<br />That's how the idea for an additional service, <strong>Chronicle</strong>, was born: like Primogenitor, it connects to any node and pulls a set of metrics to build dashboards and graphs from.<br />All the graphs are essentially not live but historic: they show how the network has lived, not what's happening right this second.</p>
<p><em>That raises a question</em>: how does every node end up with metrics for the whole network, if Chronicle only ever connects to one?<br /><em>Answer:</em> metrics are encrypted with the public half of the metrics encryption key, which every node has.</p>
<p>Any node can encrypt, including one an attacker has captured, but only whoever holds the private half of that key can decrypt, and that's only Primogenitor and Chronicle.<br />Encrypted metrics sync between nodes through a <strong>second, separate</strong> Merkle tree (the same mechanism described in the Node chapter), so any reachable node already has the whole network's picture accumulated on it, only Primogenitor and Chronicle can actually read it.</p>
<p>Specifically, the mechanism works like this: roughly every 3 minutes, a node packs its current metrics into an object, hashes it, and drops it into this tree. From there it spreads through gossip as usual.</p>
<p>There's a nice side effect too: no need for clock sync between nodes, metric blocks are compared by hash, not by timestamp.</p>
<p>For metrics, this reconciliation protocol is probably overkill: a constantly changing time series doesn't map well onto a tree built for comparing large but mostly stable sets.<br />Later on, we'll probably rework this into an epoch system with a TTL: a separate tree for each fixed time window instead of one endlessly growing tree, not unlike how Dynamo itself doesn't use one tree for everything but many separate trees, one per key range.</p>
<p>For now, though, we're also treating the current version as an extra stress test, a way to see how the reconciliation mechanism itself holds up against constantly changing data.</p>
<h2>10. Chronicle - graph</h2>
<p>For visual clarity I decided to add a visualization: a graph of how the swarm grows, when and from whom each new node appears, and at what pace.<br />I plan to show node death too.<br />In the current GIF, nodes just don't die.</p>
<p>This works the same way as metrics: a node's birth time and its parent's ID accumulate in that same metrics tree and sync along with everything else. Chronicle then pulls them out and aggregates them into a single CSV, and a separate renderer builds a GIF from it, laid out as a tree (d3-hierarchy).</p>
<p>The GIF below was recorded with a branching factor of 3 and a depth of 6, which by the formula caps out at 1093 nodes, and the swarm in the recording grows right up to that number.<br />I sped it up 10x to make it watch better, but honestly, proportionally to the real intervals from the CSV, not at some made-up pace.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/e3ad53fe-54c9-4c76-9711-38c09f2151ec.gif" alt="" style="display:block;margin:0 auto" />

<h2>11. Threat Model and What's Next</h2>
<p>I'm well aware that any node can be compromised and end up working for a different owner.<br />Once the network is running, there's no decision-making center left that controls every node.</p>
<p>BUUUT that's not actually a problem :)<br />Only Primogenitor holds the private key, so only Primogenitor can push files and commands into the network.<br />And in this version, the content of files and commands isn't secret to begin with, and really can't be, since the nodes live on the client side anyway. Metrics are encrypted the moment they're snapshotted, with the public half of the metrics encryption key, which every node has (only enough to encrypt, never to decrypt).<br />Yes, a captured node always exposes its current state in the clear: the live in-memory counters each snapshot is built from.<br />Only the sealed snapshots are encrypted; the running state they come from isn't.</p>
<p>But the history and metrics of other nodes can only be decrypted by Primogenitor and Chronicle, since only they hold the private half of that key.</p>
<p>All the code is available on <a href="https://github.com/ErnestK/spore-machine">GitHub</a>. More detailed metrics, debugging, and a look at the rough edges will be in a follow-up article...</p>
]]></content:encoded></item><item><title><![CDATA[[Part 1]: 10K, 1M.. or more active SSE streams
Building MCPSprut ( MCP Hub )]]></title><description><![CDATA[How I built an MCP hub designed to hold as many SSE streams as a single machine can handle]]></description><link>https://ernest-khas.hashnode.dev/part-1-10k-1m-or-more-active-sse-streams-building-mcpsprut-mcp-hub</link><guid isPermaLink="true">https://ernest-khas.hashnode.dev/part-1-10k-1m-or-more-active-sse-streams-building-mcpsprut-mcp-hub</guid><category><![CDATA[mcp]]></category><category><![CDATA[MCP Client]]></category><category><![CDATA[golang]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[SSE]]></category><dc:creator><![CDATA[Ernest Khasanzhinov]]></dc:creator><pubDate>Sun, 05 Apr 2026 14:09:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/8b6e435d-1f25-4fa5-b847-0cdd24326211.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're already familiar with the MCP protocol, you know it allows LLMs to interact with external services.</p>
<p>If not — a quick example.<br />You're running Claude Code locally on your machine and want it to work with Gmail: read emails, send emails, etc.<br />You connect a Gmail MCP server and voilà — now when you ask Claude Code to find an email and notify your mom about something, it automatically knows how to call the MCP server and send the email through it.</p>
<p>The way it works: each MCP server exposes tools (think REST endpoints) that the LLM can call whenever it decides they're needed to achieve a goal.</p>
<p>But here's the interesting part — there's no versioning for tools.<br />Tools can change at any time: new ones can be added, old ones removed.</p>
<p>To handle this, the protocol uses SSE (Server-Sent Events) — the server maintains an open stream with each client and pushes an event the moment the tool set changes.<br />The client must immediately re-fetch the updated list of tools.<br />In other words, the protocol expects the client to maintain a persistent stream with every server it's connected to — you need tools to be up-to-date in real time, not on a schedule.</p>
<p>Now imagine you're running a multi-tenant AI platform where each user brings their own Gmail, Slack, Jira servers and connects them to their agents — multiply by thousands of users, and you're looking at tens of thousands of connections.</p>
<p>And that's when it got interesting for me.<br />What if you need to maintain 10K, 1M active streams... <strong>or even more?</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/57122cda-b310-4d22-99ac-ea5d1dd7a570.gif" alt="" style="display:block;margin:0 auto" />

<p>I wanted to build a system like that and find out how far we can push it on a single machine. That's exactly what we'll do below.</p>
<p>I chose Go for the initial version.<br />Goroutines map perfectly to "one connection per server", and for a prototype Go is simply faster to develop with.<br />For squeezing out maximum performance, Rust is on the radar — but that's a story for a future iteration.</p>
<hr />
<h2>Simulator</h2>
<p>But before building the hub itself, I needed something to throw 10,000 servers at it.<br />How else would we build an MCP hub without a simulator that generates these millions of MCP servers?<br />Finding real servers, dealing with authentication would be nearly impossible — plus we specifically need these servers to change their tools frequently.<br />It would serve as our load testing tool and prove that the whole thing actually works.<br />So I wrote a simple simulator in Go.<br />Of course it's not the same as real servers, but it gives a reasonable... hmm, simulation.</p>
<p>The simulator is actually pretty fun. Here's the <a href="https://github.com/ErnestK/mcp-simulator/tree/v0.2.0">source code on GitHub</a>. Here's its architecture:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/4b21d8e0-7653-4247-9a2d-1690b404f4e5.png" alt="" style="display:block;margin:0 auto" />

<p>The trick is — we don't spin up 10,000 separate processes.<br />A single process creates a pool of virtual MCP servers, all behind one HTTP server. Routing is based on the path: <code>/server/0/mcp</code>, <code>/server/1/mcp</code>, etc. That way we get 10,000 "servers" without 10,000 ports.</p>
<p>Each virtual server runs its own goroutine that mutates tools at random intervals (5-60 seconds).<br />Three mutation types — <strong>add</strong>, <strong>remove</strong>, <strong>update</strong>. Tool names are generated from verb+noun combos (<code>"get_users"</code>, <code>"create_reports"</code>, <code>"deploy_clusters"</code>), so logs actually look realistic.</p>
<pre><code class="language-go">func Mutate(current []Tool) ([]Tool, MutationEvent) {
    action := rand.Intn(3)
    switch action {
    case 0: // add
        name := randomToolName()
        ...
        return append(current, tool), MutationEvent{Type: MutationAdd, ToolName: name}
    case 1: // remove
        if len(current) &lt;= 1 {
            return Mutate(current) // won't leave a server with zero tools
        }
        ...
    default: // update
        current[idx] = generateTool(current[idx].Name)
        ...
    }
}
</code></pre>
<p>Right now we're already spinning up 10,000 servers without issues, and mutations run indefinitely.<br />Later we'll push the simulator to the limit — to find out the maximum number of servers a single machine can handle.</p>
<p>The simulator currently has zero dependencies, and honestly doesn't need much — it's a load testing tool that's never going to production.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/1c7e5ab3-80a4-4a8f-a61c-800151581b3f.gif" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>MCPSprut</h2>
<p>The main focus is the MCP hub, which I named <a href="https://github.com/ErnestK/mcpsprut/tree/v0.2.0">MCPSprut</a>.<br />We need cool naming — and "Sprut" (octopus) is exactly what we do: spread our tentacles and hold on.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/6c69d465-d5d9-4dc9-99c8-a70b6b899908.png" alt="" style="display:block;margin:0 auto" />

  
<p><strong>tldr:</strong> A service that connects to thousands of MCP servers, maintains an open SSE stream with each one, catches tool changes in real time, and persists them to a database.  </p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/1705e896-5277-4e6e-bffb-f392a52477de.gif" alt="" style="display:block;margin:0 auto" />

<h3>Results</h3>
<p>The graphs already show that MCPSprut handles this more than well — 10,000 servers is comfortable, and we can definitely push further. It was fairly straightforward to build and a lot of fun.</p>
<p>The first graph — <strong>Active Streams</strong> — shows MCPSprut ramping up to 10,000 simultaneous SSE connections.<br />Once it hits the plateau — all connectors are up and holding their streams stable, nobody is dropping.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/fe5e4db2-683c-410b-ab88-7b2182d1a9ba.png" alt="" style="display:block;margin:0 auto" />

  
<p>The second — <strong>Tools Fetched (rate)</strong> — shows how many times per second MCPSprut re-fetches tool lists from servers after receiving a "tools changed" event.<br />The higher the line, the more servers are actively changing their tools and MCPSprut is keeping up.<br />The plateau here means MCPSprut is processing events at a steady rate — no backlog,<br />no falling behind.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67b4f489a46472f3ce729621/72c7ab65-026b-4786-87d2-2ea3db7e1b88.png" alt="" style="display:block;margin:0 auto" />

  
<p>To keep this article focused, I'm only showing these two key graphs as proof that the MVP works.<br />A detailed performance analysis with profiling, memory and CPU metrics<br />will come in Part 2 and 3.</p>
<hr />
<p>Below are the technical details and some interesting engineering choices I made along the way.</p>
<h2>Deep Dive into MCPSprut</h2>
<p>When I sat down to write it, I knew right away I'd be using Go, and the architecture would most likely follow the <strong>fan-out with supervision</strong> pattern. It felt like a natural fit for my use case — I considered alternatives, did some research, but this one mapped to the problem best.</p>
<p>I start a master process in main, load all the configs, and spawn a goroutine for each server. Each one connects to its MCP server, holds an SSE stream, and listens for events. As soon as it receives a tools-changed event, it re-fetches the tools and saves them to the database. Sounds easy!</p>
<pre><code class="language-go">func (h *Hub) Start(ctx context.Context) error {
    ...
    for _, server := range servers {
        h.startConnector(ctx, server)
    }
    ...
}
...
func (h *Hub) startConnector(...) {
    ...
    go func() {
        conn := connector.NewConnector(server, ...)
        conn.Run(ctx) // holds SSE stream, listens for events
    }()
}
...
</code></pre>
<p>Worth noting — the server addresses are already known, they're already in the database. This service is purely about maintaining streams for real-time tool updates. How do servers get into the database? They're pre-loaded by the user.</p>
<h3>Storage Interface</h3>
<p>An obvious question came up right away — which database to use? I decided to leave this question open. Answering it upfront is hard and not really necessary. It depends on the use case:</p>
<ul>
<li><p><strong>Postgres</strong> — persistence is never a bad thing</p>
</li>
<li><p><strong>Redis</strong> — speed matters too</p>
</li>
<li><p><strong>ClickHouse</strong> — if the number of servers gets really large</p>
</li>
<li><p>or even just <strong>writing to a file</strong> — why not</p>
</li>
</ul>
<p>In my current implementation I simply defined a storage interface. To add support for any database, you just need to implement the methods described in the interface.<br /><em>Note the</em> <code>OnNewServer</code> <em>callback — we'll get to that one below.</em></p>
<pre><code class="language-go">type Storage interface {
    // Returns all known MCP servers
    LoadServers(ctx context.Context) ([]ServerConfig, error)
    // Persists a new server config
    SaveServer(ctx context.Context, server ServerConfig) error
    // Registers a callback fired when a new server is added
    OnNewServer(callback func(ServerConfig))

    // Writes tool updates in bulk
    SaveToolsBatch(ctx context.Context, updates []ToolUpdate) error
    // Returns current tools for a given server
    GetTools(ctx context.Context, serverID string) ([]Tool, error)

    // Closes the underlying connection
    Close() error
}
</code></pre>
<p>As a test implementation I went with <strong>BoltDB</strong> — an embedded database written in pure Go. For a prototype it's a perfect fit.</p>
<h3>Batch Writer</h3>
<p>I realized that writing to the database on every single update is expensive — we need the ability to write in batches. And we need to control the batch size.</p>
<p>The idea was simple — collect updates and write them when the batch reaches a certain size, say 100. The cool part is that communication with the batcher happens through a channel, so it works concurrently and doesn't block the connectors.</p>
<p>But then it hit me — what if we collect 3 updates and the next 97 never come? We'd be waiting forever with stale data sitting in the buffer. So it became an either/or: either the batch is full, or a time limit is reached and we flush whatever we have. Go's <code>select</code> makes this really clean:</p>
<pre><code class="language-go">...
select {
// process is shutting down (e.g. SIGINT) — flush everything remaining
// and exit
case &lt;-ctx.Done():
    b.drain(&amp;buf)
    b.flush(buf)
    return

// new update arrived — add to buffer, flush if batch is full
case update := &lt;-b.updates:
    buf = append(buf, update)
    if len(buf) &gt;= b.batchSize {
        b.flush(buf)
        buf = buf[:0]
    }

// timer fired — flush whatever we have so data doesn't sit in memory
case &lt;-ticker.C:
    if len(buf) &gt; 0 {
        b.flush(buf)
        buf = buf[:0]
    }
}
...
</code></pre>
<p>I also added a mechanism so that when the main process gets killed, the batcher picks up the context cancellation, and before exiting, flushes all remaining data to the database.  </p>
<p>Here we know for certain that each server only writes about itself — one server, one connector, strictly sequential updates.<br />Each connector processes events in a simple loop — receive event, fetch tools, submit to batcher — so updates for a given server are always sequential by design.<br />The problem of different batches containing different data for the same server doesn't apply. We don't need timestamps to figure out which record is more recent — in BoltDB the last write in a batch overwrites the previous one, which is correct by design.</p>
<p>Ahhh, didn't get to squeeze in Lamport clocks for precise update ordering :D<br />Oh well, next time.</p>
<h3>Observer / Callback</h3>
<p>I also thought it would be nice to support adding servers on the fly, so their tools get monitored immediately — a kind of <strong>Observer/callback</strong> pattern.<br />When we add a new server while MCPSprut is already running, it should join the process right away.</p>
<p>I register a function in storage:</p>
<pre><code class="language-go">...
h.storage.OnNewServer(func(server storage.ServerConfig) {
    h.startConnector(ctx, server)
})
...
</code></pre>
<p>Storage holds this function. When someone calls <code>SaveServer</code>, storage invokes the callback with the new server after writing to the database.</p>
<p>Storage knows nothing about the hub, connectors, or goroutines. It just says <em>"I saved a server, here's your callback."</em><br />The hub decides what to do — start a connector.</p>
<p>Storage doesn't import hub, hub doesn't poll storage.<br />A new server appears — a connector starts automatically.</p>
<h3>Retry with Stability Window</h3>
<p>Connectors have a standard retry mechanism — three attempts, then give up.<br />Simple, no jitter or exponential backoff for now (maybe in a future version).</p>
<p>But here's the thing — our SSE streams live for hours or even days. Keeping a failure counter across that entire lifetime feels unfair.<br />Say a server glitches once, recovers, works perfectly for 24 hours, glitches again, recovers, works another week — and then one more hiccup and we mark it as dead.<br />Three failures total over days of stable work, and we just give up? That doesn't feel right.</p>
<p>So we added a <strong>"stability window"</strong> — if a connection lived longer than 30 seconds before dropping, we consider it was stable and reset the counter.<br />Three quick failures in a row? The server is probably down. A disconnect after a long stable session? Just a hiccup — start fresh.<br />I think that's fair.</p>
<pre><code class="language-go">...
// connector.go — retry loop with stability window
func (c *Connector) Run(ctx context.Context) {
    failures := 0
    for {
        start := time.Now()
        err := c.connect(ctx)
        if ctx.Err() != nil {
            return
        }

        if time.Since(start) &gt; stableConnectionThreshold {
            failures = 0 // connection was stable — reset
        }
        failures++
        if failures &gt; maxRetries {
            return
        }

        select {
        case &lt;-ctx.Done():
            return
        case &lt;-time.After(c.retryInterval):
        }
    }
}
...
</code></pre>
<h3>Shutdown Safety: WaitGroup + Mutex</h3>
<p>While building this, I noticed a subtle edge case with the Observer/callback pattern and shutdown.<br />During shutdown, the hub uses a <code>WaitGroup</code> to wait for all goroutines to finish. But if during this time the callback fires and calls <code>wg.Add(1)</code> — because a new server was added and we're starting a new connector — we have a problem. If shutdown has already started and <code>wg.Wait()</code> has been called to wait for all connectors to finish.<br />In Go, calling <code>wg.Add(1)</code> after <code>wg.Wait()</code> has returned on a zero counter always causes a panic — this is documented behavior.<br />It's not obvious at all — the callback logic looks perfectly clean, but the interaction with shutdown timing creates a hidden race.</p>
<p>The fix required both a <strong>mutex</strong> and a <strong>boolean flag</strong> — interestingly, neither one alone is enough:</p>
<ul>
<li><p><strong>A flag without a mutex?</strong> There's a gap between checking the flag and calling <code>wg.Add(1)</code> — another goroutine can slip in <code>wg.Wait()</code> right between them.</p>
</li>
<li><p><strong>A mutex without a flag?</strong> Once you unlock after <code>wg.Wait()</code>, the next callback goes right through and we're back to the same problem.</p>
</li>
</ul>
<p>So: <code>startConnector</code> locks the mutex, checks the shutdown flag, and only then calls <code>wg.Add(1)</code> — all under the same lock. <code>Wait()</code> locks the same mutex, sets the flag to true, unlocks, and then calls <code>wg.Wait()</code>. This guarantees that Add and the shutdown check are atomic — no panic.</p>
<pre><code class="language-go">...
// hub.go — callback that adds a new connector on the fly
func (h *Hub) startConnector(ctx context.Context, server storage.ServerConfig) {
    h.shutdownMu.Lock()
    if h.shutdown {
        h.shutdownMu.Unlock()
        return
    }
    h.wg.Add(1)
    h.shutdownMu.Unlock()
    go func() {
        defer h.wg.Done()
        ...
    }()
}
...
// hub.go — called from the goroutine
// that catches SIGINT and waits for all connectors
func (h *Hub) Wait() {
    h.shutdownMu.Lock()
    h.shutdown = true
    h.shutdownMu.Unlock()
    h.wg.Wait()
}
...
</code></pre>
<h3>Graceful Shutdown</h3>
<p>And now that we have this flag, let's look at the full graceful shutdown.<br />This one is satisfying — a single <code>cancel()</code> triggers a cascade through the entire stack:</p>
<ol>
<li><p><strong>SIGINT</strong> arrives — we cancel the root context</p>
</li>
<li><p>All connectors see <code>ctx.Done()</code>, their SSE streams close, goroutines exit</p>
</li>
<li><p>The hub sets the shutdown flag under a mutex — no new connectors can sneak in</p>
</li>
<li><p><code>wg.Wait()</code> waits for every goroutine to finish</p>
</li>
<li><p>The batcher sees <code>ctx.Done()</code> too, drains whatever is left in the channel, flushes it to the database</p>
</li>
<li><p>We wait for the batcher to complete, and finally close BoltDB</p>
</li>
</ol>
<p>The beautiful part is that no component knows about the others. The hub doesn't tell connectors to stop directly, the batcher doesn't know the hub exists.<br />Everything flows through <strong>context propagation</strong> — one cancel, and each layer cleans up after itself.</p>
<p>And if all of this takes too long? A 5-second timeout kicks in and we force-exit. Better to lose a few updates than hang forever.  </p>
<pre><code class="language-go">...
// main.go — the shutdown orchestrator
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
&lt;-sigCh

cancel() // triggers the entire cascade

done := make(chan struct{})
go func() { 
    h.Wait() // wait for all connectors
    bat.Wait() // wait for batcher to drain 
    close(done)
}()

select {
case &lt;-done:
    log.Println("Done")
case &lt;-time.After(5 * time.Second):
    log.Println("Shutdown timed out, forcing exit")
}
...
</code></pre>
<hr />
<h2>What's Next</h2>
<p>More logs and OpenTelemetry are absolutely essential.<br />Here I only added the basics — enough to see that it works and does what it was designed to do. But a deeper analysis plus profiling is needed.</p>
<p>Next I plan to dig deeper into the metrics and logs, study how MCPSprut and the simulator behave, find bottlenecks, and try to push the performance as far as possible.</p>
<p>We hit 10,000 active streams comfortably — but where does it actually break?<br />100K? 1M? 50M? Is it memory, CPU, or BoltDB that gives up first?</p>
<p>There's definitely room for improvement here, and the ways to optimize performance are genuinely interesting to implement. That's when we'll see what the real maximum is.</p>
]]></content:encoded></item></channel></rss>