<?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 Merlin Fuchs on Medium]]></title>
        <description><![CDATA[Stories by Merlin Fuchs on Medium]]></description>
        <link>https://medium.com/@merlinfuchs?source=rss-ae671f5db8f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NLZoCGuGqoHfnBiEE0FIHA.jpeg</url>
            <title>Stories by Merlin Fuchs on Medium</title>
            <link>https://medium.com/@merlinfuchs?source=rss-ae671f5db8f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:57:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@merlinfuchs/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[The Art of Software]]></title>
            <link>https://medium.com/@merlinfuchs/the-art-of-software-f9b5a3e6440f?source=rss-ae671f5db8f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9b5a3e6440f</guid>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Merlin Fuchs]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 21:08:36 GMT</pubDate>
            <atom:updated>2026-10-11T12:28:00.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creativity and AI in software</h3><p>I have recently been thinking about my work as a software engineer and the role of creativity in it. I feel like software development is often misunderstood to be straightforward process of solving problems. This doesn’t align with how I work at all, so I thought it makes sense to share my perspective on it.</p><h3>My background</h3><p>The way I approach software development might be different from many other people working in the field. I never studied computer science in university or learned about all these theoretical and deeply technical concepts. I did have a few computer science courses in high school where we learned the basics about computers, networking, and programming, but that’s pretty much it.</p><p>Nevertheless, I can confidently say that I’m pretty good at building software. For me building software was always about intuition. I remember when I built my first project in Python, I didn’t start out reading about patterns or algorithms — I just started writing code until something worked. Every developer knows that deeply satisfying feeling when the software you are building actually starts working.</p><p>To this day that’s exactly how I go about starting new projects. There is little planning involved. I have an idea in my head and just start building; everything else comes along the way.</p><h3>“Vibe Coding”</h3><p>The term “vibe coding” has taken over the software world in 2025. It describes the process of creating software by relying purely on AI tools like chatbots to write the code. Advocates of it suggest that this way developers can forget about the code altogether and just focus on the vibe and feel of the product.</p><p>I think the term is extremely misleading. Using AI to write the code is probably the least vibe based approach I can think of. AI doesn’t have emotions; it can’t <em>vibe</em>. Even if we say that “vibe” refers to the end-result and not to the code, AI is inherently bad at creating stuff that people can actually relate with.</p><p>My way of writing software actually fits the term “vibe coding” much better as it is extremely dependent on my vibe and creativity. When I have a blockage or can’t get into the right space of mind, I really can’t do good work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*L1p2yR9PtuRvJMakbatAFA.jpeg" /><figcaption>Trippy Clancy from The Midnight Gospel</figcaption></figure><h3>The Flow</h3><p>Everybody knows the feeling of being in the flow. This is when remaining completely focused on a task feels effortless and the time just flies by.</p><p>For me it’s the most effective way of working as I can immerse myself completely into a project without being distracted by anything else. Sadly this state is also very fragile and can’t be forced. I find that large amounts of caffeine <em>can</em> definitely help, but it’s also heavily dependent on the environment I’m in.</p><p>When I’m working on my own projects I find that there is no point in forcing me to work on something when I don’t feel inspired. Yes, there are things that have to get done and I can force myself to do them, but usually it’s more effective to follow the inspiration and work on things that I feel motivated to do. I will be magnitudes faster and do better work even if it means that the output isn’t constant.</p><p>I personally can only get into the flow when I’m alone for some time and can decide myself when and on what I want to work.</p><h4>Working Alone</h4><p>I always liked spending timealone and this also applies to the way I work. I spend probably 80% of my work day without communicating with anyone and just working on my own. Obviously I don’t write code the whole time; a lot of time is spent on thinking about problems and honestly also just distracting myself. But when the flow kicks that’s when I do my best work.</p><p>There were times when I felt bad about this and thought working more with other people would yield better results. And in many ways it can! It definitely helps discussing problems with others to get other perspectives and find the best solution for problems.</p><p>It took me a while to realize that building software is an extremely creative process for me and it works best if I don’t have other people interfering with that too often. That doesn’t mean I don’t like being part of a team, but I also don’t want to discuss every decision I make.</p><p>I believe that’s also one reason why larger teams move slower. Constant communication kills creativity and inspiration.</p><h3>The Art in Software</h3><p>In my experience the process of creating software can be very similar to creating other forms of art. Most artists do their work alone and don’t rely on constant communication with others. Obviously inspiration often happens by getting input from outside, but the actual act of creating something new happens alone.</p><blockquote>If you ask Michelangelo to paint the ceiling of your chapel, you are asking him to function as an artist; if you dictate to him the nature, coloration, size and relationship of the objects he will portray there, you are asking him to function as an engineer. <a href="https://www.spectacle.org/1199/software.html">1</a></blockquote><p>Art is created in quiet places and when no rigid instructions are given. You can treat software development as engineering — the same you can treat painting as engineering — but at what price?</p><p>I don’t want to frame myself as an artist or compare software development with other forms of art. There is some artistic part to it tho and ignoring that stops great work from happening.</p><h4>“Problem Solvers”</h4><p>I have seen many software developers call themselves problem solvers, and I think that’s a valid description for parts of what software development is. I don’t believe solving a problem is often the primary motivator tho.</p><p>Yes, software is usually there to solve a problem and I think we all like doing that, but is that actually the primary motivation? Isn’t it often just the act of creating something, even if it’s completely useless to the rest of the world?</p><p>Some of my favorite projects weren’t built to solve a problem; they just came out of interest and inspiration to create something. I think in a weird way software projects can be a way to express emotions, just like other art forms.</p><h4>Treating Software like Engineering</h4><p>For many years people have tried to squeeze the process of software development into rigid corporate structures to make things predictable and plannable.</p><p>These times are mostly over and companies have accepted that this isn’t the right approach and doesn’t align with the reality of software development. People have come up with so called “agile” frameworks like SCRUM that are supposed to be flexible enough while still maintaining control over the process.</p><p>Are these frameworks better than rigid structures? Yes. Are these frameworks good to foster creativity? No. Planning every single detail and having to communicate every step always hurts creativity and flow.</p><p>Does this apply to all software? Probably not. There is software where little creativity is involved and where this is the right approach.</p><h4>The Role of AI</h4><p>I believe when it comes to the creative act of developing software, AI can be a good tool. There is a thin line between using it as an assistant to do mundane tasks or letting it control the whole process. It’s really easy to get used to tab-completion provided by Github-Copilot and similar AI integrations, but I personally try to avoid using more than that for projects that I actually care about.</p><p>In the end — just like a chainsaw for wood sculptor — AI is a tool in the toolbox that can make certain things easier. We should be careful to not let the chainsaw make the sculpture on its own though.</p><h3>Embracing Creativity</h3><p>Software encapsulates aspects of both engineering and art. It follows clearly defined rules and requires careful considerations, but the creative aspect is undeniable.</p><p>I think in that sense the job of a software developer is very similar to an architect. There are clear rules defined by the laws of physics that affect the design and construction of the building. In practice this is only the very base of the work and obviously expected from all architects. What really defines a good architect is not how well they understand physics, but how they incorporate that into the design.</p><p>I think we should embrace the creative aspects of software more and allow for the flow to kick in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9b5a3e6440f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-compiling Rust From Mac to Linux]]></title>
            <link>https://medium.com/better-programming/cross-compiling-rust-from-mac-to-linux-7fad5a454ab1?source=rss-ae671f5db8f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fad5a454ab1</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Merlin Fuchs]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 14:20:04 GMT</pubDate>
            <atom:updated>2022-06-09T11:26:52.052Z</atom:updated>
            <content:encoded><![CDATA[<h4>A journey through the issues I encountered</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*e489ug_7SlSjR1AN" /></figure><p>While trying to cross-compile rust from Mac to Linux I ran into a few issues, so I thought I would write a simple guide for myself and anyone else interested. This mainly consists of my own findings and might not work for everyone.</p><h3>General steps</h3><p>To cross-compile from one platform to another, it’s usually not enough to just install the standard library for the target using <a href="https://rustup.rs/">rustup</a>. You also have to install a linker for the platform and tell rustc where to find it.</p><p>For some platforms, other dependencies might be necessary as well, but in this article, I will concentrate on compiling from Mac to Linux.</p><p>Generally, these are the steps necessary to compile from one platform to another:</p><ul><li>Install the standard library for the target using rustup target add &lt;target&gt;</li><li>Install a linker for the platform</li><li><a href="https://doc.rust-lang.org/cargo/reference/config.html#target">Update the cargo configuration</a> so rustc can find the linker</li><li>Set the TARGET_CC environment variable to the linker executable during compilation</li><li>Add the target flag to your build command: cargo build --release --target &lt;target&gt;</li></ul><h3>Choosing the build target</h3><p>When choosing the right build target I had the choice between x86_64-unknown-linux-gnu and x86_64-unknown-linux-musl.</p><p>The musl target produces a statically linked binary using the musl C standard library which aims to be very lightweight and simple. The benefit of statically linking the C standard library is that it will run on basically any modern Linux operating system with no dependencies. The drawback is that musl is often quite a bit slower than glibc and therefore not the optimal choice for many projects.</p><p>The gnu target on the other hand produces a dynamically linked binary which depends on glibc being installed on the host system.</p><p>Because glibc is often a bit faster than musl I decided to go with the gnu target. But I will also explain how to build for the musl target.</p><h4>GNU</h4><p>The first step is always to install the standard library using rustup. This is simply done using rustup target add x86_64-unknown-linux-gnu.</p><p>But to actually compile to the given target we also need a linker. For this we will use a homebrew formula provided by the community:</p><pre>brew install SergioBenitez/osxct/x86_64-unknown-linux-gnu</pre><p>Now that the linker is installed we need to tell rustc where to find it. This can be done by updating the <a href="https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure">.cargo/config.toml</a> and adding the linker for the target:</p><pre>[target.x86_64-unknown-linux-gnu]<br>linker = &quot;x86_64-unknown-linux-gnu-gcc&quot;</pre><p>Now you might already be able to compile to the target using cargo build --target x86_64-unknown-linux-gnu, but for many projects, it will also be necessary to set the TARGET_CC environment variable to the linker executable. A full build command could therefore look like this:</p><pre>TARGET_CC=x86_64-unknown-linux-gnu cargo build --release --target x86_64-unknown-linux-gnu</pre><p>This is it! You can now cross-compile from Mac to Linux! <br>Keep in mind that the produced binary is dynamically linked, so you might need to install other dependencies on the host system to make the executable work.</p><h4>MUSL</h4><p>First, we need to install the standard library using rustup. This is simply done by running rustup target add x86_64-unknown-linux-musl.</p><p>To actually compile to the given target we also need a linker. For this we will use a homebrew formular provided by the community:</p><pre>brew install FiloSottile/musl-cross/musl-cross</pre><p>Now that the linker is installed we need to tell rustc where to find it. This can be done by updating the <a href="https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure">.cargo/config.toml</a> and adding the linker for the target:</p><pre>[target.x86_64-unknown-linux-musl]<br>linker = &quot;x86_64-linux-musl-gcc&quot;</pre><p>Now you might already be able to compile to the target using cargo build --target x86_64-unknown-linux-musl, but for many projects it will also be necessary to set the TARGET_CC environment variable to the linker executable. A full build command could therefore look like this:</p><pre>TARGET_CC=x86_64-linux-musl-gcc cargo build --release --target x86_64-unknown-linux-musl</pre><p>That’s it! You can now cross-compile from Mac to Linux.</p><p>The produced binary is statically linked and should run on most modern Linux operating systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fad5a454ab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/cross-compiling-rust-from-mac-to-linux-7fad5a454ab1">Cross-compiling Rust From Mac to Linux</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[90% less disk space]]></title>
            <link>https://blog.xenon.bot/90-less-disk-space-e106996f50bb?source=rss-ae671f5db8f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e106996f50bb</guid>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[discord-bot]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[xenon-bot]]></category>
            <dc:creator><![CDATA[Merlin Fuchs]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 13:00:14 GMT</pubDate>
            <atom:updated>2021-10-18T13:31:32.961Z</atom:updated>
            <content:encoded><![CDATA[<p>How we reduced the disk space usage of our database by almost 90%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*a-t4JbaAq0PzuBgpnHXeew.jpeg" /></figure><p>Xenon saves a lot of data including complete discord servers with server settings, channels, roles, and even bans, members, and messages. To store these information we are using MongoDB, a document-oriented database.</p><p>Disk space was never really a problem with MongoDB, even with over 2.5 Million server backups in our database it barely used 100GB of disk space. While 100GB are easily manageable, reducing the size can still have many advantages. One of the biggest pain points was always migrating the data between servers and backing it up properly. Exporting, uploading, and then importing the data usually took hours to complete.</p><p>This is why we looked into reducing the size of our database and have found two very effective measures that reduced the size of our database by almost 90%.</p><h3>Considerations</h3><p>The “backups” collection is by far the biggest collection in our database. It contains all the server backups and makes up 95% of the stored data. That’s why this collection was the main target to reduce the disk space usage. The following changes depend on two key characteristics of the data that is stored in the “backups” collection:</p><h4>Fixed Format</h4><p>The format of server backups never changed in a substantial way. It rarely happens that new properties are added and basically never that existing ones are changed.</p><p>Server Backups are basically just a huge JSON document that contains all the information that are required to recreate the server. A highly simplified version could look similar to this:</p><pre>{<br>    &quot;name&quot;: &quot;Cool Server&quot;,<br>    &quot;icon&quot;: null,<br>    &quot;channels&quot;: [<br>        {<br>            &quot;id&quot;: &quot;524652984425250847&quot;,<br>            &quot;name&quot;: &quot;general&quot;,<br>            &quot;type&quot;: 0,<br>            &quot;messages&quot;: [...]<br>        }<br>    ],<br>    &quot;roles&quot;: [<br>        {<br>            &quot;id&quot;: &quot;416358583220043796&quot;,<br>            &quot;name&quot;: &quot;@everyone&quot;,<br>            &quot;color&quot;: 0<br>        }<br>    ],<br>    &quot;bans&quot;: [...],<br>    &quot;members&quot;: [...]<br>}</pre><h4>Rarely Accessed</h4><p>Backups are rarely read or written. Most users create a few backups of their server every now and then and only access them when they really need them.</p><h3>BSON -&gt; Protobuf</h3><p>MongoDB uses the data exchange format called “BSON” to store information. BSON stands for “Binary JSON” and aims to store JSON compatible objects in a more compact way. BSON is, in contrast to JSON, not meant to be human readable.</p><p>Protocol buffers on the other hand is a data exchange format developed by Google. In comparison to BSON (and JSON) you have to define a structure for your data beforehand in a specific format which can later be compiled to code in many different programming languages.</p><p>This is how the structure for the JSON object from above could look like in Protobuf:</p><pre><strong>syntax </strong>= &quot;proto3&quot;;</pre><pre><strong>package </strong>xenon.backups;<br><strong><br>message </strong>BackupData {<br>  <strong>message </strong>Role {<br>    <strong>string </strong>id = 1;<br>    <strong>string </strong>name = 2;<br>    <strong>uint32 </strong>color = 3;<br>  }<br>  <strong>message </strong>Channel {<br>    <strong>string </strong>id = 1;<br>    <strong>uint32 </strong>type = 2;<br>    <strong>string </strong>name = 3;<br>  }<br><br>  <strong>string </strong>name = 1;<br>  <strong>string </strong>icon = 2;<br><br>  <strong>repeated </strong>Role roles = 3;<br>  <strong>repeated </strong>Channel channels = 4;<br>}</pre><p>By knowing the exact position, type, and name of each field beforehand Protobuf can achieve way better results than BSON (and JSON) in both speed and size.</p><p>To store Protocol buffers in MongoDB we just serialize them to a byte string which is stored as a field in a normal BSON document. Filtering documents by the fields in the Protobuf byte string is obviously impossible. This is why we store some additional metadata as normal BSON fields that are used to index and query the collection.</p><h3>Pre-Compressing</h3><p>Compression is always a trade-off between speed and compression ratio. For our “backups” collection it makes sense to prioritize compression ratio over speed because documents are rarely read and written.</p><p><a href="https://docs.mongodb.com/manual/core/wiredtiger/">MongoDB uses WiredTiger</a> as the default storage engine which uses <a href="http://google.github.io/snappy/">snappy</a> as the default compression library. Snappy prioritizes speed over compression ratio, which makes sense for most use-cases of MongoDB but isn’t optimal for our “backups” collection.</p><p>Instead of changing the compression algorithm for the whole MongoDB instance we have decided to pre-compress backups before even putting them into MongoDB. The compression algorithm that we are using for this is <a href="https://github.com/google/brotli">Brotli</a>. It’s a general-purpose compression algorithm by Google that achieves one of the best compression ratios while being relatively slow in comparison to algorithms like snappy.</p><p>Brotli can target different compression levels that indicate how aggressive the algorithm works. We have decided to use level 11 for our “backups” collection which is the highest level and therefore offers the best compression ratio. Higher compression levels tend to be a lot slower while compressing data (even less than 1MB/s at level 11) but don’t have a big effect on the decompression speed. This is fine for our use-case because we can easily afford the computation time before storing a backup.</p><p>So in practice all backups go through two compression steps before being written to the disk. First we are compressing the data using Brotli and then put them into MongoDB. The storage engine of MongoDB then compresses it using snappy and writes it to the disk. The results are far better than using snappy alone but require a lot of computation time when a new backup is stored.</p><h3>Conclusion</h3><p>The final document in our “backups” collection could look like this:</p><pre>{<br>    &quot;_id&quot;: &quot;44blidf3s8&quot;,<br>    &quot;timestamp&quot;: ISODate(&quot;2019-12-23T16:43:15.085Z&quot;),<br>    &quot;user_id&quot;: &quot;386861188891279362&quot;,<br>    &quot;guild_id&quot;: &quot;410488579140354049&quot;,<br>    &quot;guild_name&quot;: &quot;WALES&quot;,<br>    &quot;data&quot;: BinData(0, &quot;034IRxQjRGOFeuG18tvcnaueAWRAs ...&quot;)<br>}</pre><p>Where data is the serialized and compressed backup data and the other fields are used to index and query the collection. This allows us to serialize and compress the data to save a lot of disk space while still being able to execute efficient queries.</p><p>These two changes and few smaller tweaks allowed us to save almost 90% of disk space and made it way easier to manage our database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e106996f50bb" width="1" height="1" alt=""><hr><p><a href="https://blog.xenon.bot/90-less-disk-space-e106996f50bb">90% less disk space</a> was originally published in <a href="https://blog.xenon.bot/">Xenon Bot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Rate Limits at Scale]]></title>
            <link>https://blog.xenon.bot/handling-rate-limits-at-scale-fb7b453cb235?source=rss-ae671f5db8f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7b453cb235</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[xenon-bot]]></category>
            <category><![CDATA[discord]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[discord-bot]]></category>
            <dc:creator><![CDATA[Merlin Fuchs]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 21:32:37 GMT</pubDate>
            <atom:updated>2021-10-03T21:35:50.207Z</atom:updated>
            <content:encoded><![CDATA[<p>How Xenon handles Discord rate limits at scale and how we are avoiding to get banned by Cloudflare</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*CTYMxfTAUOZ2xi98rrzahg.png" /></figure><h3>Rate Limits?</h3><p>As you might know the Discords API, like many other APIs, has rate limits to protect it from abuse and spam. For the Discord HTTP API those rate limits come in three different forms: Per-Route, Global and the Invalid-Request-Limit.</p><h4>Per-Route</h4><p>Many endpoints of the Discord API have an per-route rate limit. For example the GET /users/&lt;user_id&gt; endpoint has a per-route rate limit of 30 requests per 30 seconds (1 request per second).</p><p>These rate limits can change at any point and are in most cases communicated by discord through response headers like this:</p><pre>x-ratelimit-limit: 30<br>x-ratelinit-remaining: 29<br>x-ratelimit-reset-after: 30</pre><p>This means that we can handle them easily in our request client and avoid hitting the rate limit. Some per-route rate limits are not communicated through response headers (don’t ask me why) and can not be handled in advance. When you hit such a limit Discord will send you a response with a 429 status code and a JSON body containing a retry_after field. This field indicates when you will be able to use the endpoint again.</p><h4>Global</h4><p>The global rate limit is shared across all endpoints that require authentication and allows 50 requests per seconds by default. Endpoints that don’t require authentication only count into your bots global rate limit if you set the Authorization header on them. Otherwise they will have a separate global rate limit of 50 requests per second which is linked to your IP address.</p><p>Big bots that are in more 250,000 servers can get an increased rate limit which will bump them to 500 requests per second (or more). It’s important to understand that the rate limit increase only affects requests that are made with the Authorization header set.</p><p>This means in practice that it can make sense for bots to make requests to endpoints that don’t require authentication (like webhooks) without the Authorization header set. This will give you two separate global rate limits. You can even load balance the requests across multiple IP addresses to have even more separate rate limits. This only works for endpoints that don’t require authentication tho.</p><h4>Invalid-Request-Limit</h4><p>In addition to the per-route and global rate limit Discord also enforces another rate limit across all endpoints. This rate limit is enforced through Cloudflare and is linked to your IP address. If you make more than 10,000 requests in 10 minutes that result in a status code of 401, 403 or 429 you will be banned from using the API for at least one hour.</p><p>This rate limit should be avoided at all costs because it can literally take down your bot for multiple hours.</p><h3>How do we handle Rate Limits at Xenon?</h3><p>There are different ways to handle rate limits and it depends on how your bot works what is the best for your bot. If you are just running a small bot using libraries like discord.py or discord.js you will never have to think about rate limits at all. These libraries handle all the rate limit work in the background.</p><p>When your bot grows you might feel the need to split your bot into multiple processes. This is where it can get complicated. Depending on how these processes work together you might need to synchronize per-route rate limits and you most likely also need to synchronize the global rate limit across all processes.</p><h4>Synchronization between Processes</h4><p>Synchronizing rate limits between processes can be done in many different ways. One way is to use a shared key-value database like Redis to accomplish this. That is exactly what we are doing at Xenon and this is how it looks in practice:</p><p><strong>Before the request</strong></p><pre>- Client checks if redis contains the key that indicates that the global rate limit was hit<br>- Client waits for the time to live of that key to be over if that key exists</pre><pre>- Client creates a key that uniquely identifies the request route<br>- Client checks the time to live for the request key in Redis (PTTL)<br>- Client checks the remaining value for the request key in Redis (GET)<br>- Client waits for the time to live to be over if the remaining value is 0</pre><p><strong>After the request if the response code is 2XX</strong></p><pre>- Client gets the rate limit information from the response headers<br>- Client puts the remaining value into redis with a time to live that equals to the x-ratelimit-reset-after header (SETEX)</pre><p><strong>After the request if the response code is 429</strong></p><pre>- Client checks if the global rate limit was head<br>- If Global: Client sets a key in redis that indicates that the global rate limit was hit with a time to live that equals to the retry_after value in the responses body (SETEX)<br>- If Per-Route: Client sets the remaining value for the request route in redis to 0 with a time to live that equals to retry_after value in the response body (SETEX)</pre><p>By storing all the rate limit values in a shared key-value storage all processes know about all rate limits at any time. This means that process A knows when process B hit a rate limit on endpoint X and therefore can’t make another request to endpoint X until the rate limit is over.</p><p>Another advantage of storing all rate limit values in a shared key-value storage is that rate limits that last a long time (there are a few that last multiple hours and even days) are tracked and persisted even if a process is restarted.</p><h4>Global Request Proxy</h4><p>In addition to synchronizing rate limits across processes we have recently introduced another system to avoid hitting rate limits. All requests from all processes go through a central request proxy that handles the global rate limit and enforces some additional rules. This is most likely not necessary for most bots but can be helpful if you are making a lot of requests and the synchronization between the processes can’t keep up. Keep in mind that this adds a single point of failure which might not be suitable for some bots.</p><p>There are a few pretty powerful pre-built request proxies for Discord like <a href="https://github.com/twilight-rs/http-proxy">Twilight HTTP-Proxy</a> which can handle per-route rate limits and the global rate limit for you. Using such a proxy can allow you to get rid of synchronizing rate limits across processes because all rate limits are handled by the proxy.</p><p>We have chosen a different and more light weight approach. Instead of a proxy that is specifically designed for the Discord API we are using the reverse-proxy feature of Nginx. Nginx allows us to proxy requests to Discord and enforce the global rate limit. A simple Nginx config for a Discord API proxy can look like this:</p><pre>limit_req_zone $proxy_host zone=global:1m rate=50r/s;</pre><pre>log_format discord_logs &#39;$remote_addr [$time_local] $upstream_http_cf_ray $upstream_http_cf_request_id $upstream_cache_status $status &quot;$request&quot; $body_bytes_sent&#39;;</pre><pre>server {<br>    location / {<br>        limit_req zone=global burst=2000;<br>        limit_req_status 597;</pre><pre>        proxy_set_header Authorization &quot;Bot your-token&quot;;<br>        proxy_pass <a href="https://discord.com/">https://discord.com</a>;<br>        proxy_read_timeout 90;</pre><pre>        client_max_body_size 8M;</pre><pre>        access_log /var/log/nginx/discord_proxy.log discord_logs;<br>    }</pre><pre>    listen 10.0.0.6:8080;<br>}</pre><p>This enforces the global rate limit using limit_req_zone , limits the max body size to 8MB and logs all requests into a file. When the global rate limit of 50 requests per second is reached the proxy will queue up up to 2000 requests and then respond with a 592 status code to all additional requests.</p><p>This works great and makes sure that the global rate limit is never surpassed but we have added some additional rules to do a bit more:</p><pre>limit_req_zone $proxy_host zone=auth_global:1m rate=50r/s;<br>limit_req_zone $proxy_host zone=unauth_global:1m rate=50r/s;</pre><pre>log_format discord_logs &#39;$remote_addr [$time_local] $upstream_http_cf_ray $upstream_http_cf_request_id $upstream_cache_status $status &quot;$request&quot; $body_bytes_sent&#39;;</pre><pre>proxy_cache_path /etc/nginx/cache levels=1:2 keys_zone=entities:10m inactive=60m max_size=5g use_temp_path=off;</pre><pre>server {<br>    location / {<br>        limit_req zone=auth_global burst=2000;<br>        limit_req_status 597;</pre><pre>        proxy_cache entities;<br>        proxy_cache_key $request_method$request_uri;<br>        proxy_cache_methods GET HEAD POST; # PUT DELETE PATCH<br>        proxy_ignore_headers Cache-Control Expires Set-Cookie X-Accel-Expires Vary;<br>        proxy_cache_valid 404 30s;<br>        proxy_cache_valid 401 5s;</pre><pre>        proxy_set_header Authorization &quot;Bot your-token&quot;;<br>        proxy_read_timeout 90;</pre><pre>        client_max_body_size 9M;</pre><pre>        access_log /var/log/nginx/discord_proxy.log discord_logs;</pre><pre>        proxy_pass <a href="https://discord.com/">https://discord.com</a>;</pre><pre>        location /api/v./webhooks/ {<br>            limit_req zone=unauth_global burst=2000;<br>            limit_req_status 597;</pre><pre>            proxy_set_header Authorization &quot;&quot;;<br>            proxy_pass <a href="https://discord.com/">https://discord.com</a>;<br>        }<br>    }</pre><pre>    listen 10.0.0.6:8080;<br>}</pre><p>We have split the global rate limit into two separate buckets. One that counts requests that are linked to the bot (auth_global) and one that counts requests that are linked to the IP (unauth_global). In this example we only count requests to webhook endpoints into the second bucket. There are a few other endpoints that don’t require authentication and could therefore be added here.</p><p>We also added a small cache that currently only caches error responses for requests that result in a 404 or 401 status code. Endpoints that return 404 are very unlikely to not return 404 at any point in the future so it makes sense to cache them. 401 responses indicate that the token is invalid which requires a human to replace the token.</p><p>We could also cache successful responses for some endpoints like users and guilds. But we already have an internal cache at another place so it wouldn’t make sense to add another layer here.</p><blockquote>Thanks to Blue, the developer of “Not Quite Nitro” for providing the idea and initial Nginx config for the request proxy.</blockquote><h3>Conclusion</h3><p>There are many different ways to handle rate limits and the more processes you have that want to interact with the Discord API the more complex it becomes. For 99% of bots it’s fine to just handle rate limits inside the bot process itself. For the remaining 1% it might make sense to look into synchronizing rate limits across processes or to use a central request proxy. (or both)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7b453cb235" width="1" height="1" alt=""><hr><p><a href="https://blog.xenon.bot/handling-rate-limits-at-scale-fb7b453cb235">Handling Rate Limits at Scale</a> was originally published in <a href="https://blog.xenon.bot/">Xenon Bot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 Million servers on a Raspberry Pi]]></title>
            <link>https://blog.xenon.bot/1-million-servers-on-a-raspberry-pi-f02ebfcc329c?source=rss-ae671f5db8f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f02ebfcc329c</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[discord-bot]]></category>
            <category><![CDATA[discord]]></category>
            <dc:creator><![CDATA[Merlin Fuchs]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 21:23:59 GMT</pubDate>
            <atom:updated>2021-08-18T16:13:22.517Z</atom:updated>
            <content:encoded><![CDATA[<p>How we are running one of the biggest discord bots in the world on 2GB of RAM and one CPU core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*zyTOv_9il9Q-wPd7.jpg" /><figcaption>This is a Raspberry Pi</figcaption></figure><blockquote><strong>Disclaimer</strong></blockquote><blockquote>We aren’t actually running Xenon on a Raspberry Pi, but <strong>we could</strong> if we wanted to. A Raspberry Pi 4 with 2GB of RAM would easily be enough to power Xenon with only one exception: the database. <br>The database alone uses around 2GB of RAM to allow for some caching and index building. We would therefore need at least the 4GB RAM model of the Raspberry Pi 4 to also power the database. But that’s beside the point of this blog post.</blockquote><h3>But How?</h3><p>So you might be asking yourself now: How does this even work? It’s actually relatively simple and straight forward.</p><p>Xenon, at its core, is a pretty simple bot. It doesn’t need frequent access to information like channels, roles, or members and also doesn’t need to know when someone sends a message or adds a reaction. All we want to receive from Discord are the commands that you, the user, use to interact with Xenon. This makes Xenon perfect for the use of <a href="https://blog.discord.com/slash-commands-are-here-8db0a385d9e6">Slash Commands</a> and <a href="https://support.discord.com/hc/en-us/articles/1500012250861-Bots-Buttons">Interactions</a>.</p><p>Below I will try to explain in detail how Slash Commands are helping us and how we are avoiding to cache things like guilds, channels and roles.</p><h3>Slash Commands</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1F9Xa3sxKD6DomsT.png" /></figure><p>We recently switched to Slash Commands and shut down our old command handler that was based on normal messages starting with a prefix. <br>Slash Commands have one major advantage for us: We don’t have to process thousands of message events just to receive a few commands. With Slash Commands we only receive the commands and don’t have to worry about discarding all the other events. The switch to Slash Commands alone reduced the CPU usage of Xenon by around 70%.</p><p>You can see a visualization of the difference below. Keep in mind that the graph is scaled logarithmically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ldyebVsoy94Ipxkc.png" /><figcaption>Events per seconds (log2 scale) — No Slash Commands vs. With Slash Commands</figcaption></figure><p>Slash Commands have another nice side effect: You can instruct Discord to send them to you over an HTTPS-Endpoint instead of sending it over a static websocket connection.</p><p>To receive events from Discord you usually need to open one static connection for every thousand servers. This process is called <a href="https://discord.com/developers/docs/topics/gateway#sharding"><em>sharding</em></a>. At one million servers, and therefore around one thousand static connections, it can actually get challenging to keep all those statics connections up and running.</p><p>With Slash Commands you don’t have this issue. You don’t need single a static connection to receive them and can therefore save a lot of resources. <strong>Slash Commands are the reason why we can easily run Xenon on a single CPU core.</strong></p><p>Read more about our decision to switch to Slash Commands here:</p><p><a href="https://blog.xenon.bot/slash-commands-are-here-7b27c6f0dc80">Slash Commands are here!</a></p><h3>Fetching, not Caching</h3><p>To reduce RAM usage we are following one simple principle: Everything that can be fetched is not kept in cache.</p><p>Most discord bots keep a lot of information in their internal cache. Things like servers, channels, roles, and even members are commonly kept in memory to avoid fetching them. For small bots this isn’t an issue but for larger bots it can add up and use a lot of resources. If Xenon would still cache all servers, channels, roles, and members it would most likely use 100GB+ RAM.</p><p>Xenon doesn’t need frequent access to these information can therefore avoid caching them. When we actually need information about a server, channel, role, or member we just fetch it from the Discord API. Xenon is therefore almost entirely stateless with a few small exceptions.</p><p><strong>This is the reason why Xenon uses less than 2GB of RAM.</strong></p><h3>Conclusion</h3><p>We are pretty lucky that we can live without caching any information and don’t need to receive any events. Most discord bots would probably not work without a static connection to discord, but it’s definitely worth putting some thought into what you are keeping in cache.</p><p>Slash Commands are far from being perfect but they also have a lot of advantages over message based commands. A few weeks ago <a href="https://support-dev.discord.com/hc/en-us/articles/4404772028055">Discord has announced that all bots will have to switch to Slash Commands until April of 2022</a>. It’s a good feeling that we don’t have to worry about this anymore.</p><p>It’s a cool thought that we could run Xenon on a single Raspberry Pi, but it’s not a good idea in practice. The network connection, stability and safety of hosted servers can’t be replaced by a single micro controller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f02ebfcc329c" width="1" height="1" alt=""><hr><p><a href="https://blog.xenon.bot/1-million-servers-on-a-raspberry-pi-f02ebfcc329c">1 Million servers on a Raspberry Pi</a> was originally published in <a href="https://blog.xenon.bot/">Xenon Bot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slash Commands are here!]]></title>
            <link>https://blog.xenon.bot/slash-commands-are-here-7b27c6f0dc80?source=rss-ae671f5db8f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b27c6f0dc80</guid>
            <category><![CDATA[slash-commands]]></category>
            <category><![CDATA[backup]]></category>
            <category><![CDATA[discord]]></category>
            <dc:creator><![CDATA[Merlin Fuchs]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 17:56:11 GMT</pubDate>
            <atom:updated>2021-03-31T17:57:43.972Z</atom:updated>
            <content:encoded><![CDATA[<h3>Slash Commands are Here!</h3><h4>In January we already announced that Xenon will make use of Slash Commands as soon as Discord officially releases them. Due to Discord being Discord this date has been delayed by over 2 months, but they are finally here now!</h4><h3>What are Slash Commands?</h3><p>Slash Commands are a completely new way to make Discord Bots. They change the way users interact with a bot and how the bot processes the user input. Commands must be registered and have to follow a relatively strict format, which might even seem limiting at first.</p><p>After a command has been registered it shows up in the Discord client and can be executed by typing / into the text box. Auto completion and argument descriptions make it easy to quickly find commands and use them correctly.</p><figure><img alt="Image of the new Slash Command menu" src="https://cdn-images-1.medium.com/max/1024/1*krQkDB1uYF62z6CUDsjZCg.png" /></figure><p>Read more on the <a href="https://discord.com/developers/docs/interactions/slash-commands">Discord Developer Portal</a>.</p><h3>Our Plans to Switch</h3><p>So why do we want to switch as soon as possible? We believe that most Discord Bots will switch to Slash Commands sooner or later. There are two reasons why we want to switch as soon as possible instead of waiting for the mass adaptation.</p><h4>Infrastructure &amp; Hosting</h4><p>Without Slash Commands we had to create and maintain around 500 websocket connections to receive message and reaction events. These events were necessary to process commands and optionally wait for user input.</p><p>With Slash Commands we theoretically don’t need any of these websocket connections, because Discord sends us the Commands over a webhook. This makes it a lot easier to scale and balance the load to reach maximum availability and reduce the load on our servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9cAfZSRNqsON9cWJrX_0g.png" /><figcaption>Events per Second (log2 scale) — No Slash Commands vs. Slash Commands</figcaption></figure><p>As you can see we reduced the amount of events by around 99.8% and no longer have to maintain hundreds of websocket connections just to process a few commands.</p><h4>User Experience</h4><p>Beside the now obvious benefits for us and our infrastructure, we also see a lot of benefits for the users. The command menu makes it easy for new users to find commands and see how they can be used without having to dig through an endless chain of help commands.</p><figure><img alt="Example for auto-completion, argument description and required arguments" src="https://cdn-images-1.medium.com/max/600/1*VEuFpFrYyGcmMnGuzUUc4w.gif" /><figcaption>Argument descriptions and required arguments</figcaption></figure><h3>Getting Started</h3><p>So you are wondering how to start using Slash Commands? Most commands are pretty similar to their old counterpart, just the prefix changed. Type / into the text box to see all commands.</p><p>You can invite Xenon with all its slash commands by clicking <a href="https://xenon.bot/invite">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZ0JSyOLuCD4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZ0JSyOLuCD4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZ0JSyOLuCD4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4828800922bf43e4cdada6468a22ef37/href">https://medium.com/media/4828800922bf43e4cdada6468a22ef37/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b27c6f0dc80" width="1" height="1" alt=""><hr><p><a href="https://blog.xenon.bot/slash-commands-are-here-7b27c6f0dc80">Slash Commands are here!</a> was originally published in <a href="https://blog.xenon.bot/">Xenon Bot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>