<?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 Vadim Filin on Medium]]></title>
        <description><![CDATA[Stories by Vadim Filin on Medium]]></description>
        <link>https://medium.com/@filinvadim?source=rss-f1e01fe2ded0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2vYq55oRrB3GfiwuGGJCww.jpeg</url>
            <title>Stories by Vadim Filin on Medium</title>
            <link>https://medium.com/@filinvadim?source=rss-f1e01fe2ded0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:04:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@filinvadim/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[Warpnet: A Twitter With No Server.]]></title>
            <link>https://medium.com/@filinvadim/warpnet-a-twitter-with-no-server-c7f63ab757c5?source=rss-f1e01fe2ded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f63ab757c5</guid>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[censorship]]></category>
            <category><![CDATA[p2p]]></category>
            <dc:creator><![CDATA[Vadim Filin]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 13:34:53 GMT</pubDate>
            <atom:updated>2026-09-27T19:34:50.102Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Warpnet is a peer-to-peer social network on Go, where every user runs own node and this is the account of how it works, what two years of commits say about what I got wrong in my own project and what problems are still open.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKlz75s8gTv3P02jjEYZng.png" /></figure><p><a href="https://github.com/Warp-net/warpnet">https://github.com/Warp-net/warpnet</a></p><h3>1. The account that pays the rent</h3><p>I know people whose only income is the advertising revenue from one single account with large following. The platform can delete that account tomorrow, for a reason it will not explain, through a process nobody can appeal and the person will not be able to pay the rent next month. This is the situation of several people I know and it was exactly this which finally made me angry enough to begin.</p><p>The rest of the list is in general familiar - the permanent threat of ban, including the quiet kind when you continue to post and nobody sees you, the tracking of everything you do and the resale of this information to advertisers, the ownership of your personal data, including your phone number. A network earns the money from your content and you are the inventory.</p><p>In September 2024 I decided that I have sufficient skill to do something with this. I did not want an alternative to Twitter but a different model -the network where everything is on your own computer where you are your own administrator and where nobody can ban you or sell you, because there is simply nobody in position to do either of these things.</p><p>Two years later there is a network to show for that decision and this article is the account of it. Several things I believed about my own project turned out to be wrong and a few which I had described as finished did not exist yet.</p><p>The biggining of the project were me writing this thing by hand and getting it wrong, repeatedly. Whole subsystems were built, wired in, utilized and then deleted. More than one design was abandoned after months, not because something better appeared but because the one I had chosen could not hold. Thus most of what this article describes is the second or the third answer to a question which I answered badly at first and I will indicate these places when they come. This is honest shape of the work and it is the reason why my own account of the project was constantly running ahead of the project itself.</p><h3>2. Who is writing this</h3><p>I am <a href="https://www.linkedin.com/in/vadim-f-35b815164/">Vadim Filin</a>. I graduated from Saint Petersburg State University of Aerospace Instrumentation and my first field was the law. From there I moved into programming and then deep into distributed systems and crypto.</p><p>The order matters because it determines what this article argues about.</p><p>The law trains you to read a system through three questions which have nothing in common with how it runs - who holds the thing, who can take it away and what the other side is paid for. The engineering asks what happens, in what order, at what cost. I have kept both habits and thus I do not judge a network solely on the basis of whether its protocol works. A protocol can be flawless and at the same time be bolted to a company which needs you to be unable to leave and most of the interesting failures in this industry are exactly of this second kind.</p><p>This is why the chapters below spend as much time on the ownership and the incentives as on wire formats. When I compare Warpnet with Mastodon, Bluesky, Nostr and Farcaster - the question is not which handshake they utilize. It is who is in position to take something from you and what this will cost them.</p><p>The rest is ordinary: about seven years of professional work, mostly FinTech, mostly Go. Sole developer on some products, team lead on others. I like to go deep - from the protocol design down to storage layers and exactly this is what the building of this thing alone demanded.</p><p>I have used VKontakte, Instagram, YouTube and X and I observed how communities build themselves on systems which they do not control. What I took from this is more narrow than anger. The problem is the dependency itself - between you and the people who read you sits a party with its own balance sheet and all the rest follows from this one fact.</p><p>The design answer follows from it and it is deliberately not the federation. Of course federation exchanges one landlord for many and you still have one. If the position itself is the problem then in my opinion the honest fix is the deletion of this position and not its multiplication. This is why Warpnet removes the server instead of distributing it, why nobody owns the network and why I moved the licence from GPL to AGPLv3. AGPL closes the gap which allows somebody to run a modified, closed version as a service - and this is exactly how an open project is turned back into a platform.</p><p>Plainly then, because these are the facts against which all the rest of the article is to be weighed. I am the founder and, unfrtunately, the only maintainer. Nobody owns the network, including me - I write the code and I run three relays and neither of these makes me an administrator of anything or gives me a switch to flip. If I stop, the licence and the running nodes are what remains. This is the intended outcome and not a risk with which I have made peace.</p><h3>3. What “decentralized” actually means</h3><h3>3.1 Three questions which must be asked of any network</h3><p>Every social network answers three questions, no matter whether it says so or not — where does the data live, who can make you disappear and how the strangers find you. The word “decentralized” hides very different answers to all three.</p><p>Almost the whole internet works on the client-server model —<a href="http://x.com/"> x.com</a> is a central server, your app is a client which asks it for the permission to do everything and the server decides what every client is allowed to do. The alternative is a peer-to-peer (P2P) network, in which every participant is at the same time both a client and a server. There is no Big Brother, because there is no seat for him.</p><h3>3.2 Four shapes of the one word</h3><p>Client-server — one operator holds the accounts, the posts, the index and the rules. <strong>X</strong> is the pure case and <strong>Bluesky</strong> is one in the deployment, if not in the design. Federation - many servers, each one a small client-server world, speaking a shared protocol, the e-mail is the archetype and <strong>Mastodon</strong> is the social version. You can change the landlords but you always have one. Relay or hub networks - your identity is a key and not an account, thus the servers become interchangeable and your signed posts live on whichever relays you choose, <strong>Nostr</strong> and <strong>Farcaster</strong> are here and the soft centre moves from “the admin” to “the relays everybody happens to use”. True peer-to-peer - every participant stores and serves and the shared infrastructure is thin, mostly for the finding of each other, plus the relays which bounce the traffic for peers stuck behind <a href="https://en.wikipedia.org/wiki/NAT_traversal">NAT</a>, the translation on the router level, which hides home machines behind one public address and does not permit the strangers to dial them from outside: <strong>Secure Scuttlebutt</strong>, <strong>BitTorrent</strong>, <strong>Warpnet</strong>.</p><h3>3.3 The torrents, said precisely</h3><p>How I used to say it - the Russian “parliament” failed to stop the torrents, because <a href="http://rutracker.org/">rutracker.org</a> is not a server. Right in the spirit, imprecise in the details. In fact, rutracker never holds the film - it holds a hash and, historically, the address of a tracker - a phone book which tells your client which peers hold the pieces. The pieces travel from peer to peer and since 2005 BitTorrent has a distributed hash table(DHT)- a lookup table spread across all the peers, each one holding a slice with no owner so that every peer can act as a tracker. Kill the index site and kill the tracker and the swarm continues to work. Mapped onto the social networks: Mastodon is a federation of file-hosting sites, Nostr is a set of rented seedboxes, Bluesky is one hosting provider plus one enormous crawler. Secure Scuttlebutt and Warpnet are the swarm and Warpnet’s relays are the trackers with one additional job which a tracker never had - the bouncing of the traffic for peers that cannot be dialled directly.</p><h3>3.4 The one question</h3><p>The fair test is not “is it decentralized?” It is the following - if the most popular server in this network disappears tonight will your posts still exist? And will your followers be able to find you? Mastodon - only if the server which vanished was not yours and if it was yours, then no and no. Bluesky -yes in the theory, no in the practice. Nostr - yes, if you utilized more than one relay. Farcaster - only while your storage rent is paid and the validator set of Snapchain continues to carry your messages and, in distinction from the rest of this group, your identity is an on-chain registration for which you had to pay and not just a keypair. Secure Scuttlebutt and Warpnet - your posts survive, because they were never in some other place.</p><p>Now the cost side, because the true P2P pays for the missing server. The availability of your data depends on you or your replicators being online. The NAT traversal and the mobile battery are the problems which a server makes disappear. The discovery still needs the bootstrap nodes and there is no global search without an index and an index is a server. The moderation has no operator to whom one can appeal. Warpnet answers this with the moderator nodes which vote on each report, but the cost lands in any case - a verdict applies to the whole network and there is nobody whom you can ask to look again.</p><h3>4. A fair look at the neighbours</h3><p>Before writing the code I made some research about what existed already. My first pass at that survey was work of a person who had been angry for eight months and it reads exactly so. The README which I wrote later contains a rule I now prefer - a fair comparison, because the alternatives are good projects which make other tradeoffs different from mine. ActivityPub - since everything below leans on this word - is the protocol that Mastodon-style servers utilize in order to exchange posts, follows and likes and servers speaking it are the <strong>Fediverse</strong>.</p><h3>4.1 Mastodon</h3><p>My verdict about Mastodon was that its claim to be decentralized is a half-true that it is simply Twitter cut into small pieces and that admin of instance is king and god.</p><p>In general, “The admin is king” holds for one server, but not for the network. Your instance admin can suspend you or simply pull the plug; what the admin cannot do is to act on the whole platform and you can move your followers to another instance, although not your posts. Also I claimed that the hiding of accounts functions through centralized DNS or through list of public addresses. The first half - wrong, the second half is in fact the real mechanism, domain blocks, an application-level list in the admin’s database of hostnames of other servers which must be limited or suspended.</p><p>The stack - Ruby on Rails, the licence - AGPLv3-or-later and not the plain GPL, as I kept calling it. This licence is exactly the reason why Mastodon could not stop <strong>Gab</strong> or <strong>Truth Social</strong> from utilizing its code, only individual admins were able to block them and the majority of instances blocked Gab’s domains within few days after its July 2019 fork. Hence the irony which I must accept: the defederation tool I criticised is exactly that which isolated Gab.</p><h3>4.2 Bluesky / AT Protocol</h3><p>This is the one judgement which I got flatly wrong. I was convinced that Bluesky does not even claim the decentralization. In the reality it claims it very loudly: the protocol describes itself as open standards for decentralized publishing, an IETF working group (ATP) was chartered in early 2026 and announced in April of that year and the charter lies on the IETF datatracker.</p><p>The publishable version: decentralized on the paper, centralized in the deployment. According to the company’s own October 2025 count, 99.99% of users sit on Bluesky PBC infrastructure. Handles are ordinary DNS, the central piece is the did:plc identity directory, which is run by the company, with a handover to a Swiss association announced by the company in September 2025 and still being in formation instead of being in charge. A Personal Data Server, holding the repository of one user, is cheap for self-hosting. The expensive tiers consist of the relay, which collects that which every server publishes and the AppView, transforming this stream into timelines, search and counts. The only full-network AppView the company still operates itself. Blacksky operates an independent PDS, a relay and a moderation stack and, by its own announcement, an AppView which opened in public beta in July 2026 - but not one which indexes the whole network. DMs pass through one central service and they are not encrypted end to end.</p><h3>4.3 Nostr</h3><p>My summary of Nostr was that it stores your content on server that the server moderates that you cannot connect without one.</p><p>The first three hold, but with sharper wording. A relay cannot forge signed note - however, it can refuse to store it or to serve it and each relay moderates only that which it stores itself. “No relay, no connection” is true, but “a relay” means any of several hundred public relays, including five-dollar VPS which you run yourself and with the outbox model your reach does not depend on one relay: thus no single relay is able to isolate you from your followers. Nostr DMs were always encrypted (NIP-04), but they leaked who talked with whom and when, NIP-17 gift wrap now hides this, although the adoption is uneven.</p><h3>4.4 Farcaster</h3><p>I described Farcaster as semi-decentralized, built on Ethereum plus hubs, making sense only inside Ethereum and impossible for ordinary person to run.</p><p>In fact the hubs were already gone at the moment when I settled on this description and it is necessary to say this directly instead of correcting it silently. Snapchain replaced them in April 2025: the content lives on a chain kept in step by a small and permissioned set of validators (seven as of July 2026 per the Snapchain documentation, five of them run by Neynar); identity and storage rent are contracts on OP Mainnet which an ordinary user never touches. But a node requires server with 16 GB of RAM, four cores and one to two terabytes of disk (the README says 1 TB, the docs 2 TB) and to become a validator demands the agreement of the existing operators. In January 2026, according to the announcements of both companies themselves, the protocol and the dominant client were sold to Neynar. Thus the soft centre now has the name of a company on it.</p><h3>4.5 Secure Scuttlebutt</h3><p>I called <a href="https://medium.com/clebertech-en/the-definitive-guide-to-secure-scuttlebutt-a1b3a3fd73f6">SSB</a> genuinely decentralized and at the same time hobbled by the outdated technology, because it utilizes an append-only log instead of database.</p><p>SSB is the only other true peer-to-peer design here and the closest ancestor of that which Warpnet attempts. “Slow” is fair- the one-word verdict of LWN in its April 2026 piece was exactly this. But “outdated” I would replace with specifics: no deletion, one identity per device, two-hop reach, the successor protocol renamed to PZP and still not ready for end users, the flagship client Manyverse which is effectively unmaintained. And “uncensorable” means also “unamplifiable” - no message reaches the whole network.</p><h3>4.6 The table</h3><p>This comparison I took from the README, widened to six networks and with the moderation cell of Nostr corrected to “per relay + per client”. This information is accurate as of September 2026 and every figure in this section carries the date and the source from which it came -whether it is the project’s own post or documentation, the April 2026 piece of LWN about Secure Scuttlebutt, or the IETF datatracker entry for the ATP working group so that a reader, when he checks some number, can see for himself whether it has become stale since that moment.</p><blockquote><strong>Mastodon - </strong>Server required?: Yes (instance); Where your data lives: Instance admin’s database; Who can drop you: Instance admin; Discovery: Instance-scoped, federated fetch; Moderation: Per instance, human admins</blockquote><blockquote><strong>Bluesky-</strong>Server required?: Yes (PDS, relay, AppView); Where your data lives: Your PDS provider (99.99% the company); Who can drop you: Provider; company AppView; PLC directory; Discovery: Relay + AppView; Moderation: Company labelers, pluggable labelers</blockquote><blockquote><strong>Nostr</strong> -Server required?: Yes (at least one relay); Where your data lives: Relays you post to; Who can drop you: A relay can ban; nobody revokes your key; Discovery: Relay lists, NIP-05, web of trust; Moderation: Per relay + per client</blockquote><blockquote><strong>Farcaster</strong> -Server required?: Yes (Snapchain nodes); Where your data lives: Snapchain, pruned when rent lapses; Who can drop you: Validators decide inclusion; nobody deletes the FID; Discovery: Client and API; Moderation: Client operator</blockquote><blockquote><strong>SSB</strong> -Server required?: No (pubs and rooms optional); Where your data lives: Every replicating peer; Who can drop you: Nobody; Discovery: Friend-graph gossip, pubs, rooms; Moderation: Blocks along the friend graph</blockquote><blockquote><strong>Warpnet</strong> -Server required?: No (stateless relays); Where your data lives: Your node, plus followers’ copies; Who can drop you: No admin; a moderator quorum can shadow-ban content and a floored rating drops you from the DHT; Discovery: DHT, gossip, mDNS, relays; Moderation: Automatic moderator quorum, per-node blocks</blockquote><h3>5. What I wanted and how this was written</h3><h3>5.1 Six wants, thirteen principles</h3><p>I wanted six things: the full autonomy without servers, the local storage without clouds, no registration, anonymity by choice, cryptographic isolation and administration of the network without human participation. The line under which I still stand is that the privacy must be architectural, not declarative: a promise in policy is only promise; a design which has no place to put the data is a fact.</p><p>These wants hardened into thirteen General Principles of the network:</p><ol><li><em>Warpnet cannot be owned by anyone.</em></li><li><em>Warpnet must operate independently of any third-party services.</em></li><li><em>Warpnet must not rely on any proprietary or third-party technologies.</em></li><li><em>Warpnet node must be distributed as a single executable file.</em></li><li><em>Warpnet must be a cross-platform solution.</em></li><li><em>Only one Warpnet member node may run on a single machine, but it may have multiple aliases.</em></li><li><em>Warpnet member nodes must be governed solely by network consensus.</em></li><li><em>Warpnet business nodes may allow centralized management.</em></li><li><em>Warpnet business nodes must responsibly run at least one bootstrap node and one moderator node.</em></li><li><em>Warpnet node must store private data only on the local host machine.</em></li><li><em>Warpnet nodes network must not be developed or controlled by a single individual.</em></li><li><em>Content on WarpNet must be moderated automatically, without human intervention, moderator nodes must be protected from unauthorized modification.</em></li><li><em>Node owners bear full personal responsibility for any content they upload to Warpnet.</em></li></ol><p>Four of them hold this article: a node is a single executable file (4); a node stores private data only on the local machine (10); the content is moderated automatically, without human intervention (12); node owners bear full personal responsibility for that which they upload (13). The others the reality has contradicted. Principles 8 and 9 describe “business nodes”- for a network native market, not implemented. Principle 11 says that the network must not be developed by single individual, three quarters of the commits in this repository are mine. Principle 12 had the code early - the moderation branch was merged in July 2025. But fifteen months more were required in order to make it automatic and network-wide: only in August 2026 three moderators started to vote with signed verdicts.</p><h3>5.2 A disclaimer before the code</h3><p>One thing I want to say directly, because people ask about it. <strong>Warpnet is not vibecoded</strong>. The base of it was written by hands, by me. The Android app is heavily refactored fork of Tusky, a Mastodon client and its base is the work of Tusky. I utilize AI tools only for trivial boilerplate, in order to not burn out, while I am writing everything alone.</p><p>Of course the git log is also the check for this and it is less flattering than the disclaimer. Between March and August 2026, 557 commits, a bit more than a quarter of everything in this repository, carry AI attribution. The big part of this is boilerplate and refactoring. The architecture and the original implementation are mine. But some of the hardening lying on top of them was written with machine at the keyboard.<br>Archived prototype from Jan 2025: <a href="https://github.com/filinvadim/warpnet">https://github.com/filinvadim/warpnet</a></p><h3>6. The stack: one file</h3><h3>6.1 One binary is the product</h3><p>The stack I have described from the very beginning in the following manner: written in Go, frontend on Vue 3, all data in encrypted <a href="https://github.com/dgraph-io/badger">BadgerDB</a> on your disk, whole node is one executable without dependencies, no server and no app store behind it. In general this description still holds, with the caveat that the desktop build links the platform webview (libwebkit2gtk on Linux) and exactly for this reason the snap ships it. embedded.go embeds the version file, the icon and the committed frontend/dist (147 files) into the binary. <a href="https://wails.io/">Wails</a> is Go framework which wraps a web UI into native window - it renders the Vue bundle, thus the desktop application is simply the node with window on it.</p><p>The data lives in ~/.warpdata/&lt;network&gt;/storage/v0 (or %LOCALAPPDATA%\warpdata\&lt;network&gt;\storage\v0 on Windows). There are two networks with shipped bootstrap lists, testnet and warpnet, each one with its own database and its own version of your identity. Why one file? Because for the extraction of something from it neither app store, nor installer, nor server is necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbtN7Ze-v82cn_MReItsiA.png" /></figure><h3>6.2 Four roles from one option list</h3><p>The same codebase builds four kinds of node: <em>member</em> (the desktop app), <em>remote</em> (-tags remote, the same node headless, serving the same Vue bundle to a browser), <em>relay</em> (stateless, publicly reachable, self-updating), <em>moderator</em> (its own build tag, runs the moderation classifier locally and votes on reports). In general every one of them constructs its host from the same option list utilizing <a href="https://github.com/libp2p">libp2p</a> - the open networking toolkit which peer-to-peer projects share for transports, encryption and peer routing.</p><p>There is exactly one transport and exactly one security protocol, hence libp2p’s defaults (plain TCP, QUIC, WebSocket, WebTransport, TLS) are never added. The transport is TCP wrapped into camouflage layer, which a later section will take apart; TCP only, because WebRTC and QUIC do not support private networks yet. And every member with public address offers itself at the same time also as relay for the others.</p><p>One per-role option deserves explanation already now: the PSK, or pre-shared key- a secret which every libp2p connection must present before anything else happens. Warpnet’s PSK is sha256(network + major version) and the code states in so many words that it is public: its task consists in the separation of testnet from mainnet and of incompatible major versions, forcing the upgrade. A label, not a credential -and to this question the camouflage section will return later.</p><h3>7. Your password is your identity</h3><h3>7.1 The logging in is local operation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGIyOGwKHq-0NwfSQlh1XQ.png" /></figure><p>In the following manner I used to describe the logging in: no registration- on first launch you type a name and a password. The password is sent nowhere and is needed only in order to encrypt the local database - lose it and you lose the account. The middle sentence was not whole truth even then, today the password is central design fact of the system.</p><p>There is no account server, thus “logging in” is something which your node does to itself: it validates the password, unlocks Badger and derives the cryptographic identity of the node. On first run it mints a <a href="https://medium.com/@taycode/why-you-should-use-ulids-549aa8ca9454">ULID</a> (sortable 128-bit identifier generated locally) for your user id. Only then the libp2p node starts, deriving its peer ID from the public half of the key. The key is Ed25519 - a signature scheme whose 32-byte public key is small enough to be inlined into the peer ID itself, hence anyone who knows your peer ID knows also your public key and nobody ever fetches a key in order to verify your signature.</p><h3>7.2 One password, three secrets</h3><p>Every root secret is derived with Argon2id, a memory-hard key derivation function: one guess costs about 20 milliseconds and 64 MiB of RAM and this is what denies to an attacker the GPU speed-up which makes the brute force cheap. Three secrets are obtained from one password, separated by salts; the salt consists of a context string, the username and, for two of them, the network name:</p><pre><br>const (<br> identityKeyContext = &quot;warpnet/kdf/v1/identity-key&quot;<br> databaseKeyContext = &quot;warpnet/kdf/v1/database-key&quot;<br> walletSeedContext  = &quot;warpnet/kdf/v1/wallet-seed&quot;<br>)<br><br>func DeriveIdentityKey(username, password, network string) (ed25519.PrivateKey, error) {<br> if password == &quot;&quot; {<br>  return nil, ErrEmptyPassword<br> }<br> seed := deriveKey([]byte(password), derivationSalt(identityKeyContext, network, username))<br> defer Wipe(seed)<br><br> return GenerateKeyFromSeed(seed)<br>}<br><br>func DeriveDatabaseKey(username, password string) ([]byte, error) {<br> if password == &quot;&quot; {<br>  return nil, ErrEmptyPassword<br> }<br> return deriveKey([]byte(password), derivationSalt(databaseKeyContext, username)), nil<br>}<br><br>func DeriveWalletSeed(identityKey ed25519.PrivateKey, network, username string) []byte {<br> return deriveKey(identityKey, derivationSalt(walletSeedContext, network, username))<br>}<br><br>func derivationSalt(parts ...string) []byte {<br> return ConvertToSHA256([]byte(strings.Join(parts, &quot;\x00&quot;)))<br>}</pre><p>The identity key depends on the network, the database key does not. Thus the same credentials give you the same peer ID on any machine, on testnet a peer ID different from the one on warpnet and the same database key on both of them. The third secret is wallet seed, which obtains its own section further down.</p><p>The intent is: “no random - private key must be determined”. There is no server which holds your identity, hence it must be reproducible from something you know. In my opinion a key file would only move the single point of failure onto fragile artifact that can be lost or copied.</p><p>The consequences, stated plainly: recovery does not exist (yet). If you lose the password, you lose the data and the identity together; change it and you are already another person. A backup is copy of the storage folder plus the credentials in your head. One secret is not derived from the password - a session token of 32 random bytes minted once per launch and utilized only for the pairing of a phone.</p><h3>7.3 A wrong password is a decryption-key mismatch</h3><p>Actually a password check in the usual sense does not exist at all. Badger is opened with the derived key- if it does not decrypt the key registry, Badger returns ErrEncryptionKeyMismatch and the node translates this into &quot;wrong username or password&quot;. A wrong password is literally the impossibility to read the disk. No artificial logic, just cryptographic nature.</p><h3>7.4 How the data is laid out</h3><p>The keys follow a grammar /&lt;NAMESPACE&gt;/&lt;root&gt;/&lt;range&gt;/&lt;id&gt; and the sortable form embeds reversed timestamp -math.MaxInt64 minus the Unix milliseconds, zero-padded to 19 digits so that a forward scan returns the newest first. Not all information lives forever: notifications expire after 24 hours, undelivered outbound messages wait 7 days in the outbox, a paired phone is remembered for 72 hours (at most 10 devices), cached copies of the media of other people live 7 days and their tweets 30 days. Your own content the node keeps indefinitely.</p><h3>8. Challenge one of four: how to find each other</h3><p>Four hard problems I have named for myself already. The first of them was the discovery — how participants find each other in general. But at first it is necessary to describe the layer which lies beneath it.</p><h3>8.1 Noise instead of TLS and then TLS as a costume</h3><p>The decision I took and repeated to everybody who asked was such. Node-to-node traffic is encrypted with Noise protocol and TLS I rejected, because it depends on certificate authorities - imagine that a CA revokes a certificate and the whole network goes dark (Russia switched to their own certificates for example). Noise is the encrypted, authenticated handshake between two raw public keys, without certificates and without anybody who is able to revoke something.</p><p>And here is the twist: every node-to-node connection is wrapped into real <a href="https://github.com/Warp-net/libp2p-camouflage-transport">TLS tunnel which looks like a browser talking to a website</a>.</p><p>The reason for this reversal is not cryptographic, it is political. <a href="https://en.wikipedia.org/wiki/Internet_censorship_in_Russia">In Russia</a>, in Iran and in a number of other countries the blocking happens already not on the level of addresses but on the level of protocols. The equipment of the provider examines the shape of the connection - the first bytes, the timings, the size of the packets - and drops what it does not recognise, or what it recognises too well. This is why VPN protocols, Tor and in general anything with an unusual handshake are the first targets there: nobody needs to know what is inside, it is sufficient to see that the traffic is not ordinary. And for a network like mine such detection is equivalent to a switch-off. The removal of the server saves you from the seizure of the server, but it saves you from nothing when your packets announce themselves on every hop between you and your peer. Hence the costume: the most boring thing which exists on the network today is a browser opening HTTPS to some large site and this is exactly what Warpnet tries to look like.</p><p>But this tunnel is only a disguise. The client skips the certificate verification, the server presents self-issued chain and the Noise handshake inside remains the only thing which authenticates anybody; the PSK decides only to which network and to which major version you are allowed to speak. Thus the certificate-authority argument survives, my flat “no TLS”- does not. How well this costume holds on a real censored network is a separate question and I answer it without flattering myself in 8.5.</p><h3>8.2 Four sources, one queue</h3><p><a href="https://en.wikipedia.org/wiki/Gossip_protocol">Gossip</a> is the pattern when peers repeat what they heard to some few neighbours until everybody knows, libp2p’s gossipsub does this over the named topics. mDNS is <a href="https://en.wikipedia.org/wiki/Multicast_DNS">multicast DNS</a> -it shouts in local network in order to find peers in the same house.</p><p>The discovery consists of four named sources which feed one queue: stream, gossip, mdns and dht. In the code gossip is annotated as a second source after DHT: every node publishes own addresses plus up to ten connected peers on /warpnet/discovery/1.0.0 every five minutes. The fourth source is reciprocal - whoever asks your node about its info gets enqueued in return. Therefore I expected that the heart of the discovery would be the DHT. In the reality it turned out different from my expectation: gossip plus relays which seed everything and the DHT remains one of four sources, not the engine.</p><h3>8.3 Relays</h3><p>Relays are stateless: peerstore in memory, one served route, no user content, dumb AF. They are pinned on maximum connection priority and they are the only candidates which the autorelay logic will use. Being started with enabled self-update they poll GitHub releases every hour and replace own binary. Only PSK keeps testnet and mainnet separate.</p><p>A relay serves circuit v2 only after AutoNAT reports public reachability and until then peers reject it as “doesn’t speak circuit v2”. This node is deployed on a static public address by definition, so state that instead of waiting to be probed -NATed peers need therelay before they can help confirm it.</p><h3>8.4 NAT: the failure you cannot see</h3><p>For a network where every user is server, NAT is the central engineering problem. Warpnet utilizes the libp2p toolkit: AutoNAT v2 in order to learn whether you are reachable, hole punching (DCUtR, where two NATed peers dial each other at the same moment through the coordination of a relay), circuit relay v2 as a fallback and UPnP in order to ask the router about port. Dedicated tracers log every hole-punch attempt because, as the comment in that file says, a node which never punches continues to work -simply permanently through a relay. Hence NAT traversal is the single subsystem whose failures are invisible from outside.</p><h3>8.5 Camouflage, honestly rated 5 out of 10</h3><p>DPI is a <a href="https://en.wikipedia.org/wiki/Deep_packet_inspection">deep packet inspection</a>: network equipment which classifies the traffic by its shape and not by its address. The thesis “no server to block” holds only in the case when the traffic also cannot be fingerprinted and blocked. The traffic of Warpnet I have described as looking like Chrome’s HTTPS and rated this protection five out of ten. As for me, I stand by the five.</p><p>What is shipped since the transport became the default: the dialer utilizes uTLS with a Chrome ClientHello fingerprint and a fixed SNI (the destination hostname which a TLS client sends in the clear) of www.googleapis.com; the listener presents self-issued certificate chain named after Cloudflare with deadlines and an accept queue against the active probing. The fragmentation is more modest than I made it sound — one TCP split in the middle of the SNI string and with zero delay, as it is shipped. Is it in general possible to name such a thing a fragmentation? Moreover, an attentive censor is able to notice a Google SNI outside, a Cloudflare certificate inside and a certificate which no real TLS client would accept. Thus, in my opinion, five out of ten defeats the cheap filters, but not the expensive ones.</p><h3>9. The wire: one handler, many doors</h3><h3>9.1 Routes are the protocol IDs</h3><p>Warpnet has no HTTP API at all. Every operation is a libp2p stream — your own UI which clicks “post”, a paired phone, a node of some stranger which asks for your tweets. The stream is opened on protocol ID which doubles as the route string: /&lt;private|public&gt;/&lt;get|post|delete&gt;/&lt;entity&gt;/0.0.0. There are 95 of them now. One JSON envelope travels per stream and it consists of body, message id, node ID, path, timestamp, version, signature; then the sender half-closes the stream and the end-of-file plays role of frame delimiter.</p><h3>9.2 What the signature covers and how it has grown</h3><p>In the absence of any trusted server the message itself must prove who has sent it. Therefore every envelope carries Ed25519 signature and the hardening of this subsystem is in fact the whole story of what exactly this signature covers.</p><pre>// SigningBytes returns the bytes an ed25519 signature covers: the raw body, the<br>// timestamp as decimal Unix nanoseconds, then the destination route. Senders<br>// must set Timestamp and Destination first.<br>func (m Message) SigningBytes() []byte {<br>    ts := strconv.FormatInt(m.Timestamp.UnixNano(), 10)<br>    buf := make([]byte, 0, len(m.Body)+len(ts)+len(m.Destination))<br>    buf = append(buf, m.Body...)<br>    buf = append(buf, ts...)<br>    buf = append(buf, m.Destination...)<br>    return buf<br>}</pre><p>The verification does not need any key exchange, because peer ID is an inlined Ed25519 public key: the verifier extracts the key from the ID of the one who has opened the stream and thus claiming of another node’s ID only invalidates the message. The price of “no version negotiation” is visible exactly here - the commit that added the destination split the network across itself.</p><h3>9.3 Middleware and why the UI is treated as a stranger</h3><p>Every handler sits behind the same chain: Logging, RateLimiter, Auth, Idempotency. The rate limiter works before the authentication on purpose, so that a flood is dropped before anybody spends CPU for verification of signatures. It keeps leaky bucket per route and per peer and the size of this bucket depends on the rating of the peer, but never goes below one call: slowed down, never starved. The auth middleware, in its turn, enforces the public/private split: private routes are allowed only for node itself, for the pairing route or for a paired phone.</p><p>And now - the trick which makes “one canonical handler per route” a truth and not a slogan. The desktop UI does not call any local API. It builds the same envelope a peer would send, signs it by the key of the owner and calls SelfStream, which executes the same middleware-wrapped handler over in-process pipe. The browser dashboard does the same over WebSocket and the phone - over the real libp2p stream. Thus, three transports, one handler:</p><pre>                    ┌──────────────────────────────────────┐<br>                    │  the node (Go)                       │<br>                    │  core/handler/&lt;feature&gt;.go           │   one canonical handler per route<br>                    │  database/&lt;feature&gt;-repo.go          │<br>                    └──────────────────▲───────────────────┘<br>                                       │  same {path, body, signature} envelope<br>        ┌──────────────────────────────┼──────────────────────────────┐<br>        │                              │                              │<br> in-process Wails call          Noise XX WebSocket            libp2p stream over Noise<br> (no network boundary)          (network boundary)            (network boundary)<br>        │                              │                              │<br>  Vue desktop app               Vue browser dashboard           Android app (Tusky fork)<br>  on the member node            on the remote node              via gomobile AAR</pre><p>On the picture in the contributor guide the middle arrow is labelled “AES-256-GCM WebSocket”. This is stale already and the paragraph about the clients below says what has replaced it.</p><h3>9.4 Timelines: one gossipsub topic per person and the follow gate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*jTLimyI2qLodYUzcPPsnbA.png" /></figure><p>Each user has gossipsub topic with the name user-update-&lt;userId&gt;. The act of following subscribes your node to this topic; composing of a tweet publishes into your own one; the subscribers verify that the known node ID of the claimed author is equal to the signer and only then the tweet is added to their home timeline.</p><p>Such gate, which makes all of this safe, during first twenty months simply did not exist. Replies and here it is worth noting, do not travel by the gossip - in this case the mechanism is different from the tweets. A reply is forwarded to the node of the parent author which holds the whole thread.</p><h3>9.5 DMs and the outbox</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mgow5bkWKu2VA1HR2RMPMg.png" /></figure><p>Direct messages are two public routes: one creates chat on both nodes, another one delivers a message capped at 5,000 runes. If the other node is offline, the message enters a 7-day outbox and will be flushed when the peer reconnects.</p><p>About the encryption here I want to be exact, because in the release notes the information was not exact at all. The confidentiality in transit is Noise session between two nodes and at rest it is the Badger’s encryption on each side; on the message layer, however, there is no encryption at all. The banner in the conversation window says “end-to-end encrypted and stored only on your device and theirs”. This is stronger than what the code really does, because “the two ends” means here two nodes and not two people. But it’s same considering p2p architecture of the Warpnet. Delivery receipts do not exist yet.</p><h3>9.6 Three clients, one sentence for each</h3><p>The desktop client is the Vue bundle inside a Wails window. The remote node serves the same bundle over HTTP and at the same time carries every request on one WebSocket, protected by Noise XX handshake with the key of the node, which the browser pins on the first connect. The Android client is a thin node which is not a node - later sections explain this in detail.</p><h3>10. Challenges two to four and the fifth one I did not list</h3><p>The discovery was the first of these four and the section above was its answer. For each remaining challenge I therefore give the same three things: what I promised to myself, what was shipped and what the code admits.</p><h3>10.1 Challenge two: the consensus that died and became counters</h3><p>The second challenge which I wrote down for myself was the agreement without humans and the first answer that came into my head was the consensus - the family of algorithms (Raft, Paxos and their byzantine relatives) which forces a set of machines to agree on one ordered log of events. During the first year this stood in the code. Today it does not stand there and the reason deserves its own explanation, because it is at the same time the reason why a large social network cannot be built on such algorithms at all.</p><p>The consensus buys you exactly one thing: everybody agrees about the same order of the same events. And it takes the payment in four currencies, none of which a social network is able to pay.</p><p>The leader. Raft and Paxos commit a write through one elected leader which replicates it to the majority. Hence the throughput of the whole cluster is the throughput of one machine - and this machine is precisely that server which I had removed. To put a leader back only in order to count the hearts would be a joke.</p><p>The round trip. A commit is not finished until the majority has confirmed it. Between home machines in different countries this is hundreds of milliseconds in the best case. But a reaction must appear instantly and the view counter of a popular post is incremented by everybody who scrolls past it. The interactions of a social network are the small and frequent writes and this is the worst possible load for an algorithm whose unit of work is a round trip to the half of the planet.</p><p>The membership. These algorithms demand a known and stable set of participants. A social network is the exact opposite: laptops are closed, phones fall asleep, people join and leave every minute. The consensus above such a set means the permanent reconfiguration and a quorum which is assembled rarely. When the half of the participants sleeps, such network does not become slower - it stops.</p><p>The identity. Between the strangers you need not the ordinary consensus but the byzantine one, which tolerates f liars only among 3f+1 participants and costs a quadratic number of messages per decision. Both of these numbers assume that the identity is scarce. In Warpnet the identity is free, thus somebody mints ten thousand of them and owns the quorum. The blockchains solve this by making the identity expensive -through the work or through the stake - and I wanted neither the first nor the second.</p><p>And there exists the fifth argument, the most simple one: the consensus answers a question which a social network almost never asks. Two people in different countries react to two unrelated posts - in which order did this happen? Nobody needs this answer and nothing depends on it. The single place where I really need several machines to agree about one outcome is the moderation verdict - and there the quorum is three, the window is 30 seconds and the subject is one report. Such a vote the network can afford, because it happens rarely and concerns one object.</p><p>What my own consensus guarded in the reality was the uniqueness of the user id and this problem I had invented for myself. The id is a ULID and it carries eighty random bits. A collision there is not the thing which one can usefully engineer and a stolen id proves nothing without the key derived from the credentials behind it. Thus the deletion of the whole subsystem removed a gate that was guarding nothing and nobody noticed the loss.</p><p>Actually, what really needed the convergence was numbers, because there exists no central tally which could be authoritative about how many reactions a tweet has. The instrument here is a <a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type">CRDT</a>, a conflict-free replicated data type: a data structure where any two copies can be merged in any order, without coordination and reach the same result. Engagement counters of Warpnet (reactions, retweets, replies, views, poll votes) are PN-counters, positive-negative counters, replicated over the gossipsub topic /warpnet/stats/1.0.0.</p><p>The realisation of this design took three tries in one day. There is no shared cell to increment: every process owns its own key /STATS/{incr|decr}/{dataKey}/{nodeID}/{generation} and writes there its running total; a read sums every key under prefix. The generation is a 128-bit random nonce minted on each process start, so that two lifetimes of one node never share a sub-counter.</p><p>Two things which I was saying about this need a correction. I called it “CRDT consensus”. It is not a consensus- nobody agrees about anything. It is coordination-free convergence and the only real consensus in Warpnet is the moderation vote. Also I said that the counters would be needed for analytics - no such code exists.</p><h3>10.2 Challenge three: people and the sealed envelope in every photo</h3><p>The third challenge, in that single word which I had written down for it, was people. I did not want the child pornography in a network which nobody can switch off and people are the weak link of any network. Hence every media file carries an encrypted metadata about who uploaded it, tuned in such way that an ordinary person cannot read it, while the police, having a couple of weeks of compute, can.</p><p>Today every image and video entering Warpnet leaves the node of the uploader carrying a sealed blob. The blob contains the full NodeInfo of the node (peer ID, paired-phone aliases, every address the node knows for itself), the full user record and the hardware address of every network interface. It is sealed with a random salt, Argon2id on the same 64 MiB cost as the identity key and AES-256-GCM. The password is drawn randomly from 110,000,000,000 values, about 2^36.7, utilised once for the whole upload and then wiped. The repository ships no tool for searching this password space: decryption routine exists in security/aes.go, but it is unexported and reachable only from its own tests.</p><pre>const (   <br>    // weakPasswordSpace bounds the single-use password. It is deliberately<br>    // small: the media-metadata scheme relies on brute force being possible<br>    // but expensive. A guess costs ~19-22 ms here, putting the expected<br>    // search near 12 days on a 1000-core cluster and ~5 years on an<br>    // eight-core laptop. Both figures track per-core speed, so treat them as<br>    // an order of magnitude rather than a promise.<br>    //<br>    // Tune the cost here, not in argonMemory: dropping the memory parameter<br>    // would hand the attacker back the GPU speed-up it exists to deny.<br>    weakPasswordSpace = 110_000_000_000 // ~2^36.7<br>    // weakPasswordSize is the fixed big-endian width the bounded password is<br>    // encoded to before it reaches the KDF.<br>    weakPasswordSize = 8<br>    // Argon2id cost. Memory dominates: 64 MiB per guess is what denies an<br>    // attacker the GPU/ASIC speed-up that makes a 2^40 search cheap.<br>    argonTime    = 1<br>    argonMemory  = 64 * 1024<br>    argonThreads = 4<br>)<br>// NewWeakPassword draws a single-use password from the bounded space above:<br>// small enough that brute force stays possible, expensive enough that it costs<br>// a data centre. Wipe returns the bytes to zero once they have been used.<br>func NewWeakPassword() ([]byte, error) {<br> n, err := rand.Int(rand.Reader, big.NewInt(weakPasswordSpace))<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;failed to generate weak password: %w&quot;, err)<br> }<br><br> password := make([]byte, weakPasswordSize)<br> binary.BigEndian.PutUint64(password, n.Uint64())<br> return password, nil<br>}</pre><p>On my own machine I measured 22.7 milliseconds per guess — the slow end of the range from that comment. Everything here depends on the speed of one core and therefore this puts the expected search nearer to fourteen days on a thousand cores than to twelve.</p><p>The blob is also signed by the node over the hash of the file, with the node and owner ids kept out of the file, so that a leaked copy reveals nothing additional. The reason is written in the commit: before this the metadata proved nothing. Its format is public and its password is nobody’s, hence anyone could seal a blob naming there an innocent user and attach it to their own content and nothing on the receiving side ever looked at it. Now a node fetching a foreign image verifies the signature against the node ID of the serving user and refuses unattributable media. Exempt from this is only the media bridged in from Fediverse, because its attribution is the source URL by which the gateway keys it. At the same time images are re-encoded to JPEG, which discards the original EXIF of the camera that made the photo including GPS; videos keep their own metadata.</p><h3>10.3 Challenge four: moderation without humans</h3><p>The moderation was still only planned and I was certain about its shape: automatic, without humans and not hard. It took fifteen months and three redesigns. Made the moderation report-driven: nothing scans and the only trigger is a user who presses Report. The chosen model was a one-billion-parameter open-weights safety classifier trained exactly for this and a verdict dropped to about two seconds. Also there’re a quorum of moderators, signed verdicts and mutual audits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*W9vW9JxHcjBXS1g-VGgZ4w.png" /></figure><p>You press Report on a tweet or on a profile (replies and images are not reportable yet; DMs never). Your node stamps the report with your id and with its own and publishes it on /warpnet/reports/1.0.0. Who will judge is decided without single message: each moderator computes sha256(reportID, moderatorID) and this ranks every moderator in an order unpredictable before the report exists, so that nobody can arrange to review the post of a friend. About three of them vote at once, each one estimating its own place from the same hash and from the moderators which it has seen lately; everybody else waits eight seconds per estimated rank and withdraws if three ballots already exist. Each voter fetches the content from the own node of the target and runs the model locally, blind to the others. The window is 30 seconds - an even count is trimmed to odd by dropping the highest-ranked ballot? FAIL needs a strict majority and a tie favours the content.</p><p>The lowest-ranked voter is the chair and announces the verdict; when he stays silent for ten seconds, the next in the line takes over. The verdict is Ed25519-signed by the chair and a member node verifies it against the public key inside the peer ID of the chair before it touches anything, because otherwise anyone could shadow-ban arbitrary users with a forged verdict.</p><p>Enforcement is an isolation, not a deletion, because Warpnet cannot reach into your computer and erase a file. A FAIL verdict is published on the own followers topic of the offender. The node of the offender never subscribes to its own topic, thus it never hears the verdict; its followers do hear it and their clients hide the content. Someone who knows that he was caught reposts with a different wording-someone who does not know keeps shouting into a room which has quietly emptied. The reporter hears back on both outcomes.</p><p>Moderators also spot-check each other with challenges drawn from the texts on which the network already ruled and keep a ledger of agreement. The ledger records standing but never refuses anything, because single auditor able to disqualify honest moderators would be a worse attack than the one against which we defend.</p><p>On a private test network from one member and three moderators, a post containing a direct threat was hidden about 30 seconds after the report and a killed chair was replaced by the next in line about ten seconds later. With zero moderators online the report was accepted and nothing happened. In one test the model flagged a profile which contained nothing objectionable. The majority requirement exists in order to make a mistake need several machines, not in order to make mistakes impossible.</p><p>What the code admits. The identity costs nothing, hence a patient attacker with several machines and several moderator keys is the unsolved problem. I have rejected pinned allowlists, bootstrap-issued credentials and proof-of-work, because each one of them puts somebody back in the middle. There are no appeals.</p><p>And at the moment of writing the three testnet moderator containers are taking up to 2 GiB of memory each.</p><h3>10.4 The fifth challenge: the reputation, when identity is free</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*lbC3FK_kYIzZglNRVdTEhA.png" /></figure><p>The challenge which I did not list among those four is the one under all the others: if anyone can mint an identity for free, how does the network remember a bad behaviour? The answer is ratings. Neighbours rate a node, never the node itself; a record which names its own author is rejected on validation, not by convention. The rating consists of three dimensions: network, application and moderation behaviour. Everybody starts from 1,000, because identity is free and a probation would only punish honest newcomers, while a patient attacker will simply wait it out.</p><p>Observations fold into hourly buckets, signed by the observer and replicated on their own CRDT topic so that relays and moderators, which have no disk, survive a restart. Penalties decay with a half-life of 12 hours on the network dimension and of 7 days on the others. The own evidence of a node counts uncapped; remote evidence is capped at 150 per observer and 400 in total so that the slander alone can never push anybody below 600. Tiers are trusted at 800 and above, watched at 500, degraded at 200, floor below that and each one maps to a rate-limit multiplier (1, 0.5, 0.25, 0.1, floored at one call), a connection-manager tag and a gossipsub score. A low rating slows a node but never blocks it- the exceptions are that a floor-tier peer leaves the DHT routing table and drops below the graylist threshold of gossipsub.</p><h3>11. The bridge to the networks I criticised</h3><h3>11.1 The node does not know that ActivityPub exists</h3><p>Warpnet bridges into Mastodon and into Threads. The decision which made this so cheap is in fact simple: node knows nothing about any of it. The node-side package consists of 110 lines. It marks bridged users with a foreign network name and seeds two entry accounts whose home node is the peer ID of the ActivityPub gateway, hence every already existing path for a remote user continues to work without any change at all, because it streams to the home node of user, which happens to be the gateway.</p><p>The gateway is a stateless sister repository which joins the private network as ordinary peer. Its peer ID is a per-node setting, therefore you can run your own. It holds no Warpnet state on which some node would depend, because a bridge caching the social graph would become a mini-instance — exactly the soft centre which Warpnet rejects.</p><h3>11.2 A budget, not a bypass</h3><p>Every rate limit in the node is calculated for the client of one person, whereas the gateway is one peer ID which carries the whole Fediverse. Therefore it receives its own tier (600 burst and 6,000 per minute) instead of an exemption, because peer ID is settable and thus must not buy one. For the same reason the relay circuits grew to 1 GiB and one hour: gateway forces private reachability, hence every node reaches it through a relay.</p><h3>11.3 The merging of all timelines</h3><p>The interleaved Warpnet-plus-Mastodon-plus-Threads timeline which you see in the release notes is realised entirely on the client side: a K-way merge in the Vue app with one source per followed handle and a cursor for each source. Timeline handler of the node contains no bridged logic at all. Threads required a seeded entry account, because it serves no account search and no browsable follow graph. Replies to Threads posts are refused in the client, because Threads shows Fediverse replies only under the posts whose author opted in and nothing on the wire says which posts these are.</p><h3>11.4 The warning banner is my own critique, verbatim</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*Wl_KIbbLanKpscosmRDHvA.png" /></figure><p>Open a bridged profile and a yellow banner tells you that you are leaving the trusted zone: the information of this profile lives on its own server, passes through the gateway in the plain text and is moderated by human administrators. This is my own case against Mastodon, turned into an element of the interface, minus the adjectives. In June the bridge was read-only, now it is two-way for follows, replies and reactions. DMs to bridged accounts are refused and the “read-only” on the website is simply stale.</p><h3>12. What Warpnet does today</h3><p>Instead of a walk through the commit log, here is the software as it stands. The conditions I have marked honestly, because several things work only in one client, only on the local machine or only in the test network. The next chapter lists what is weak or missing completely.</p><h3>12.1 Account and identity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*qFHsgSRVmO7xc7Bwu78iRg.png" /></figure><p>On the first run you choose a username and a password. There is no registration, no e-mail, no phone number and no server which holds an account for you. The password unlocks your local database and regenerates your signing key, thus the same credentials reproduce the same identity on any machine and different password is simply different person. Recovery does not exist - if you lose it, the data and the identity go together.</p><h3>12.2 Posting and reading</h3><p>You can post, reply, edit, delete and pin, within 280 characters. A quote is a normal post with pointer to the quoted one; a plain retweet carries the source id with an RT: prefix. Your home timeline is assembled from the people whom you follow, each of whom publishes into his own topic and the replies are obtained from the node of the person who wrote the root post, thus a conversation arrives whole and not in fragments.</p><p>Likes are gone. You react with an emoji through a picker with categories and you can see who reacted and how. Only the total count travels through the network, while at the same time the breakdown per emoji lives on the node of the author and reactions which were recorded before this change read back as a heart. Polls take from two to four options and an obligatory expiry, the node of the author enforces both and the tally stays hidden until you vote or the poll closes. View counts are recorded.</p><h3>12.3 Media</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*Ug5zaNq3WvF5D6h8GRntfw.png" /></figure><p>Posts carry up to four images or one video of up to 36 MiB and on the video preview you see a frame from the file itself. Direct messages on the desktop carry media too. Incoming images are re-encoded — this re-encoding discards the original metadata of camera, including GPS and every file leaves your node carrying a sealed blob which identifies the uploader, as was already described earlier in this article. Media of other people is cached for a week.</p><h3>12.4 Direct messages</h3><p>Chats show a preview of the last message and unread markers and they are sorted by recency. A conversation opens immediately, even when the other person is offline. If the person is offline, the message waits in an outbox up to seven days and is delivered when he reconnects. Delivery receipts do not exist. The protection here is the encrypted session between two nodes plus the encryption at rest on each side and not message-layer end-to-end encryption - such thing the network does not have.</p><h3>12.5 The social graph and the controls above it</h3><p>Follow and unfollow, see the followers and the following and receive the recommendations whom to follow. Follow requests have routes, storage and a page in the interface, but the flag which would make an account private is never read, thus the gate at the moment does not do anything.</p><p>Blocks, mutes and keyword filters are yours and local. A block escalates also into a permanent entry in the peer blocklist, although this list is consulted only when your node chooses whom to discover, hence it does not refuse an incoming connection. Keyword filters are stored by the node but applied in the client and only the kind which hides a post from your home feed. Bookmarks are simply a local list.</p><h3>12.6 Notifications, search, profiles</h3><p>Notifications cover mentions, follows, follow requests and reactions. They are cleared when you open them and they can be also sent to you by e-mail. There is a notification when the network discovers a new user. You can search for people and profiles have working Media and “Tweets and threads” tabs which load lazily, thus the profile of somebody else opens quickly.</p><h3>12.7 The Fediverse and the money</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*seQhnnxQZ0oSJQjqbwwvGw.png" /></figure><p>Mastodon and Threads accounts are visible, followable and readable from inside Warpnet through the ActivityPub gateway, interleaved with Warpnet posts in one timeline, with the recommendations divided by source. Bridged profiles carry a dismissible warning that their content lives on the server of somebody else and is moderated by the administrators of that server. Follows, replies and reactions travel in both directions. Direct messages to bridged accounts are refused and replies to Threads posts are refused in the client, for the reason given already earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*O7kB2pv2RFRamYt6Irr4-g.png" /></figure><p>The wallet is test network only. It sits on the Nile network of TRON, holds USDT and TRX, derives its seed from your identity key instead of storing a spend key and finds contacts by asking the people whom you follow for their derived address. A fresh address cannot send anything until it holds some TRX, because the fees are paid in TRX.</p><h3>12.8 Reporting, moderation and ratings</h3><p>You can report a post or a profile from the desktop and write the reason with your own words; from the phone only profiles can be reported. Replies and images are not reportable and direct messages are never moderated at all. The report goes to the moderator nodes, approximately three of which judge it independently and vote and in both cases you receive an answer. Nothing is deleted. The content which fails is hidden from the people who would otherwise see it. All of this depends on the moderators being online and at the moment of writing the moderator machines of the test network are switched off.</p><p>Separately the nodes rate each other by network, application and moderation behaviour. A poor rating slows down the requests of a node and lowers its standing in peer selection, but never blocks it completely.</p><h3>12.9 How to get your Twitter archive inside</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*XIlTxZxg6eoTfIZOD67hdQ.png" /></figure><p>An import of a Twitter archive is possible. The client unpacks it, retains your original posts with up to four photos in each and streams them to your node one by one, where the photos are treated like any other upload.</p><h3>12.10 Clients</h3><p>There exist three ways to reach a node and all of them speak the same protocol to the same handlers.</p><p><strong>What it is</strong> — Desktop app: the node itself, with a window; Browser dashboard: the same interface, served by a headless node; Phone: a thin client paired to your node</p><p><strong>Reading and posting</strong> — Desktop app: yes; Browser dashboard: yes; Phone: yes</p><p><strong>Direct messages, reactions, bookmarks</strong> — Desktop app: yes; Browser dashboard: yes; Phone: yes</p><p><strong>Reporting</strong> — Desktop app: posts and profiles; Browser dashboard: posts and profiles; Phone: profiles only</p><p><strong>Pairing a phone</strong> — Desktop app: shows the code; Browser dashboard: no; Phone: scans the code</p><p><strong>Deep links to profiles</strong> — Desktop app: yes; Browser dashboard: no; Phone: no</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5HTqxvjDfSgicZRz_5C6w.png" /></figure><p>The phone is not a node in the sense in which the desktop is one. It runs a deliberately small networking stack with no listening address and a tight memory budget and it acts as an alias of the account which lives on your desktop node: you pair it once, scanning a code and after this it can speak on behalf of that account as long as the pairing lasts. A node remembers at maximum ten paired devices. Notifications on the phone come from the polling of your own node, because there is no push service in the middle.</p><p>To be an alias and not a full node means also that the phone stays behind the desktop in the ways which are worth naming. It has no wallet, cannot import a Twitter archive, does not show the node ratings and cannot edit your profile, thus the setting which would make an account private can be changed only from the desktop. Search of posts from the phone returns nothing -only the search of people works there. Several controls, inherited from the client from which it was forked, are still drawn but do not reach the network yet, including post visibility, content warnings and saved drafts. In my opinion, it is better to write this down than to let you discover it by tapping.</p><h3>12.11 Platforms and networks</h3><p>There are builds for Linux on both Intel and ARM, for macOS and for Windows, plus an Android package and a relay binary. On Linux there is also a package in the beta channel of the Snap Store. The Android build is packaged for F-Droid and waits for the review <a href="https://gitlab.com/fdroid/fdroiddata/-/merge_requests/42627">there</a>, thus for now the file in the releases is the only one.</p><p>The same binary plays several roles, depending on how it is built: the full node, which most people run, a headless one which serves its interface to a browser, a stateless relay which helps new nodes to find peers, a moderator running the safety classifier and a test bot. There exist two separate networks, a main one and a test one, each with its own relays, its own database and its own version of your identity, thus nothing that you do in the test network follows you into the main one.</p><h3>13. What it does not do and where it is weak</h3><p>Grouped by the layers. Dry, without any defence.</p><p>Identity.</p><ul><li>No recovery of password by the design.</li><li>The salt is deterministic — a hash of fixed context string and of your username, where the identity key adds the network — thus a stolen database can be attacked offline at about 20 milliseconds per guess. The strength of password is everything.</li><li>The private key lies on the disk inside the encrypted database, through libp2p’s peerstore. Nothing cleans it from the memory on logout and on Windows there is no anti-debugging at all.</li></ul><p>Network.</p><ul><li>The blocklist filters only the outbound discovery. No connection gater is registered, hence a blocked node can still dial you. The escalating ban ladder lies in the code and is never invoked.</li><li>Camouflage is self-rated 5 out of 10. The failures of hole-punch are invisible from the outside. A relay operator sees who connected with whom and when.</li></ul><p>Protocol.</p><ul><li>DMs depend on the Noise session and on the encryption at rest, not on the encryption of the message layer. No receipts of delivery.</li><li>The deletion of a tweet is gossiped to the followers on a private route: the node of the author publishes it into the topic of its own followers as /private/delete/tweet and on each follower the message arrives as a private route from a foreign peer — and the auth middleware refuses it; a test in core/middleware asserts exactly this refusal. Hence the nodes of followers continue to show the tweets that their author deleted, until their cached copy expires on its own schedule.</li><li>No negotiation of versions: a change of the signature format splits the network.</li></ul><p>Data, counters, rating.</p><ul><li>Your posts are available when you are online. The deletion cannot be guaranteed on other nodes. Pseudonymous, not anonymous.</li><li>The increments of stats are not authenticated — any node can increase the counter of any tweet under its own key — and are never garbage-collected.</li><li>The weights of rating are not calibrated. The identity is free, thus a floored node restarts from 1,000. The capped remote evidence means that a node which was not attacked keeps the attacker on 600 or above.</li></ul><p>Moderation.</p><ul><li>Identities are free and the root of trust is not solved. Members verify only the signature of the chair, thus one moderator keypair can emit a valid “trio” verdict.</li><li>Moderators are anonymous and random on each start by the decision; the audit standings are never enforced. No appeals. The model makes the errors in both directions.</li><li>The pinned engine never applies the safety template of the model, thus every “unsafe” verdict reads as the first category of hazard.</li></ul><p>Media.</p><ul><li>The sealed blob is recoverable by anyone who has about a thousand cores for two weeks, not only by the police.</li><li>It contains the MAC address of every interface and theuser record - mentioned compromise.</li><li>A hostile client can seal garbage and sign it; the signature binds the file to a node, but not to the truth of the blob.</li><li>The bridged Fediverse media is completely exempt from the check of signature.</li><li>A screenshot removes it. An upload from the phone carries the data of the desktop node.</li></ul><p>Gateway and wallet.</p><ul><li>One single gateway peer ID by default; the bridged content is plaintext there.</li><li>TronGrid is a centralised dependency (it doesn’t affect anything honestly).</li></ul><p>Project.</p><ul><li>The principle 11 says that one person must not develop this network. One person develops.</li><li>No Apple support yet — i don’t have Apple Developer subscription.</li></ul><h3>14. Try it</h3><p>On Linux: sudo snap install warpnet --beta and then warpnet; on stable channel nothing is published yet. Begin with --node.network testnet; it has its own database and gives you a different peer ID, thus nothing that you do there follows you into the main network. The GitHub releases carry Linux amd64 and arm64, macOS, Windows, the relay binary and the Android APK, which is about 42 MB. The Android application is not on F-Droid yet: the packaging is finished, the merge request against fdroiddata is open and waits for a reviewer and therefore, until it lands, the APK in the GitHub release is the only build that exists.</p><p>On the first run you choose a username and a password from 8 to 32 characters with an upper-case letter, a lower-case letter, a digit and a symbol. This password is your identity: if you lose it, you lose the account and nobody can help. A backup is a copy of ~/.warpdata/&lt;network&gt;/storage plus the credentials.</p><p>In order to pair a phone, open the account menu in the sidebar of the desktop, choose “Sign in by QR-code” and scan it from the application; Settings, then Devices, demonstrates what is already paired and can unpair it. For headless machine docker compose up starts a remote node, whose browser dashboard pins the key of the node on the first connection; there is no flag for the password. Of course this is pre-1.0 software. Expect the rough edges and report them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*5RJxtvh05C32M2Q1-2cZkA.png" /></figure><h3>15. Help</h3><p>About the help I have asked already before, in the words much more blunt than these: please, help, because I am exhausted from writing all of this alone. Two years later it is still effectively one maintainer with a handful of the outside pull requests. The plea stands in the same spirit and with less swearing.</p><p><a href="https://warpnet.site/how-to-help">HOW-TO-HELP.md</a> lists seven ways. Test the software: run a node on your platform, break the UI, tell me what breaks. Fix the code and, please, the frontend. Build another client or a mobile alias. Audit the code of Noise, of PSK and of the key derivation; the section 13 is in fact a menu for such research. Write and translate the documentation; the stale like.go references in <a href="https://github.com/Warp-net/warpnet/blob/main/docs/ONBOARDING.md">ONBOARDING</a> are an open task. Run the infrastructure: host a publicly reachable relay, please. Spread the word.</p><p>One caveat to the last of these recommendations. A member node with a public address already serves the relay circuits, but today nothing adopts them automatically: the autorelay of every node is pinned to the three hardcoded bootstrap addresses, thus in order to remove “three containers on one IP” from the list of weaknesses it is necessary also to get the new relays into that list or to pass them with --node.bootstrap.</p><p>Entry points: <a href="https://github.com/Warp-net/warpnet/blob/main/docs/ONBOARDING.md">docs/ONBOARDING.md</a> for the code, the good-first-issue label on GitHub, the Telegram group on t.me/warpnetdev and a read-only Codeberg mirror of main and develop. The new files carry the AGPLv3 header.</p><h3>16. Conclusion</h3><p>The section 3 asked one question: if the most popular server in this network disappears tonight, will your posts still exist and will your followers still be able to find you? In general, for Warpnet the answer is yes on the first and mostly yes on the second: your posts were never in some other place and the weaker half is exactly this being found again, because the three bootstrap relays sit on one machine. The soft places that remain have the names: three relays on one address, the three testnet moderators and one gateway to the Fediverse. Anyone can build and run all three, although only the relays and the moderators join by themselves: the peer ID of the gateway is a compile-time default, thus a second gateway serves only those nodes that point their settings at it. All of them are still run by me.</p><p>In two years a proof of concept became a network with the desktop application, a phone, a headless build, the signed envelopes, the sealed media, a quorum of moderation, the ratings and a bridge to those networks that I criticised. Several things I described as done were in fact, during a whole year, only the comments in the code. The hardest open problem is not the technical one: the identity costs nothing and every layer above it is built in order to price the behaviour instead, because to price the identity would mean to put someone again in the middle. I set for myself the goal to build a network that you cannot switch off. The accurate version of what exists is a network with nothing in the middle to switch off and with everything else still to do.</p><p>The people from the first section still pay the rent with those accounts. The difference I can offer consists in who holds the key. In order to understand whether this difference is worth something or not, run a node on testnet tonight and if you have a public address, run a relay.</p><p><a href="https://warpnet.site/">https://warpnet.site</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f63ab757c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You better use sync.Pool!]]></title>
            <link>https://medium.com/@filinvadim/you-better-use-sync-pool-8befefbcaf11?source=rss-f1e01fe2ded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8befefbcaf11</guid>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Vadim Filin]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 13:20:31 GMT</pubDate>
            <atom:updated>2025-10-12T15:13:48.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="“America wants you” by James Montgomery Flagg, 1917. Public domain rights." src="https://cdn-images-1.medium.com/max/800/1*eDL7HYtnYLgtjg_mbX_ocA.jpeg" /></figure><p>In high-load Go services, one of the silent but expensive operations is constant memory allocation during object conversions between layers. A classic case is working with REST APIs: we receive generated Swagger (OpenAPI) structures like APIObject, but internally we operate on our own domain models like DomainObject. Every request creates fresh slices and objects, which quickly piles up into extra work for the garbage collector. For example:</p><pre>type (<br> APIObject struct {<br>  Name string<br> }<br> DomainObject struct {<br>  Name string<br> }<br>)<br><br>type SimpleConverter struct {}<br><br>func NewSimpleConverter() *SimpleConverter {<br> return &amp;SimpleConverter{}<br>}<br><br>func (c *SimpleConverter) Convert(apiObjects []APIObject) []DomainObject {<br> domainObjects := make([]DomainObject, 0, len(apiObjects)) <br><br> for _, apiObj := range apiObjects {<br>  domObj := DomainObject{Name: apiObj.Name}<br>  domainObjects = append(domainObjects, domObj)<br> }<br> return domainObjects<br>}</pre><p>And if we add here print to check how domain objects in the slice were allocated and run it couple of times</p><pre>fmt.Printf(<br>  &quot;simple: pool item len=%d cap=%d, addr=%p\n&quot;,<br>  len(domainObjects), cap(domainObjects), &amp;domainObjects[0],<br> )</pre><p>we will see that every time object has new allocation:</p><pre>simple: pool item len=1 cap=20, addr=0xc000122140<br>simple: pool item len=1 cap=20, addr=0xc000122280</pre><p>It is noticeable that on every tryout object has new address in underlying array which in it’s turn was newly allocated. This is normal and expected behavior but not really efficient.</p><p>It turns out this can be avoided. Go provides a tool called sync.Pool which is simply a place where you can keep temporary objects for later reuse.</p><p>Lets improve previous example to make memory allocation more effective for handling temporary objects:</p><pre>type SyncConverter struct {<br> pool    *sync.Pool<br> pageLen int<br>}<br><br>func NewSyncConverter(apiPaginationLen int) *SyncConverter {<br> return &amp;SyncConverter{<br>  pageLen: apiPaginationLen,<br>  pool: &amp;sync.Pool{<br>   New: func() interface{} {<br>    return make(*[]DomainObject, 0, apiPaginationLen)<br>   },<br>  },<br> }<br>}<br><br>func (c *SyncConverter) Convert(apiObjects []APIObject) []DomainObject {<br> // we get here same underlying array but just reset slice<br> domainObjects := c.pool.Get().(*[]DomainObject)<br> domainObjects = *domainObjects[:0] // reset slice<br><br> for _, apiObj := range apiObjects {<br>  *domainObjects = append(*domainObjects, DomainObject{Name: apiObj.Name})<br> }<br><br> if len(*domainObjects) != 0 {<br>  fmt.Printf(<br>   &quot;sync: pool item len=%d cap=%d, addr=%p\n&quot;,<br>   len(dbObjects), cap(dbObjects), &amp;dbObjects[0],<br>  )<br> }<br><br> if cap(*domainObjects) &lt;= c.pageLen {<br>  c.pool.Put(domainObjects)<br> }<br> return domainObjects<br>}</pre><p>Basic behavior is simple:</p><ul><li>define sync.Pool <em>New</em> property. New must be a function which returns desired object wrapped in a interface <strong>if pool is empty</strong>. In the example above *[]DomainObjectslice is returned.</li><li>retrieve slice of domain objects using <em>sync.Pool method Get()</em> and unwrap the interface. Here’s caveat: if Pool was used once it contain slice that has data from previous usage. So better to reset slice using operator [:0]. It doesn’t affect underlying array.</li><li>put slice back in the Pool. Here’s also limitation: slice that we put back in Pool must not be grown and reallocated. If slice was appended out of it’s capacity and therefore reallocated usage of sync.Pool loses it meaning — Pool will store only new allocated slice and previous one will hang in memory.<br>So to avoid that length of incoming api.APIObject slice must be known beforehand. It could be achieved but converting incoming slice by chunks or getting data from external API by pages (startTime or fromID + limit). Also for the same reason check cap(*domainObjects) &lt; c.pageLen was added — there’s no point to store reallocated slice.</li></ul><p>Here’s the same print for converted that uses sync.Pool:</p><pre>sync: pool item len=1 cap=20, addr=0xc000122000<br>sync: pool item len=1 cap=20, addr=0xc000122000</pre><p>The address of object in the slice stays the same! No new allocation!</p><p>In conclusion, sync.Pool is not a silver bullet: it works best when the data sizes are predictable and fit within a reasonable buffer capacity. Oversized objects should either be handled separately or excluded from the pool to avoid uncontrolled memory growth. But when applied in the right context, buffer pooling can be one of the simplest and most effective performance optimizations in Go.</p><p><strong>Useful links</strong></p><ul><li><a href="https://victoriametrics.com/blog/go-sync-pool">Victoria Metrics article</a></li><li>Official Go docs on <a href="https://pkg.go.dev/sync#Pool">sync.Pool</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8befefbcaf11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs for Go Developers: A Plug-and-Play Approach with llama.cpp]]></title>
            <link>https://medium.com/@filinvadim/llms-for-go-developers-a-plug-and-play-approach-with-llama-cpp-4ccccb6d04df?source=rss-f1e01fe2ded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ccccb6d04df</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Vadim Filin]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 21:17:56 GMT</pubDate>
            <atom:updated>2025-06-30T21:21:41.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As the developer of <a href="https://github.com/Warp-net/warpnet"><strong>WarpNet</strong></a>, a fully peer-to-peer social network, I needed a way to moderate user content directly on each node — with no central server and no reliance on cloud APIs. My requirements were clear:</p><ul><li>Local inference, no network calls</li><li>Minimal dependencies (ideally zero)</li><li>Reasonable performance on consumer-grade hardware</li><li>Full control from Go</li><li>No human intervention</li></ul><p>That’s how I ended up integrating <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> using a fantastic Go binding: <a href="https://github.com/go-skynet/go-llama.cpp">go-skynet/go-llama.cpp</a>. If you’re a Go developer and you’ve ever thought LLMs were “too complex” or “only for Python,” I’m here to tell you — it’s not scary, and you can get started in minutes.</p><h3>Plug-and-Play with go-llama.cpp</h3><p>Prerequisites:</p><ul><li>Ubuntu 24.04</li><li>Golang 1.24.2</li><li>go-llama.cpp commit <a href="https://github.com/go-skynet/go-llama.cpp/commit/6a8041ef6b46d4712afc3ae791d1c2d73da0ad1c"><em>6a8041ef6b46d4712afc3ae791d1c2d73da0ad1c</em></a></li></ul><p>Forget writing your own CGO bindings — the community has already done the hard part. <a href="https://github.com/go-skynet/go-llama.cpp">go-skynet/go-llama.cpp</a> provides idiomatic Go bindings over llama.cpp, with support for most modern GGUF models.</p><h3>Clone and build the binding</h3><pre>git clone --recurse-submodules https://github.com/go-skynet/go-llama.cpp<br>cd go-llama.cpp<br>make libbinding.a</pre><p>This will build the static binding library libbinding.a from llama.cpp and prepare the CGO wrapper for use in your Go code.</p><h3>Use it in your app</h3><p>Once you’ve built the libbinding.a static library, you need to embed the go-llama.cpp repository directly into your own project — since simply relying on vendor won&#39;t work for CGO.</p><p>Recommended layout:</p><pre>your-project/<br>├── go.mod<br>├── main.go<br>├── binding/<br>│   └── go-llama.cpp/<br>│       ├── llama.go<br>│       ├── binding.h<br>│       ├── libbinding.a<br>│       └── (other source files...)</pre><p>In your Go code, import it using a <strong>local import path</strong> (e.g. if it lives in your-project/binding/go-llama.cpp):</p><pre>import llama &quot;your-project/binding/go-llama.cpp&quot;</pre><p>Avoid using the module from github.com/go-skynet/go-llama.cpp directly if you&#39;re planning to embed it and statically link it — instead, clone it once, build it locally, and import it from within your repository structure.</p><p>This way, you’re fully self-contained and the Go compiler will be able to resolve all CGO requirements at build time. No runtime linking, no surprises.</p><p>The package handles model loading, context management, inference, and memory cleanup for you. Under the hood, it links against a statically built llama.cpp and gives you pure Go APIs.</p><h3>Choosing a Model — and Solving the Tokenizer Error</h3><p>For moderation, I wanted a balanced model: accurate but not too heavy. I chose:</p><ul><li><a href="https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF">TheBloke/Llama-2-7B-Chat-GGUF</a></li><li>Quantized version: Q8_K_M(Q4 version hallucinated heavily)</li></ul><p>After downloading the model file, I ran into this common error:</p><pre>Could not find tokenizer.model</pre><p>This happened because go-llama.cpp expected a consolidated .gguf file that includes the tokenizer. For example some Hugging Face repos split these artifacts. The solution: make sure you download the <em>correct GGUF variant</em> that includes everything like <a href="https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF/blob/main/llama-2-7b-chat.Q8_0.gguf">TheBloke/Llama-2–7B-Chat-GGUF</a>.</p><h3>Dealing with Linker Errors</h3><p>I also ran into this runtime panic:</p><pre>golang stderr@@GLIBC_2.2.5&#39; can not be used when making a PDE object; <br>recompile with -fPIE</pre><p><strong>Fix:</strong> change corresponding <em>go-llama.cpp/Makefile</em> code lines like this:</p><pre>#<br># Compile flags<br>#<br>CMAKE_ARGS += -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DCMAKE_C_FLAGS=&quot;-fPIE&quot; -DCMAKE_CXX_FLAGS=&quot;-fPIE&quot;<br>BUILD_TYPE?=<br># keep standard at C11 and C++11<br>CFLAGS   = -I./llama.cpp -I. -O3 -DNDEBUG -std=c11 -fPIC<br>CXXFLAGS = -I./llama.cpp -I. -I./llama.cpp/common -I./common -O3 -DNDEBUG -std=c++11 -fPIC<br>LDFLAGS  =<br><br>...<br><br>binding.o: prepare<br> $(CXX) $(CXXFLAGS) -fPIE -c binding.cpp -o binding.o</pre><p>Then rerun binding compilation:</p><pre>make clean<br>make libbinding.a</pre><h3>Building the Moderation Service</h3><p>Here’s an example of the moderation service that has basic functionality:</p><pre>type llamaService struct {<br> llm  *llama.LLama<br> opts []llama.PredictOption<br>}<br>func NewLlamaService(modelPath string, threads int) (_ *llamaService, err error) {<br> if modelPath == &quot;&quot; {<br>  return nil, errors.New(&quot;model path is required&quot;)<br> }<br> llm, err := llama.New(<br>  modelPath, // model .gguf path<br>  llama.SetContext(512), // considerable prompt length<br>  llama.SetMMap(true), // lowers RAM consuming by memory mapped IO<br>  llama.EnabelLowVRAM, // use more CPU/less GPU!<br> )<br> if err != nil {<br>  return nil, err<br> }<br> opts := []llama.PredictOption{<br>  llama.SetThreads(threads),<br>  llama.SetTokens(32), // response length<br>  llama.SetTopP(0.9), // 1 is response with more relaxed probability, 0.1 is stricter deterministic response<br>  llama.SetTemperature(0.0), // level of randomness<br>  llama.SetSeed(42), // constant seed keeps model deterministic<br>  llama.SetMlock(false), // if true - &#39;pin&#39; model in memory to boost performance but consume a lot of memory<br> }<br> lle := &amp;llamaService{llm: llm, opts: opts}<br> return lle, nil<br>}<br>func (e *llamaService) Moderate(content string) (bool, string, error) {<br> prompt := generatePrompt(content)<br> resp, err := e.llm.Predict(prompt, e.opts...)<br> if err != nil {<br>  return true, &quot;&quot;, err<br> }<br> out := strings.ToLower(strings.TrimSpace(resp))<br> switch {<br> case strings.HasPrefix(out, &quot;no&quot;):<br>  return true, &quot;&quot;, nil<br> case strings.HasPrefix(out, &quot;yes&quot;):<br>  reason := strings.TrimSpace(strings.TrimPrefix(out, &quot;yes&quot;))<br>  reason = strings.Trim(reason, &quot;,.:;- \&quot;\n&quot;)<br>  reason = strings.ReplaceAll(reason, &quot;\n&quot;, &quot;&quot;)<br>  return false, reason, nil<br> default:<br>  return true, &quot;&quot;, errors.New(&quot;unrecognized LLM output: &quot; + out)<br> }<br>}<br>func (e *llamaService) Close() {<br> e.llm.Free()<br>}</pre><h3>Prompt Engineering</h3><p>Here’s the system prompt I used for moderation:</p><pre>const moderationPromptTemplate = `<br>	Instruction: Does the following content violate moderation policy?<br>	Prohibited topics:<br>		- CSAM or sexual content involving minors (including deepfakes or AI-generated).<br>		- Non-consensual sex, porn with coercion or abuse.<br>		- Gore, violence, snuff, dead bodies.<br>		- Weapon/drug creation or sales.<br>		- Self-harm, suicide, eating disorders.<br>		- Sexism, racism, casteism, xenophobia, hate speech.<br>		- Religious extremism, terrorism incitement.<br>		- Spam, mass unsolicited promos.<br> Respond in English only.<br> If yes, answer: &#39;Yes&#39; and provide reason (ten words of finished sentence maximum)<br> If no, answer: &#39;No&#39;<br> No other answer types accepted.<br> <br> Content:<br> &quot;&quot;&quot;%s&quot;&quot;&quot;<br> <br> Answer:<br>`<br>func generatePrompt(content string) string {<br> return fmt.Sprintf(moderationPromptTemplate, content)<br>}<br></pre><p>This keeps the LLM deterministic and forces concise answers.</p><h3>Example HTTP Handler</h3><p>Here’s a minimal Go HTTP server exposing the moderation engine:</p><pre>var service LLamaServicer<br><br>http.HandleFunc(&quot;/moderate&quot;, func(w http.ResponseWriter, r *http.Request) {<br>	defer r.Body.Close()<br>	data, _ := io.ReadAll(r.Body)<br>	text := string(data)<br>        ok, reason, err := service.Moderate(text)<br>        if err != nil {<br>         w.WriteHeader(http.StatusInternalServerError)<br>         fmt.Fprint(w, err.Error())<br>         return<br>        }<br>        resp := map[string]interface{}{<br>         &quot;allowed&quot;: ok,<br>         &quot;reason&quot;:  reason,<br>        }<br>        json.NewEncoder(w).Encode(resp)<br>})</pre><h3>Dockerfile for Full Static Build</h3><p>Here’s how I bundle the whole system with no dynamic dependencies:</p><pre>FROM ubuntu:24.04<br><br>RUN apt update &amp;&amp; apt install -y curl tar build-essential ca-certificates<br>ENV GO_VERSION=1.24.2<br>RUN curl -fsSL https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz -o go.tar.gz \<br>    &amp;&amp; tar -C /usr/local -xzf go.tar.gz \<br>    &amp;&amp; rm go.tar.gz<br>COPY . /your-project<br>WORKDIR /your-project<br>ENV PATH=&quot;/usr/local/go/bin:${PATH}&quot;<br>ENV GOMODCACHE=/go/pkg/mod<br>ENV GOPATH=/your-project<br>ENV CGO_ENABLED=1<br># memory limit to prevent OOM<br>ENV GOMEMLIMIT=2750MiB<br># double the GC frequency to relax memory<br>ENV GOGC=50<br>RUN go version &amp;&amp; go build -v -o your-project cmd/your-project/main.go<br>CMD [&quot;/your-project&quot;]</pre><h3>Conclusion</h3><p>Adding LLM inference to a Go project used to feel out of reach — especially for non-ML developers. But with llama.cpp and go-llama.cpp, it&#39;s now realistic to build <strong>fast, local, private</strong> AI functionality into your apps with a few dozen lines of Go.</p><p>For me, this made it possible to embed powerful moderation directly into each WarpNet Moderator node — with no external services, no Python, and no human help.</p><h3>Links</h3><ul><li>GitHub (my profile): <a href="https://github.com/filinvadim">https://github.com/filinvadim</a></li><li>WarpNet project: <a href="https://github.com/filinvadim/warpnet">https://github.com/filinvadim/warpnet</a></li><li>go-llama.cpp: <a href="https://github.com/go-skynet/go-llama.cpp">https://github.com/go-skynet/go-llama.cpp</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ccccb6d04df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate limiter: which design to pick?]]></title>
            <link>https://medium.com/@filinvadim/rate-limiter-which-design-to-pick-f75fca08c249?source=rss-f1e01fe2ded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f75fca08c249</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Vadim Filin]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 16:29:53 GMT</pubDate>
            <atom:updated>2025-03-04T16:29:53.504Z</atom:updated>
            <content:encoded><![CDATA[<p>Rate limiting is essential for protecting APIs and distributed systems from abuse, ensuring fair resource allocation, and preventing denial-of-service (DoS) attacks. There are several approaches to implementing a rate limiter, each with its own advantages and trade-offs. Below is a detailed breakdown of the most common implementations:</p><p><strong>1. Token Bucket Algorithm</strong><br><em>How it Works:</em><br>- A bucket holds a fixed number of tokens.<br>- Tokens are added at a constant rate (e.g., 1 token per second).<br>- Each request consumes a token.<br>- If the bucket is empty, requests are rejected or delayed.</p><pre>   +------------------+<br>   |   Token Bucket   |   &lt;== (Tokens are added at a constant rate)<br>   |------------------|       Example: 1 token per second<br>   |  [●] [●] [●] [ ] |   &lt;== (Bucket has a max capacity, e.g., 4 tokens)<br>   |------------------|<br>           ||<br>           \/<br>   +----------------+<br>   | Incoming Request|  &lt;== (Each request takes 1 token)<br>   |----------------|<br>   |  Request #1 ✔  |  ✅ Token available → Request processed<br>   |  Request #2 ✔  |  ✅ Token available → Request processed<br>   |  Request #3 ✔  |  ✅ Token available → Request processed<br>   |  Request #4 ❌  |  ❌ No tokens left → Request rejected<br>   +----------------+<br><br></pre><p><em>Pros</em>:<br>- Smooth request rate over time. <br>- Allows bursts up to the bucket&#39;s capacity. <br>- Efficient and simple to implement.<br><br><em>Cons</em>:<br>- If the bucket is empty, requests must wait until tokens are replenished. <br>- Not suitable for precise per-second limits, as bursts are allowed.<br><br><em>Use Cases</em>:<br>- APIs with occasional traffic bursts.<br>- Rate limiting API keys in public services.<br>- Protecting microservices from excessive requests.</p><p><em>Implementations</em>:<br>- <a href="https://pkg.go.dev/golang.org/x/time/rate">https://pkg.go.dev/golang.org/x/time/rate</a></p><p><strong>2. Leaky Bucket Algorithm</strong><br><em>How it Works</em>:<br>- Requests enter a queue (bucket).<br>- Requests are processed at a constant rate.<br>- If the queue is full, new requests are dropped (‘bucket spills’).</p><pre>   +------------------+<br>   |   Leaky Bucket   |  &lt;== (Requests enter the queue)<br>   |------------------|<br>   |  [Req1] [Req2]   |  <br>   |  [Req3] [Req4]   |  &lt;== (Bucket has a max queue size)<br>   |------------------|<br>           ||<br>           \/  (Requests are processed at a fixed rate)<br>   +--------------------+<br>   | Outgoing Requests  |  &lt;== (Requests &quot;leak&quot; out at a constant rate)<br>   |--------------------|<br>   |  Request #1 ✔     |  ✅ Processed<br>   |  (wait 1 sec...)  |  <br>   |  Request #2 ✔     |  ✅ Processed<br>   |  (wait 1 sec...)  |<br>   |  Request #3 ✔     |  ✅ Processed<br>   +--------------------+<br><br>   If new request arrives and bucket is full:<br>   ❌ Request #5 is dropped!</pre><p><em>Pros</em>:<br>- Ensures a steady request rate. <br>- Prevents large traffic bursts. <br>- Simple to implement.<br><br><em>Cons</em>:<br>- Can introduce latency if the queue is full. <br>- Drops excess requests instead of delaying them.<br><br><em>Use Cases</em>:<br>- Load balancing in backend services.<br>- Ensuring predictable API response times.<br>- Enforcing strict request flow control.</p><p><em>Implementations</em>:<br>- <a href="https://github.com/uber-go/ratelimit">https://github.com/uber-go/ratelimit</a></p><p><strong>3. Fixed Window Counter</strong><br><em>How it Works</em>:<br>- The system tracks request counts in fixed time intervals (e.g., per minute).<br>- If the request count exceeds the limit, excess requests are rejected.<br>- The counter resets at the start of the next window.</p><pre>Time Windows (e.g., 10 requests per 5 sec)<br>---------------------------------<br>| 00:00 - 00:01 | 00:01 - 00:02 |<br>|---------------|---------------|<br>|  Req1 ✔       |  Req7 ✔       | ✅ Request processed<br>|  Req2 ✔       |  Req8 ✔       | <br>|  Req3 ✔       |  Req9 ✔       | <br>|  Req4 ✔       |  Req10 ✔      | ❌ Rejected (limit reached)<br>|  Req5 ✔       |  Req11 ❌      | <br>|  Req6 ✔       |               | <br>---------------------------------<br><br></pre><p><em>Pros</em>:<br>- Simple and easy to implement using Redis or in-memory storage. <br>- Works well when requests are evenly distributed.<br><br><em>Cons</em>:<br>- Requests are not smoothly distributed (spikes can occur at window boundaries).</p><pre> Fixed Window (10 requests per 1 min)<br>---------------------------------<br>| 12:00:58 - 12:00:59 | 12:01:00 - 12:01:01 |<br>|---------------------|---------------------|<br>|  Req1 ✔           |  Req11 ✔           | ✅ Request processed<br>|  Req2 ✔           |  Req12 ✔           | ✅ Request processed<br>|  Req3 ✔           |  Req13 ✔           | ✅ Request processed<br>|  Req4 ✔           |  Req14 ✔           | ✅ Request processed<br>|  Req5 ✔           |  Req15 ✔           | ✅ Request processed<br>|  Req6 ✔           |  Req16 ✔           | ✅ Request processed<br>|  Req7 ✔           |  Req17 ✔           | ✅ Request processed<br>|  Req8 ✔           |  Req18 ✔           | ✅ Request processed<br>|  Req9 ✔           |  Req19 ✔           | ✅ Request processed<br>|  Req10 ✔          |  Req20 ✔           | ✅ Request processed<br>---------------------------------<br>    ↑                          ↑  <br>    |                          |  <br>   Full bucket at 12:00:59     New bucket resets at 12:01:00  <br>    but all requests allowed again instantly! So in 2 seconds<br>    rate limiter allowed 20 requests instead of 10.</pre><p>- Can lead to unfair throttling if many requests come at the start of the window</p><pre>Fixed Window (1 min)<br>-------------------------------------------------<br>| 12:00:00 - 12:00:59 (Limit: 5 requests)       |<br>-------------------------------------------------<br>|  User A - Req1 ✔  |  ✅ Processed             |<br>|  User A - Req2 ✔  |  ✅ Processed             |<br>|  User A - Req3 ✔  |  ✅ Processed             |<br>|  User A - Req4 ✔  |  ✅ Processed             |<br>|  User A - Req5 ✔  |  ✅ Processed             |<br>|-------------------|--------------------------|<br>|  User B - Req1 ❌ |  ❌ Rejected (limit hit)  |<br>|  User B - Req2 ❌ |  ❌ Rejected (limit hit)  |<br>-------------------------------------------------</pre><p><em>Use Cases</em>:<br>- API rate limiting per user/IP.<br>- Enforcing hourly/daily quotas on resource consumption.<br>- Preventing excessive resource usage in SaaS applications.</p><p><em>Implementations</em>:<br>- <a href="https://medium.com/@sumit-s/implementing-fixed-window-counter-rate-limiting-in-go-f5f8bf352c6c">https://medium.com/@sumit-s/implementing-fixed-window-counter-rate-limiting-in-go-f5f8bf352c6c</a></p><p>4. <strong>Sliding Window Counter</strong><br><em>How it Works</em>:<br>- Similar to the fixed window, but instead of resetting at fixed intervals, a moving time window is used.<br>- Requests are counted dynamically based on the last **X** seconds (e.g., the last 60 seconds instead of a fixed minute).</p><pre>Sliding Window (1 min)  <br>-------------------------------------------------<br>| Time: 12:00:00 - 12:01:00                     |<br>-------------------------------------------------<br>| Req1 (12:00:05) ✔  ✅ Count: 1               |<br>| Req2 (12:00:10) ✔  ✅ Count: 2               |<br>| Req3 (12:00:20) ✔  ✅ Count: 3               |<br>| Req4 (12:00:40) ✔  ✅ Count: 4               |<br>| Req5 (12:00:55) ✔  ✅ Count: 5               |<br>-------------------------------------------------<br>Sliding Window Moves Forward →  <br>-------------------------------------------------<br>| Time: 12:00:10 - 12:01:10                     |<br>-------------------------------------------------<br>| Req1 (12:00:05) ❌ Expired (Removed)         |<br>| Req6 (12:01:05) ✔  ✅ Count: 5               |<br>-------------------------------------------------</pre><p><em>Pros</em>:<br>- Prevents artificial spikes at window boundaries. <br>- More evenly distributed request throttling.<br><br><em>Cons</em>:<br>- More complex to implement than fixed window counters. <br>- Can be expensive in high-throughput systems if not optimized well.<br><br><em>Use Cases</em>:<br>- Enforcing fair resource usage in distributed systems.<br>- Implementing dynamic API rate limits.<br>- Handling short bursts of traffic efficiently.</p><p><em>Implementations</em>:<br>- <a href="https://github.com/RussellLuo/slidingwindow">https://github.com/RussellLuo/slidingwindow</a></p><p>And here i want to stop and focus on my favorite implementation of limiter which is more complex but could potentially solve all the issues related to rate limiting.</p><p><strong>5. Sliding Window Log</strong><br><em>How it Works</em>:<br>- Instead of storing a counter for fixed intervals (like Fixed or Sliding Window Counter), <strong>Sliding Window Log stores the exact timestamps of each request</strong>.<br>- To check if a request is allowed, the system removes outdated timestamps and counts the recent ones.<br>- If the count is below the limit, the request is allowed.</p><pre>Time Window: Last 60 seconds (Moving Window)<br>-------------------------------------------------<br>|  Stored Requests (Timestamps)                |<br>|----------------------------------------------|<br>|  [12:00:05] - Request 1 ✔                    |<br>|  [12:00:12] - Request 2 ✔                    |<br>|  [12:00:18] - Request 3 ✔                    |<br>|  [12:00:27] - Request 4 ✔                    |<br>|  [12:00:42] - Request 5 ✔                    |<br>|  [12:00:51] - Request 6 ✔                    |<br>|----------------------------------------------|<br>| ✅ Current count: 6 (Allowed: 10 per minute) |<br>-------------------------------------------------<br><br>&gt;&gt;&gt; New Request at **12:01:03**:<br>- ✅ Count last 60 seconds: **6 requests**<br>- ✅ Within the limit (10 requests per minute)<br>- ✅ Request **allowed** and added to the log<br>-------------------------------------------------<br>|  Stored Requests (Updated)                   |<br>|----------------------------------------------|<br>|  [12:00:12] - Request 2 ✔                    |<br>|  [12:00:18] - Request 3 ✔                    |<br>|  [12:00:27] - Request 4 ✔                    |<br>|  [12:00:42] - Request 5 ✔                    |<br>|  [12:00:51] - Request 6 ✔                    |<br>|  [12:01:03] - Request 7 ✔ (New Request)      |<br>|----------------------------------------------|<br>| ✅ Current count: 6 (Still under limit)      |<br>-------------------------------------------------<br><br>&gt;&gt;&gt; New Request at **12:01:10**:<br>- ✅ Count last 60 seconds: **6 requests**<br>- ✅ Within the limit<br>- ✅ Request **allowed** and added to the log<br><br>&gt;&gt;&gt; New Request at **12:01:15**:<br>- ✅ Count last 60 seconds: **7 requests**<br>- ✅ Within the limit<br>- ✅ Request **allowed** and added to the log<br><br>&gt;&gt;&gt; New Request at **12:01:20**:<br>- ❌ Count last 60 seconds: **10 requests**<br>- ❌ Limit exceeded (10 per minute)<br>- ❌ Request **rejected**</pre><p><em>Pros</em>:<br>- Provides precise rate limiting. <br>- Handles traffic bursts better than other methods.<br><br><em>Cons</em>:<br>- Requires more memory/storage as logs grow with traffic. <br>- Computationally expensive for large-scale systems.<br><br><em>Use Cases</em>:<br>- Implementing real-time API rate limiting with high accuracy.<br>- Preventing abuse in financial or authentication systems.</p><p><em>Implementations</em>:<br>- <a href="https://github.com/filinvadim/ratelimiter">https://github.com/filinvadim/ratelimiter</a></p><p>Each approach has trade-offs in accuracy, memory usage, and computational complexity, so the choice depends on system requirements.</p><p><strong>Making rate limiter agile</strong></p><p>By default, rate limiters treat all requests equally, but in many cases, some requests <strong>consume more resources</strong> than others. By assigning <strong>weights</strong>, we can limit users based on the actual cost of their requests rather than a simple count.</p><p><em>How it Works</em>:</p><p>- Instead of each request counting as <strong>“1 unit”</strong>, we assign a weight based on <strong>complexity, priority, or resource usage</strong>.</p><p>- The rate limiter then <strong>deducts tokens/credits based on weight</strong>, rather than a fixed amount.</p><pre>User requests:<br>- GET /profile     → Weight: 1 (light request)<br>- POST /upload     → Weight: 5 (heavy request)<br>- AI model inference → Weight: 10 (very heavy request)<br><br>Rate limit: 50 tokens per minute<br>------------------------------------------------<br>| 12:00:00 - GET /profile (1 token)  ✅ Allowed |<br>| 12:00:10 - GET /profile (1 token)  ✅ Allowed |<br>| 12:00:15 - POST /upload (5 tokens) ✅ Allowed |<br>| 12:00:20 - AI model inference (10 tokens) ✅ Allowed |<br>| 12:00:30 - AI model inference (10 tokens) ❌ Blocked |<br>------------------------------------------------</pre><p>Weighted rate limiting prevents expensive operations from overwhelming the system, heavy users consume more quota, light users get more access, limits can be adjusted dynamically per request type.</p><p>Also rate limiting based on IP address or global limits is often inefficient because<strong> </strong>single user could be monopolizing resources while others are blocked or shared networks (e.g., corporate VPNs) could result in unfair blocking or certain premium users may require higher limits.</p><p>To solve this, we rate-limit each user individually using a <strong>Unique Identifier (UID)</strong>, such as:</p><p><strong>- </strong>API Key (for API-based access)</p><p><strong>- </strong>User ID (for authenticated users)</p><p><strong>- </strong>Session Token (for web applications)</p><p><strong>- </strong>Device ID (for mobile apps)</p><p>- IP Address (fallback for anonymous users)</p><p>Unique identifier prevents one user from blocking others, allows to have customizable limits, is fair and scalable.</p><p><strong>Summary</strong><br>- <em>Token Bucket</em> allows bursts but smooths traffic.<br>- <em>Leaky Bucket</em> enforces a strict request rate.<br>- <em>Fixed Window</em> is simple but can cause spikes.<br>- <em>Sliding Window</em> balances fairness and efficiency.<br>- <em>Sliding Window Log</em> is precise but resource-intensive.</p><p><strong>Useful links</strong></p><ul><li><a href="https://blog.bytebytego.com/p/rate-limiting-fundamentals">https://blog.bytebytego.com/p/rate-limiting-fundamentals</a></li><li><a href="https://en.wikipedia.org/wiki/Rate_limiting">https://en.wikipedia.org/wiki/Rate_limiting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f75fca08c249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hashicorp Raft: Plug-n-Play]]></title>
            <link>https://medium.com/@filinvadim/hashicorp-raft-plug-n-play-ab0a04193315?source=rss-f1e01fe2ded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab0a04193315</guid>
            <category><![CDATA[raft]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <dc:creator><![CDATA[Vadim Filin]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 10:41:33 GMT</pubDate>
            <atom:updated>2025-07-02T12:51:28.395Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Raft?</strong><br> Raft is a distributed consensus algorithm designed to be understandable and implementable. It ensures that multiple nodes in a distributed system agree on a log of transactions, even in the presence of failures. Unlike Paxos, which is often considered complex and difficult to implement, Raft is structured around leader election, log replication, and safety guarantees.<br> Key features of Raft:<br>1. Leader Election – nodes elect a leader that manages log replication.<br>2. Log Replication – the leader ensures that all followers apply the same sequence of log entries.<br>3. Commit and Safety – Raft guarantees that once an entry is committed, it remains committed.<br>4. Membership Changes – Raft allows nodes to join and leave the cluster dynamically.<br><br><strong>hashicorp/raft – The Go Implementation</strong><br> <a href="https://github.com/hashicorp/raft">https://github.com/hashicorp/raft</a> is a production-ready Go implementation of the Raft protocol. It is used in HashiCorp&#39;s tools like Consul and Nomad to maintain consistent state across nodes.<br> Core components of hashicorp/raft:<br><em> Raft</em> - the main struct managing consensus and state transitions;<br><em>FSM (Finite State Machine)</em> - application logic for handling committed logs;<br><em> LogStore</em> - persistent storage for logs;<br><em> StableStore</em> - persistent storage for Raft metadata (e.g., term, voted leader);<br><em> Transport</em> - handles communication between nodes;<br><em> SnapshotStore</em> - saves snapshots of the FSM to reduce log size.</p><p>Breakdown of <em>hashicorp/raft</em> APIs<br>1. Log Storage<br> The <em>LogStore</em> stores the Raft log entries, ensuring persistent, ordered application of commands. <br>The most common implementation are:<br>- <a href="https://github.com/hashicorp/raft-boltdb">https://github.com/hashicorp/raft-boltdb</a></p><pre>logStore, err := raftboltdb.NewBoltStore(&quot;raft-log.bolt&quot;)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><p>- <a href="https://github.com/tidwall/raft-leveldb">https://github.com/tidwall/raft-leveldb</a></p><pre>logStore, err := raftleveldb.NewLevelDBStore(&quot;raft-log.leveldb&quot;, 0)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><p>- <a href="https://github.com/BBVA/raft-badger">https://github.com/BBVA/raft-badger</a></p><pre>logStore, err := raftbadger.NewBadgerStore(&quot;raft-log.badger&quot;)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><p>2. State Machine (FSM)<br>The <em>Finite State Machine</em> (FSM) applies committed log entries to an application&#39;s state.</p><pre>type FSM struct{}<br><br>func (f *FSM) Apply(log *raft.Log) interface{} {<br> log.Println(&quot;Applying log:&quot;, string(log.Data))<br> return nil<br>}<br><br>func (f *FSM) Snapshot() (raft.FSMSnapshot, error) {<br> return &amp;Snapshot{}, nil<br>}<br><br>func (f *FSM) Restore(rc io.ReadCloser) error {<br> return nil<br>}</pre><p>3. Transport Layer<br> Communication between nodes uses a transport abstraction. The two main implementations are:</p><pre>raft.NewTCPTransport(...) – Production use<br>raft.NewInmemTransport(...) – Testing<br><br>transport, err := raft.NewTCPTransport(<br>              &quot;127.0.0.1:8080&quot;, nil, 3, time.Second, os.Stderr,<br>            )</pre><p>4. Cluster Membership Management<br>Nodes can join or leave the cluster dynamically. Here&#39;s an example:</p><pre>raftNode.AddVoter(raft.ServerID(&quot;node-2&quot;), &quot;127.0.0.1:8081&quot;, 0, 0)<br>raftNode.RemoveServer(raft.ServerID(&quot;node-3&quot;), 0, 0)</pre><p><strong>How Raft Works Internally in HashiCorp&#39;s Implementation</strong><br>1. Leader Election:<br>- nodes start in the Follower state.<br>- if no leader is detected, a Candidate state is initiated.<br>- candidates request votes from other nodes.<br>- a majority vote elects a Leader.<br>2. Log Replication:<br>- clients send commands to the Leader.<br>- the Leader appends the command to its log.<br>- the command is replicated to followers.<br>- if a majority acknowledges, the log entry is committed.<br>3. Cluster Membership Changes:<br>- new nodes start as non-voting members.<br>- the Leader updates the cluster configuration.<br>- when committed, the node becomes active.<br><br><strong>Setting Up a Raft Node in Go</strong><br> A Raft node is initialized using the raft.NewRaft(...) function. Below is a minimal setup:</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;time&quot;<br><br> &quot;github.com/hashicorp/raft&quot;<br> &quot;github.com/hashicorp/raft-boltdb&quot;<br>)<br><br>func main() {<br> // Create configuration<br> config := raft.DefaultConfig()<br> config.LocalID = raft.ServerID(&quot;node-1&quot;)<br><br> // Setup Raft storage (logs, metadata, snapshots)<br> logStore, _ := raftboltdb.NewBoltStore(&quot;raft-log.bolt&quot;)<br> stableStore, _ := raftboltdb.NewBoltStore(&quot;raft-stable.bolt&quot;)<br> snapshots, _ := raft.NewFileSnapshotStore(&quot;snapshots&quot;, 3, os.Stderr)<br><br> // Transport layer (communication between nodes)<br> transport, _ := raft.NewTCPTransport(&quot;127.0.0.1:8081&quot;, nil, 3, time.Second, os.Stderr)<br><br> // Initialize the Raft node<br> raftNode, err := raft.NewRaft(config, &amp;FSM{}, logStore, stableStore, snapshots, transport)<br> if err != nil {<br>   log.Fatal(err)<br> }<br><br> // setup a cluster<br> configuration := raft.Configuration{<br>   Servers: []raft.Server{<br>     {ID: config.LocalID, Address: transport.LocalAddr()},<br>     {ID: raft.ServerID(&quot;node-2&quot;), Address: &quot;127.0.0.1:8082&quot;},<br>     {ID: raft.ServerID(&quot;node-3&quot;), Address: &quot;127.0.0.1:8083&quot;},<br>   },<br> }<br> raftNode.BootstrapCluster(configuration)<br>}</pre><p>Now theoretical part is done. Looks simple, huh? Let&#39;s start our practice.<br><br><strong>Caveats</strong><br>Inexperienced users may run into various issues when integrating HashiCorp’s Raft library into their distributed systems. Here are some of the most common pitfalls and how to avoid them:<br><br><strong>1. Misunderstanding Cluster Bootstrapping</strong><br><em>BootstrapCluster</em> does many implicit operations (not really <a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a> function) which are incomprehensible by inexperienced user. For example:<br>- you cannot bootstrap cluster twice if you set up persistent storage. <em>BootstrapCluster</em> stores information about all cluster nodes and their initial states. Second call of this function will return error: <em>ErrCantBootstrap = errors.New(&quot;bootstrap only works on new clusters&quot;)</em>. So it&#39;s quite challenging to set up cluster only once. There are several options what you can do:<br> 1. Call <em>BootstrapCluster</em> and ignore the error. Simplest solution but potentially you can miss some other important errors.<br> 2. Set up some distributed lock (like Redis one) which will prevent other nodes to call <em>BootstrapCluster</em> function.<br> 3. Completely rewrite <em>BootstrapCluster</em> function using your own custom logic.<br>- you must use persistent storage at least for <em>stable store</em> and <em>snapshot store</em>. Otherwise, your Raft node will lose its stability and won&#39;t be able to sync with other nodes.<br>- node must have unique <em>ServerID</em> across all Raft cluster and consistent address also.<br>- other cluster nodes may not be ready to be part of a cluster due to network conditions or just because of start up lag. That will lead of impossibility to elect leader and cluster will become stalled.<br><br> Here&#39;s my personal solution to avoid <em>BootstrapCluster</em> function unpredictive behavior:</p><pre>func ForceBootstrap(addr raft.ServerID, logStore raft.LogStore, stableStore raft.StableStore) error {<br> lastIndex, err := logStore.LastIndex()<br> if err != nil {<br>   return fmt.Errorf(&quot;failed to read last log index: %v&quot;, err)<br> }<br><br> if lastIndex != 0 {<br>   // if last index is not zero it means that there&#39;s already set up and <br>   // active Raft cluster<br>   // so skip<br>   return nil<br> }<br><br> // force Raft to create single node cluster no matter what;<br> // single node will elect itself as a leader immediately;<br> // after connection to other nodes cluster reelects leader again<br> raftConf := raft.Configuration{}<br> raftConf.Servers = append(raftConf.Servers, raft.Server{<br>   Suffrage: raft.Voter,<br>   ID: addr,<br>   Address: raft.ServerAddress(addr),<br> })<br><br> // set up initial values for log store and stable store<br> if err := stableStore.SetUint64([]byte(&quot;CurrentTerm&quot;), 1); err != nil {<br>   return fmt.Errorf(&quot;failed to save current term: %v&quot;, err)<br> }<br> if err := logStore.StoreLog(&amp;raft.Log{<br>   Type: raft.LogConfiguration, Index: 1, Term: 1,<br>   Data: raft.EncodeConfiguration(raftConf),<br>   }); err != nil {<br>     return fmt.Errorf(&quot;failed to store bootstrap log: %v&quot;, err)<br>   }<br><br> // ensure that cluster last index now is not zero<br> return logStore.GetLog(1, &amp;raft.Log{})<br>}</pre><p>Surprisingly, HashiCorp’s Raft allows nodes outside the defined cluster configuration to join. This is clearly a bug, yet it still works.</p><p><strong>2. Misunderstanding Cluster Readiness</strong><br> One of the most common pitfalls when working with Raft is misunderstanding when a cluster is actually ready to serve requests. If nodes aren’t properly initialized, users might experience unexpected failures, stale reads, or unresponsive services.<br> Cluster may appear &quot;Up&quot; but its actually isn’t ready and here are symptoms of it:<br>- cluster starts, but requests fail or get stuck;<br>- leader election occurs, but logs don’t replicate;<br>- clients receive stale data or not the leader errors;<br>- cluster stays in the follower state forever;<br>- leader election never succeeds, even after multiple retries;<br>- clients query a follower node and get stale data;<br>- leader has committed new entries, but followers lag.<br><br> The solution of above problems requires understanding how Raft manages nodes roles. You need to be sure prior that Raft has majority of nodes (quorum) to be alive to make decisions. And it&#39;s absolutely necessary to check cluster quorum before serving requests and check if there is<br>a leader elected.<br> Also don&#39;t forget that nodes state takes time to be synchronized so you won&#39;t be able to apply any new state until sync is done.<br>Here is how it might look in a code:</p><pre>raftNode, _ := raft.NewRaft(config, &amp;FSM{}, logStore, stableStore, snapshots, transport)<br>ticker := time.NewTicker(time.Second)<br>defer ticker.Stop()<br><br> // wait for leader election<br>loop:<br>  for {<br>    select {<br>    case &lt;-ticker.C:<br>      if addr, id := raftNode.LeaderWithID(); addr != &quot;&quot; {<br>        // leader found!<br>        break loop<br>      }<br>    case &lt;-ctx.Done():<br>      return ctx.Err()<br>    }<br>  }<br><br> // after leader election let&#39;s wait own node promotion to a voter<br>loop2:<br>  for {<br>    select {<br>    case &lt;-ctx.Done():<br>      return ctx.Err()<br>    case &lt;-ticker.C:<br>      wait := raftNode.GetConfiguration()<br>      if err := wait.Error(); err != nil {<br>        return err<br>      }<br>    <br>      if isVoter(id, wait.Configuration()) {<br>        // node is voter!<br>        break loop2<br>      }<br>    }<br>  }<br><br> // wait state to be sync. Applied index must be equal to last index<br>for {<br>  select {<br>  case &lt;-ctx.Done():<br>    return ctx.Err()<br>  case &lt;-ticker.C:<br>    lastAppliedIndex := r.raft.AppliedIndex()<br>    lastIndex := r.raft.LastIndex()<br>  <br>  <br>    if lastAppliedIndex == lastIndex {<br>      return nil<br>    }<br>  }<br>}</pre><p><strong>3. Misunderstanding FSM (Finite State Machine) and state data types</strong><br> When implementing Raft with <em>hashicorp/raft</em>, a common mistake is misunderstanding how the <em>FSM</em> works and what data types can or should be stored. This often leads to data corruption, crashes, or performance issues. Here are the most common caveats:<br>- logs cannot be replayed because non-serializable types (e.g., maps with interfaces) were used;<br>- <em>FSM</em> only applies logs on the leader; followers replicate logs but don’t execute them;<br>- <em>FSM</em> doesn&#39;t validate your data in any way. You must create custom <em>FSM</em> for that;<br>- <em>FSM</em> is an in-memory application state that is rebuilt from Raft logs. It is not automatically <br> persistent. To persist state across restarts, enable snapshots so Raft can restore <em>FSM</em> efficiently.<br><br> After some research i&#39;ve found out that the most suitable data type for <em>FSM</em> is a <em>map[string]string</em>. Having unique keys for you data is a leading to good state consistency. Of course, it&#39;s regular Golang map so its methods must be wrapped to mutex to avoid potential race condition because <em>hashicorp/raft</em> may call <em>FSM</em> methods asynchronously.<br>Also, if you need nodes to have consensus about validity of something like transaction, for example, you need <em>FSM</em> to have validation functionality.<br>Here&#39;s how basic implementation of <em>FSM</em> that consider of above notes might look like:</p><pre>type (<br> KVState map[string]string // THE &#39;STATE&#39;!<br><br> ConsensusValidatorFunc func(k, v string) error<br>)<br><br>type fsm struct {<br> mux *sync.Mutex // mutex hat<br> state *KVState // link to a curren state<br> prevState KVState // previous state store for proper disaster recovery<br> <br> validators []ConsensusValidatorFunc // custom validators<br>}<br><br>func newFSM(validators ...ConsensusValidatorFunc) *fsm {<br> // initializing state to avoid nil state errors<br> // &#39;genesis&#39; value here is only for observability and not required<br> state := KVState{&quot;genesis&quot;: &quot;genesis&quot;}<br> return &amp;fsm{<br>   state: &amp;state,<br>   prevState: KVState{},<br>   mux: new(sync.Mutex),<br>   validators: validators,<br> }<br>}<br><br>// Apply is invoked by Raft once a log entry is commited. Do not use directly.<br>func (fsm *fsm) Apply(rlog *raft.Log) (result interface{}) {<br> fsm.mux.Lock()<br> defer fsm.mux.Unlock()<br> defer func() {<br> // attempt to save state after panic<br>   if r := recover(); r != nil {<br>     *fsm.state = fsm.prevState<br>     result = errors.New(&quot;fsm apply panic: rollback&quot;)<br>   }<br> }()<br> var newState = make(KVState, 1)<br> if err := json.Unmarshal(rlog.Data, &amp;newState); err != nil {<br>   return fmt.Errorf(&quot;failed to decode log: %w&quot;, err)<br> }<br><br> for _, validator := range fsm.validators {<br>   // apply validator on each key/value<br>   for k, v := range newState {<br>     if err := validator(k, v); err != nil {<br>       return err<br>     }<br>   }<br> // applied validators doesn&#39;t stop method Apply from storing data<br> }<br> <br> // save previous state<br> fsm.prevState = make(KVState, len(*fsm.state))<br> for k, v := range *fsm.state {<br>   fsm.prevState[k] = v<br> }<br> // save new state<br> for k, v := range newState {<br>   (*fsm.state)[k] = v<br> }<br> return fsm.state<br>}<br><br>// Snapshot encodes the current state so that we can save a snapshot.<br>func (fsm *fsm) Snapshot() (raft.FSMSnapshot, error) {<br> fsm.mux.Lock()<br> defer fsm.mux.Unlock()<br><br> buf := new(bytes.Buffer)<br> err := json.NewEncoder(buf).Encode(fsm.state)<br> if err != nil {<br>   return nil, err<br> }<br><br> return &amp;fsmSnapshot{state: buf}, nil<br>}<br><br>// Restore takes a snapshot and sets the current state from it.<br>func (fsm *fsm) Restore(reader io.ReadCloser) (err error) {<br> defer func() {<br>   err = reader.Close()<br> }()<br><br> fsm.mux.Lock()<br> defer fsm.mux.Unlock()<br><br> err = json.NewDecoder(reader).Decode(fsm.state)<br> if err != nil {<br>   return err<br> }<br><br> // here previous state might be handy<br> fsm.prevState = make(map[string]string, len(*fsm.state))<br> return nil<br>}<br><br>// just a buffer for snapshot data<br>type fsmSnapshot struct {<br> state *bytes.Buffer<br>}<br><br>// Persist writes the snapshot (a serialized state) to a raft.SnapshotSink.<br>func (snap *fsmSnapshot) Persist(sink raft.SnapshotSink) error {<br> _, err := io.Copy(sink, snap.state)<br> if err != nil {<br>   _ = sink.Cancel()<br>   return err<br> }<br> return sink.Close()<br>}<br><br>func (snap *fsmSnapshot) Release() {<br> // interface stub<br>}</pre><p>Full simple wrapper for HashiCorp&#39;s Raft implementation in Go that helps to avoid all above issue you can find here: <a href="https://github.com/filinvadim/easy-raft">https://github.com/filinvadim/easy-raft</a><br><br><strong>Useful links</strong><br>- Hashicorp Raft Golang implementation - <a href="https://github.com/hashicorp/raft">https://github.com/hashicorp/raft</a><br>- Raft paper - <a href="https://raft.github.io/raft.pdf">https://raft.github.io/raft.pdf</a><br>- Raft Wikipedia - <a href="https://en.wikipedia.org/wiki/Raft_(algorithm)">https://en.wikipedia.org/wiki/Raft_(algorithm)</a><br>- Raft for libp2p - <a href="https://github.com/filinvadim/libp2p-raft-go">https://github.com/filinvadim/libp2p-raft-go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab0a04193315" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>