<?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 Roko Kovač on Medium]]></title>
        <description><![CDATA[Stories by Roko Kovač on Medium]]></description>
        <link>https://medium.com/@kova98?source=rss-91bca95035fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g8UWlF7I6q8sreBzVe943A.jpeg</url>
            <title>Stories by Roko Kovač on Medium</title>
            <link>https://medium.com/@kova98?source=rss-91bca95035fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:00:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kova98/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[Why my Saas Failed]]></title>
            <link>https://medium.com/@kova98/why-my-saas-failed-78755fa5a883?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/78755fa5a883</guid>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 14:28:43 GMT</pubDate>
            <atom:updated>2026-01-04T12:22:13.273Z</atom:updated>
            <content:encoded><![CDATA[<h4>And What I Learned From It</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKcuQugRcirraQtQYMTbRw.png" /></figure><h3>Introduction</h3><p>My first attempt at a SaaS, <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>, failed.</p><p>It was an interactive learning platform focusing on .NET content.</p><h3><strong>Quick Stats</strong></h3><ul><li>Time spent: <strong>343 hours</strong></li><li>Money spent: <strong>$300</strong> (rough estimation)</li><li>Revenue: <strong>$0</strong></li></ul><h4><strong>Summary</strong></h4><ul><li>got better at design, marketing, writing, and the tech stack</li><li>got better at prioritizing and making product decisions</li><li>learned how to track product metrics and employ a data driven approach</li></ul><h4>Takeaways:</h4><ul><li>don’t build anything that doesn’t have users from day one</li><li>ask for money early</li><li>payments are the only true validation</li><li>make data driven decisions</li><li>fail or pivot faster</li><li>be brutally realistic about time and scope</li></ul><h3><strong>The Good</strong></h3><p>To start, let’s celebrate the good.</p><p>I learned a lot, had fun, and spent time productively.</p><p>I learned marketable skills which will help me in future projects and in my software engineering career.</p><p>I’ll reap the benefits for years to come, and consider the project to be a net success.</p><h4><strong>Marketing</strong></h4><p>I gained some experience with various marketing tools and got a general idea on how to generate some traffic.</p><p>Reddit has proven to be an amazing source of traffic, but marketing on Reddit requires you to be clever. The paid ads don’t do very well, and posting ads in communities will get you banned quickly. You need to be genuinely helpful and/or mask your ads so they look like organic content.</p><p>This blog has also been a decent source of traffic. I didn’t invest any time into it during the project, but I did put a lot of effort in years ago. It yielded results, but whether it’s worth investing time into it probably depends on the project.</p><p>There is so much more to learn, especially in regards to actually converting the traffic into sales, but I feel like I got a good taste of what tools are available and how to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*zI0RDSoz9SXWwybW8kwbSQ.png" /></figure><h4><strong>Design</strong></h4><p>I got better at designing apps.</p><p>Before Code Interactive, I had no idea how to make anything look remotely decent. I had never built a fully featured landing page. Now, I feel like I can put together a presentable website, using tools familiar to me.</p><p>I’m still working on my design skills, developing taste and a personal style, and have invested some time into it lately. Building Code Interactive has definitely been the spark that I needed to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCk7zFaTvtIbVRG1--Cwng.png" /><figcaption>codeinteractive.dev landing page</figcaption></figure><h4><strong>Tech Stack</strong></h4><p>I got comfortable with Go, which is a big plus as I recently switched to it for my new job.</p><p>I figured out how to set up my own infrastructure and mostly automated it with <a href="https://www.devjourney.io/u/kova98/hatch">hatch</a>. I control it, understand it, and have no fear of surprise bills and rate limits.</p><p>I got more comfortable with the frontend. I moved away from NextJS to a simpler setup (plain React and Astro for landing/marketing) that I understand and can work with. I’m still learning, but I feel much more comfortable.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontent.devjourney.io%2Fkova98%2F87c00653-f457-49c1-aa78-1d1295270561.mp4&amp;type=text%2Fhtml&amp;schema=devjourney&amp;display_name=FlowDrive&amp;src=https%3A%2F%2Fcontent.devjourney.io%2Fkova98%2F87c00653-f457-49c1-aa78-1d1295270561.mp4%3Fembed%3Dtrue" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d479ec14c65f57e01fb20ab8260cd7/href">https://medium.com/media/f5d479ec14c65f57e01fb20ab8260cd7/href</a></iframe><h4><strong>Linux</strong></h4><p>I learned a lot about Linux.</p><p>Experimenting with Firecracker, working extensively with Docker, and building my own orchestrator meant that I spent most of my time in either WSL or docker containers.</p><p>This, in the end, pushed me to switch to Linux completely. It has been one of the biggest productivity boosts for me and has reignited the joy of working with computers that I had as a kid.</p><h4><strong>Journaling</strong></h4><p>As a way to stay motivated and on top of things, I started journaling.</p><p>After a few months, I realized how powerful this was, and decided to share it publicly. It has been a great way of keeping myself accountable and sharing my process.</p><p>I ended up building <a href="https://devjourney.io/">devjourney.io</a> for it, as it was outgrowing my personal website.</p><p>I’ve also started journaling at my day job because of it, and it has been a game changer for me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCB6JbJN9URVd_sbawwrnA.png" /><figcaption>My page on devjourney.io</figcaption></figure><h3><strong>The Bad</strong></h3><p>I made a lot of mistakes. Not all of it was in vain though, as I’ve learned a lot and came out of the project with rich experience and some actionable takeaways.</p><p>I’ll go through the main ones.</p><h4><strong>I Lost the Founder-Product Fit</strong></h4><p>This, I feel, is the biggest one: I lost the founder-product fit.</p><p>When I decided I wanted to build Code Interactive, I was a decently experienced .NET developer. I had been blogging for some time, my following was growing rapidly and I was getting 10k+ monthly views on my blog. I knew the domain, I had an audience, and I loved it. At that time, and even more so now, boot.dev was growing rapidly, and I wanted to build something like that, but for .NET. The project ticked all the boxes and made sense at the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Yo1IybJYT-fP3o42Lae5MA.png" /><figcaption>My growth on Medium at the time</figcaption></figure><p>Fast forward fall 2024 — suddenly I’m no longer writing .NET at work or at home. I’m no longer thinking about design patterns, libraries and nicely packaged utilities. I’m all up in Linux, Go, infrastructure and observability.</p><p>I decided to stick it out, partly due to sunk cost fallacy, but also due to a desire to finish something and gain experience past the tinkering and MVP phase. It was also kind of useful, as I was still writing infrastructure code at the time and was learning actual skills that I ended up using at my day job.</p><p>As soon as the infrastructure was good enough and it was time to focus on content — I hit a wall.</p><p>Somewhere in April 2025 I estimated that I would have to put in at least <strong>200–300 more hours of writing .NET content</strong> — something that just didn’t make sense to do. It wasn’t improving my marketable skills and it wasn’t fun.</p><p>I tried automating this with AI, but all attempts failed as the output was extremely low quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*6NWqlx17TsPdgYaiqyECUA.png" /><figcaption>Last ditch effort: a course generator</figcaption></figure><p>This, added with constant battle against bad actors and alerts, eventually pushed me to shut the project down.</p><p>In the future, before starting any project, I will ask: Do I see myself working on this 2 years from now? If the answer is no, this is not a project for me.</p><h4><strong>Poor Validation / Product Market Fit</strong></h4><p>Now this is the one that’s hard for me to gauge. There was definitely some demand, and my stats show that. People messaged me and signed up for updates. But most of these dropped because there simply wasn’t enough content.</p><p>There’s a competing, validated product really similar to mine. The only difference is the content niche.</p><p>I probably shouldn’t have gone with a new niche for my first real product. A copy of an existing product with a big market would’ve been a better choice, as it would’ve eliminated the risk of validation and product market fit, and helped me learn the ropes and make my first sale.</p><p>Also, I never asked for money, so I never validated if the product is actually needed — I just validated that there’s some interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*79doUfE1VZmXnFBOrIRAxg.png" /><figcaption>People are still trying to access courses — months after disabling them</figcaption></figure><p>Whenever I shared the project in niche communities of my target audience I got <strong>lukewarm responses or none at all</strong>. If I’d had a product-market fit, users would’ve been swarming me. This should’ve been my main cue.</p><p>Finding product-market fit is the hardest thing for me at this stage, just like it is for most others. It is a foundational skill, and something I will have to put more focus on.</p><p>In the future, I will do actual validation. I will ask for money as soon as possible, and not spend too much time on things users don’t actually want. I will not build anything that doesn’t have at least 1 user from day 1. Building for myself, or building alternatives of existing products helps, but there is no validation without payment.</p><h4><strong>Poor Feedback Loops</strong></h4><p>To keep a momentum going, I have found, requires good feedback loops — I create something, make a change, I get feedback. Actionable feedback.</p><p>My courses were far from finished, and the users didn’t stick for too long, so I wasn’t getting a lot of feedback. My idea that users will willingly leave feedback did not result in much — the feedback was mostly bot spam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvVWn3H7cppOOT_RlN1MVg.png" /><figcaption>Bot spam in my feedback form</figcaption></figure><p>In the future, I will focus on getting a few users that I will maintain a relationship with and ask for feedback frequently. Ideally, I would use the product myself from day one.</p><h4><strong>Failed Focus</strong></h4><p>I focused too much on what I thought was interesting, instead of what users actually wanted to do. My <strong>first course</strong>, Testing in .NET, ended up being among the <strong>least favorite</strong> courses clicked on the website.</p><p>I eventually decided to take a data driven approach and actually track which courses are favorites, which helped me focus, but by that time I had wasted a lot of time and effort for basically nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*XskKBoIBRDxv_i35" /><figcaption>My first course (unit testing) was among the least popular</figcaption></figure><p>This is probably the most valuable lesson I’ve learned.</p><p>In the future, I will take a data driven approach with everything I do. I will make experiments, test my assumptions and fail or succeed as soon as possible.</p><h4><strong>Unrealistic expectations</strong></h4><p>I need to be more realistic with what I can achieve.</p><p>Everything I imagined to do with Code Interactive was possible and I would’ve achieved it given more time. But that’s the catch — I don’t have more time.</p><p>I have about 10 hours a week, sometimes less, so I need to plan accordingly. I can either:</p><ul><li><strong>get more resources</strong> (time, money)</li><li><strong>cut quality</strong>, or</li><li><strong>cut scope</strong></li></ul><p>Resources are out of the question. Quality can be cut in some ways, but in the end, the most realistic approach is:</p><ul><li>reducing the scope drastically</li><li>doing what’s left <strong>really well</strong></li></ul><h3><strong>Conclusion</strong></h3><p>I tried, I failed, I learned.</p><p>I’m looking forward to my next project, <a href="https://barelytics.io/">Barelytics</a>, which seems to be much more promising.</p><p>Statistically speaking, there’s a high chance of it failing too. That’s fine, because every failure gets me closer to success — however far away that may be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78755fa5a883" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Apps in .NET with SignalR]]></title>
            <link>https://medium.com/@kova98/real-time-apps-in-net-with-signalr-f4e0381771ab?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4e0381771ab</guid>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 17:05:29 GMT</pubDate>
            <atom:updated>2025-09-22T09:27:10.720Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-Time Apps in .NET with SignalR</h3><h4>Simple, Reliable, and Scalable Real-Time Communication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Covm_e4rdz5YxR0ykYzyg.png" /></figure><h3>Introduction</h3><p>In my previous articles, we explored different ways of achieving real-time communication using many different techniques.</p><p>While it‘s important to know the basics, using a corporate-backed, seasoned, out-of-the-box solution like SignalR makes more sense both engineering and business-wise.</p><p>In this article, we will explore how SignalR works under the hood and expand the chat app from the <a href="https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb">WebSocket article</a> to show just how easy it is to implement advanced features.</p><h3>Why SignalR?</h3><p>The WebSocket protocol, while useful, is very bare bones. This leads to reimplementing the same common features such as connection management, heartbeat, serialization, piping…</p><p>SignalR helps us save time and money by abstracting these technical details so that we can focus on solving business problems.</p><h4>Pros</h4><ul><li>seasoned open-source library, backed by Microsoft</li><li>rich out-of-the-box functionality</li><li>backplane scaling support</li><li>seamless ASP.NET Core integration</li></ul><h4>Cons</h4><ul><li>requires client library, not supported on all platforms</li><li>slight overhead</li></ul><h3>SignalR Features</h3><p>Out of the box, SignalR provides common real-time app features:</p><ul><li>Serialization/Deserialization using JSON or MessagePack</li><li>Persistent connections with automatic reconnection</li><li>Hubs, Groups</li><li>Security using ASP.NET Core Identity</li></ul><h3>How does SignalR Work?</h3><p>Under the hood, SignalR uses three transports, which we already explored: <a href="https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb">WebSocket</a>, <a href="https://medium.com/@kova98/server-sent-events-in-net-7f700b21cdb7">Server-Sent Events</a>, and <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Long Polling</a>.</p><p>Just like with WebSocket, the connection process starts with a <em>handshake</em>, where the best possible transport is negotiated and the final connection is established.</p><p>Unless specifically configured otherwise, <strong>SignalR will always prefer WebSocket</strong>, only falling back to Server-Sent Events if WS isn’t supported and Long Polling as a last resort (rare).</p><h3>Creating a SignalR Server</h3><p>As always, the full code is on my <a href="https://github.com/kova98/BackendCommunicationPatterns.NET/tree/master/SignalR">GitHub</a>.</p><p>Let’s recreate the simple chat app from the <a href="https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb">WebSocket article</a>. You will need to add the SignalR package.</p><p><strong>dotnet </strong>add package Microsoft.AspNetCore.SignalR</p><p>We’ll set up a simple server that will accept connections and broadcast messages to all connected clients.</p><pre><br>using Microsoft.AspNetCore.SignalR;<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddCors(o =&gt;<br>{<br>    o.AddPolicy(&quot;AllowAnyOrigin&quot;, p =&gt; p<br>        .WithOrigins(&quot;null&quot;) // Origin of an html file opened in a browser<br>        .AllowAnyHeader()<br>        .AllowCredentials()); <br>});<br>builder.Services.AddSignalR();<br><br>var app = builder.Build();<br>app.UseCors(&quot;AllowAnyOrigin&quot;);<br>app.MapHub&lt;ChatHub&gt;(&quot;/chatHub&quot;);<br>app.Run();<br><br>public class ChatHub : Hub<br>{<br>    public async Task SendMessage(string message)<br>    {<br>        await Clients.All.SendAsync(&quot;ReceiveMessage&quot;, message);<br>    }<br>}</pre><p>As I will be running the client from a simple HTML file in a browser, I set up the CORS policy accordingly.</p><h3>Creating a SignalR Client</h3><p>Just like with WebSocket, we will create a simple client inside an HTML file. We will have to use the <strong>JavaScript SignalR library</strong>. In this example, I will add the min.js script from a CDN, but in a real-life scenario, you would probably use a package manager.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;SignalR Client&lt;/title&gt;<br>  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;SignalR Client&lt;/h1&gt;<br>  &lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;<br>  &lt;input id=&quot;chatbox&quot;&gt;<br>  &lt;script&gt;<br>    const connection = new signalR.HubConnectionBuilder()<br>      .withAutomaticReconnect()<br>      .withUrl(&quot;http://localhost:5008/chatHub&quot;)<br>      .build();<br><br>    connection.start().then(function () {<br>      document.getElementById(&quot;chatbox&quot;).addEventListener(&quot;keyup&quot;, function (event) {<br>        if (event.key === &quot;Enter&quot;) {<br>          connection.invoke(&quot;SendMessage&quot;, event.target.value);<br>          event.target.value = &quot;&quot;;<br>        }<br>      });<br>    }).catch(function (err) {<br>      return console.error(err.toString());<br>    });<br><br>    connection.on(&quot;ReceiveMessage&quot;, function (message) {<br>      const messages = document.getElementById(&quot;messages&quot;);<br>      messages.innerHTML += `&lt;p&gt;${message}&lt;/p&gt;`;<br>    });<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Just like with WS, we set up a few handlers to send and receive the messages and initialize the connection.</p><p>And just like that, we have a working, auto-reconnecting client that can send and receive messages to our server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yL683dHn-rQCgVIe69b7g.gif" /><figcaption>A simple SignalR client</figcaption></figure><h3>Adding Users and Rooms</h3><p>To demonstrate just how easy it is, let’s expand our chat app. We will make it support users and different rooms.</p><pre>public record User(string Name, string Room);<br>public record Message(string User, string Text);<br><br>public class ChatHub : Hub<br>{<br>    private static ConcurrentDictionary&lt;string, User&gt; _users = new();<br><br>    public override async Task OnDisconnectedAsync(Exception? exception)<br>    {<br>        if (_users.TryGetValue(Context.ConnectionId, out var user))<br>        {<br>            await Groups.RemoveFromGroupAsync(Context.ConnectionId, user.Room);<br>            await Clients.Group(user.Room).SendAsync(&quot;UserLeft&quot;, user.Name);<br>        }<br>    }<br>    <br>    public async Task JoinRoom(string userName, string roomName)<br>    {<br>        _users.TryAdd(Context.ConnectionId, new User(userName, roomName));<br>        await Groups.AddToGroupAsync(Context.ConnectionId, roomName);<br>        await Clients.Group(roomName).SendAsync(&quot;UserJoined&quot;, userName);<br>    }<br>    <br>    public async Task SendMessageToRoom(string roomName, string content)<br>    {<br>        var message = new Message(_users[Context.ConnectionId].Name, content);<br>        await Clients.Group(roomName).SendAsync(&quot;ReceiveMessage&quot;, message);<br>    }<br>}</pre><p>As you can see, using the built in Groups and Context, implementing rooms is trivial.</p><p>In this example, we keep the users simple by just requiring usernames, but for real apps, SignalR integrates with ASP.NET Core Identity seamlessly. We will dive into security in a future series, <a href="https://subscribe.rokokovac.com/">stay tuned</a> for that.</p><p>We’ll handle the new messages on the client side, and add a few cosmetic tweaks. Here I show only the important parts, but you can get the <a href="https://github.com/kova98/BackendCommunicationPatterns.NET/tree/master/SignalR/SignalR.Client">full client code here</a>.</p><pre>document.getElementById(&quot;joinRoom&quot;).addEventListener(&quot;click&quot;, function () {<br>        const roomName = document.getElementById(&quot;roomName&quot;).value;<br>        const userName = document.getElementById(&quot;userName&quot;).value;<br>        connection.invoke(&quot;JoinRoom&quot;, userName, roomName);<br>    });<br><br>    document.getElementById(&quot;messageInput&quot;).addEventListener(&quot;keyup&quot;, function (event) {<br>        if (event.key === &quot;Enter&quot;) {<br>            const message = document.getElementById(&quot;messageInput&quot;).value;<br>            const roomName = document.getElementById(&quot;roomName&quot;).value;<br>            if (message &amp;&amp; roomName) {<br>                connection.invoke(&quot;SendMessageToRoom&quot;, roomName, message);<br>            }<br>        }<br>    });<br><br>    connection.on(&quot;ReceiveMessage&quot;, function (msg) {<br>        const messages = document.getElementById(&quot;messages&quot;);<br>        messages.innerHTML += `&lt;p&gt;${msg.user}: ${msg.text}&lt;/p&gt;`;<br>    });<br>    <br>    connection.on(&quot;UserJoined&quot;, function (msg) {<br>        const messages = document.getElementById(&quot;messages&quot;);<br>        messages.innerHTML += `&lt;p&gt;${msg} has joined.&lt;/p&gt;`;<br>    });<br>    <br>    connection.on(&quot;UserLeft&quot;, function (msg) {<br>        const messages = document.getElementById(&quot;messages&quot;);<br>        messages.innerHTML += `&lt;p&gt;${msg}has left.&lt;/p&gt;`;<br>    });</pre><p>This leaves us with this little gem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wbd4PLSrrAHKUgZlbExRVg.gif" /><figcaption>A more advanced SignalR chat client</figcaption></figure><h3>Conclusion</h3><p>We have concluded the series on real-time communication in .NET by building a simple app in SignalR.</p><p>There are many more advanced topics to tackle, especially when scaling, but the fundamentals learned in these few articles will serve you at every step of the journey.</p><p>If you’re interested in more .NET topics, consider <a href="https://subscribe.rokokovac.com/">subscribing</a>.</p><p>Any thoughts? Leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4e0381771ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSockets in .NET]]></title>
            <link>https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f1fc69bdcb</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 15:17:37 GMT</pubDate>
            <atom:updated>2025-09-22T09:27:43.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebSocket in .NET</h3><h4>Real-Time, Two-Way Communication Over TCP/IP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OXutYfSidHxdxztESvbKQ.png" /></figure><h3>Introduction</h3><p>There are many techniques for achieving near-real-time communication using HTTP, such as Polling, <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Long Polling</a>, <a href="https://medium.com/@kova98/server-sent-events-in-net-7f700b21cdb7">Server-Sent Events</a>, or even <a href="https://medium.com/@kova98/webhooks-in-net-e79530f0d764">Webhooks</a>.</p><p>All approaches share the same issue — they are limited to <strong>one-way </strong>communication.</p><p>In this article, we will explore <strong>WebSocket</strong>, a protocol built on top of TCP/IP that allows <strong>two-way</strong>, <strong>real-time</strong> communication and use it to implement a simple chat app in .NET 8.</p><h3>WebSocket vs Server Sent Events</h3><p>Just like in my previous articles, I will compare WebSocket with the closest alternative — <a href="https://medium.com/@kova98/server-sent-events-in-net-7f700b21cdb7">SSE</a>.</p><h4>Similiarities</h4><p>Both SSE and WebSockets:</p><ul><li>use a single persistent TCP/IP connection</li><li>are supported in all modern browsers</li><li>allow real-time communication</li></ul><h4>Differences</h4><p><strong>Server Sent Events</strong> work with a simple <strong>HTTP </strong>request, which is limited by its Request — Response design to <strong>one-way</strong> communication.</p><p><strong>WebSocket</strong> is a<strong> two-way</strong> (full duplex) real-time communication <strong>protocol </strong>built on top of TCP/IP. It uses an HTTP request to <strong>establish a connection (handshake)</strong>, which is then <strong>upgraded</strong> to a WebSocket connection.</p><p>Unlike SSE, WebSocket also supports <strong>binary</strong> messages.</p><p>This makes it an excellent choice for cases where two-way communication is required, such as a <a href="https://github.com/kova98/Chat">chat app</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*9T9ghdUzWWZcSWPz9vBIuA.png" /><figcaption>Establishing A WebSocket Connection</figcaption></figure><h3>Implementing a WebSocket Server</h3><p>Let’s build a simple WebSocket server in .NET 8.</p><p>If you just want the code, you can get it on my <a href="https://github.com/kova98/BackendCommunicationPatterns.NET">GitHub</a>.</p><p>First, we will set up a web server and the required dependencies.</p><pre>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddSingleton&lt;ChatService&gt;();<br>var app = builder.Build();<br>app.UseWebSockets();</pre><p>Then, we add a simple endpoint that will check for <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#client_handshake_request">the required headers</a> to determine if it’s a WebSocket request, and if so, accept it and pass it onto our <strong>ChatService</strong>.</p><pre>app.MapGet(&quot;/&quot;, async (HttpContext context, ChatService chatService) =&gt;<br>{<br>    if (context.WebSockets.IsWebSocketRequest)<br>    {<br>        var webSocket = await context.WebSockets.AcceptWebSocketAsync();<br>        await chatService.HandleWebSocketConnection(webSocket);<br>    }<br>    else<br>    {<br>        context.Response.StatusCode = 400;<br>        await context.Response.WriteAsync(&quot;Expected a WebSocket request&quot;);<br>    }<br>});</pre><p>In the ChatService, we will handle the WebSocket connection. It’s a singleton service that keeps track of all connected clients.</p><pre>public class ChatService<br>{<br>    private readonly List&lt;WebSocket&gt; _sockets = new();<br>    <br>    public async Task HandleWebSocketConnection(WebSocket socket)<br>    {<br>        _sockets.Add(socket);<br>        var buffer = new byte[1024 * 2];<br>        while (socket.State == WebSocketState.Open)<br>        {<br>            var result = await socket.ReceiveAsync(new ArraySegment&lt;byte&gt;(buffer), default);<br>            if (result.MessageType == WebSocketMessageType.Close)<br>            {<br>                await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, default);<br>                break;<br>            }<br>            <br>            foreach (var s in _sockets)<br>            {<br>                await s.SendAsync(buffer[..result.Count], WebSocketMessageType.Text, true, default);<br>            }<br>        }<br>        _sockets.Remove(socket);<br>    }<br>}</pre><p>While the WebSocket is open, we await the next message. If it’s a Close message, we simply close the connection. If not, we read it and <strong>write it into an allocated buffer</strong>.</p><p>We then take <strong>a slice of the buffer</strong> that contains the message and send it to all connected clients.</p><p>To keep it simple, we don’t validate message type or message size, or serialize/deserialize to domain entities, which is something you would probably want to do <a href="https://github.com/kova98/Chat/blob/main/Chat.Api/WebSocketAdapter.cs#L59">in a real application</a>.</p><h3>Implementing a WebSocket Client</h3><p>As it’s supported by all browsers, we will use HTML and JavaScript to build a client.</p><pre>&lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;<br>&lt;input id=&quot;chatbox&quot; &gt;<br>&lt;script&gt;<br>    const socket = new WebSocket(&#39;ws://localhost:5007&#39;);<br>    <br>    socket.onmessage = function (event) {<br>        const messages = document.getElementById(&quot;messages&quot;);<br>        messages.innerHTML += `&lt;p&gt;${event.data}&lt;/p&gt;`;<br>    };<br><br>    document.getElementById(&quot;chatbox&quot;).addEventListener(&quot;keyup&quot;, function(event) {<br>        if (event.key === &quot;Enter&quot;) {<br>            socket.send(event.target.value);<br>            event.target.value = &quot;&quot;;<br>        }<br>    });<br>&lt;/script&gt;</pre><p>This simple code opens up a WebSocket connection and displays something resembling a chat application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOsIkufLNg5M50NbP-9n3g.gif" /><figcaption>A Simple Chat App</figcaption></figure><h3>Conclusion</h3><p>I have introduced you to the WebSocket protocol and shown you how to implement a simple WebSocket server in .NET 8</p><p>For a more advanced use case, check out my <a href="https://github.com/kova98/Chat/tree/main">chat app</a>.</p><p>If you’re interested in .NET topics, consider <a href="https://subscribe.rokokovac.com/">subscribing</a>.</p><p>Any thoughts? Comments are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f1fc69bdcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Sent Events in .NET]]></title>
            <link>https://medium.com/@kova98/server-sent-events-in-net-7f700b21cdb7?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f700b21cdb7</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 15:09:36 GMT</pubDate>
            <atom:updated>2025-09-22T09:28:02.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Server-Sent Events in .NET</h3><h4>Implementing The Most Elegant HTTP-Based Push Mechanism</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unac79HeHrIwqTq0EvvpYQ.png" /></figure><h3>Introduction</h3><p>To achieve near-real-time communication over HTTP, a few techniques emerged, such as Polling, <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Long Polling</a>, or even <a href="https://medium.com/@kova98/webhooks-in-net-e79530f0d764">Webhooks</a>.</p><p>However, all of them come with limitations, and none of them maintain a <strong>consistent connection</strong> with <strong>instantaneous server push</strong>.</p><p>In this article, we will explore the most elegant HTTP-Based server push mechanism — <strong>Server-Sent Events</strong> and implement it in<strong> .NET 8</strong>.</p><h3>Server-Sent Events vs Long Polling</h3><p>SSE is often compared to <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Long Polling</a> and can be seen as an alternative.</p><p>While both techniques are HTTP-based and provide seemingly the same end result, there are a few distinct differences.</p><h4>Similarities</h4><p>Both SSE and <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Long Polling</a>:</p><ul><li><strong>enable near-real-time communication over HTTP/1.1</strong>,</li><li><strong>are one way </strong>(an HTTP/1.1 limitation)</li><li><strong>require a specific implementation</strong> (cannot be used with existing HTTP endpoints)</li><li><strong>keep an HTTP connection open</strong></li></ul><h4>Differences</h4><p>Just like <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Long Polling</a>, SSE maintains an open HTTP/1.1 connection. The main difference is in what happens when new information arrives.</p><p>While a <strong>Long Polling</strong> request will <strong>finish</strong> as soon as new information arrives, acting like a regular, long-lasting request, an <strong>SSE</strong> request <strong>stays open</strong> until the client or the server decides to finish it, and the new information is simply <strong>written to the buffer.</strong></p><p>This makes it suitable for <strong>high-frequency updates</strong>, which is one of the problems with Long Polling.</p><p>Put simply, <strong>SSE</strong> is a technique that allows real-time server push over HTTP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av8iMEhoSeM3aTwN6vTR0Q.png" /><figcaption>Server-Sent Events</figcaption></figure><h3>Server-Sent Events Caveats</h3><p>There are a few caveats to watch out for when using SSE.</p><h4>Request Timeouts</h4><p>Most web servers have a request timeout configured. For example, <strong>Nginx </strong>defaults <strong>proxy_read_timeout </strong>to <strong>60 seconds</strong>. Depending on your needs and restrictions, you might need to increase this or implement client-side retry mechanisms.</p><h4>Additional Server Configuration</h4><p>Depending on the server, you might need to configure various caching and buffering mechanisms. For example, an app behind an Nginx<strong> </strong>reverse proxy<strong> </strong>will not work if chunked_transfer_encoding, proxy_buffering, or proxy_cache are enabled.</p><h4>Browser connection limitations</h4><p>Most modern browsers have a limit of <strong>6</strong> <strong>active connections per domain. </strong>All requests beyond this limit will stall. Keep this in mind when opening an SSE request, since stalled connections can slow down your website significantly.</p><h3>SSE Message Format</h3><p>A full SSE response format, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#browser_compatibility">supported by all modern browsers</a>, will look something like this.</p><h4>Headers</h4><p>The only required header is the <strong>Content-Type:</strong> <strong>text/event-stream, </strong>which indicates to the client that it’s an SSE response.</p><pre>HTTP/1.1 200 OK<br>Content-Type: text/event-stream</pre><h4>Body</h4><p>A body consists of multiple messages, with data prefixed by “<strong>data: </strong>” and event names prefixed by “event: “. You can send both named or unnamed messages with one or more lines, but each line must be prefixed by “<strong>data</strong>: “</p><pre>event: itemCreated<br>data: {&quot;name&quot;: &quot;bucket&quot;, &quot;Price&quot;: &quot;114.50&quot;}<br><br>data: Here&#39;s an example of a multi-line message <br>data: returned piece by piece by a <br>data: chatbot application. </pre><h3>Implementing Server-Sent Events in .NET</h3><p>Let’s implement a simple SSE endpoint in .NET 8.</p><p>if you just want the code, <a href="https://github.com/kova98/BackendCommunicationPatterns.NET">you can find it on my GitHub</a>.</p><pre>app.MapGet(&quot;/&quot;, async (HttpContext ctx, ItemService service, CancellationToken ct) =&gt;<br>{<br>    ctx.Response.Headers.Add(&quot;Content-Type&quot;, &quot;text/event-stream&quot;);<br>    <br>    while (!ct.IsCancellationRequested)<br>    {<br>        var item = await service.WaitForNewItem();<br>        <br>        await ctx.Response.WriteAsync($&quot;data: &quot;);<br>        await JsonSerializer.SerializeAsync(ctx.Response.Body, item);<br>        await ctx.Response.WriteAsync($&quot;\n\n&quot;);<br>        await ctx.Response.Body.FlushAsync();<br>            <br>        service.Reset();<br>    }<br>});</pre><p>The code is pretty straightforward. While the request is not canceled, we wait for the new item, serialize the message and <strong>write it directly into the response buffer </strong>in the standard format.</p><p>We also make sure to include the <strong>Content-Type: text/event-stream </strong>header.</p><p>The <strong>ItemService </strong>class is a <strong>Singleton service </strong>that provides a <strong>Task Completion Source </strong>that could get triggered from a separate process, eg. an event handler or a call from another service.</p><p>After writing a new item message to the buffer, we make sure to <strong>reset</strong> the Task Completion Source so that we can wait for the next one.</p><p>Here is a simple ItemService to demonstrate the implementation.</p><pre>public record Item(string Name, double Price);<br><br>public class ItemService<br>{<br>    private TaskCompletionSource&lt;Item?&gt; _tcs = new();<br>    private long _id = 0;<br>    <br>    public void Reset()<br>    {<br>        _tcs = new TaskCompletionSource&lt;Item?&gt;();<br>    }<br><br>    public void NotifyNewItemAvailable()<br>    {<br>        _tcs.TrySetResult(new Item($&quot;New Item {_id}&quot;, Random.Shared.Next(0, 500)));<br>    }<br><br>    public Task&lt;Item?&gt; WaitForNewItem()<br>    {<br>        // Simulate some delay in Item arrival<br>        Task.Run(async () =&gt;<br>        {<br>            await Task.Delay(TimeSpan.FromSeconds(Random.Shared.Next(0, 29)));<br>            NotifyNewItemAvailable();<br>        });<br>        <br>        return _tcs.Task;<br>    }<br>}</pre><p>If you want to see it in action alongside other transports, check out this<a href="https://github.com/kova98/Chat"> Chat app</a>.</p><h3>Implementing an SSE Client</h3><p>All browsers support the standard EventSource API, which makes using an SSE endpoint a breeze.</p><pre>const eventSource = new EventSource(&#39;http://localhost:5006/sse&#39;);<br><br>eventSource.onmessage = function (event) {<br>    const item = JSON.parse(event.data);<br>    console.log(&quot;New item received:&quot;, item);<br>};</pre><h3>Conclusion</h3><p>I have shown you how to implement the most elegant server push over HTTP technique— Server-Sent Events.</p><p>Albeit rarer than other techniques like WebSockets, it still has very strong and recent use cases, such as <strong>ChatGPT</strong> using it to stream chat responses, or <strong>SignalR</strong> using it as a fallback when WebSockets aren’t available.</p><p>In the following articles, we will move beyond HTTP and explore the <strong>WebSocket </strong>and<strong> gRPC </strong>protocols to implement two-way real-time communication.</p><p>If you’re interested in reading about those, consider <a href="https://subscribe.rokokovac.com/">subscribing</a>.</p><p>Any thoughts? Comments are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f700b21cdb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Long Polling in .NET]]></title>
            <link>https://medium.com/@kova98/long-polling-in-net-08caa91000cd?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/08caa91000cd</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[polling]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 14:23:00 GMT</pubDate>
            <atom:updated>2024-12-31T09:09:57.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Long Polling in .NET</h3><h4>Implementing a More Efficient Polling Technique</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnrAOGU2M-uNmJ7BihyGtA.png" /></figure><h3>Introduction</h3><p><strong>Polling</strong> is a simple way to provide near-real-time updates using HTTP requests. However, in many cases, it can result in many empty responses and wasted resources.</p><p>In this article, I will introduce you to a more efficient way of polling for updates—<strong> Long Polling, </strong>and show you how to implement it in .NET.</p><p>Bored of reading? Try my interactive tutorials over at <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>!</p><h3>Polling vs Long Polling</h3><h4><strong>Polling</strong></h4><p>Polling consists of <strong>sending requests</strong> in set <strong>intervals</strong> to get updates.</p><p>It is the <strong>simplest </strong>way to implement <strong>near-real-time updates</strong> using HTTP requests.</p><p>The biggest advantage over other options is that the backend doesn’t need to implement anything special for it to work. You can poll <strong>any existing HTTP endpoint</strong>.</p><p>A real-life example is a client polling a server to check if any new items arrived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c2mhqXEVt5-ksUgr.png" /><figcaption>Polling</figcaption></figure><h4>Long Polling</h4><p>Just like Polling, Long Polling consists of <strong>sending requests</strong> in set <strong>intervals</strong> to get updates.</p><p>The <strong>difference</strong> between polling and long polling is that the server <strong>keeps the connection open </strong>and finishes the request <strong>only when there’s an update</strong> or the <strong>timeout</strong> is reached.</p><p>This way, fewer resources are wasted on chatty communication between the client and server.</p><p>The disadvantage, compared to polling, is that the server needs to implement it. You <strong>cannot long poll existing HTTP endpoints</strong> if the server doesn’t support it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5WGtTp6kC5pDfPJsxU0RA.png" /><figcaption>Long Polling</figcaption></figure><h3>Long Polling Caveats</h3><p>There are a few caveats to consider before choosing to use long polling.</p><h4>Not suited for high-frequency updates</h4><p>If the updates are more frequent than the polling frequency, long polling will essentially result in a regular poll. This makes it a viable option only in cases where updates are not as frequent.</p><h4>Browser connection limitations</h4><p>Most modern browsers have a limit of <strong>6 active connections per domain. </strong>All requests beyond this limit will stall. Keep this in mind when opening a long polling request, since stalled connections can slow down your website significantly.</p><h4>Resource consumption</h4><p>Depending on your server, it could be more suited for frequent short-lived connections than less frequent long-lived connections.</p><h3>Implementing Long Polling in .NET</h3><p>Let’s implement a simple long polling endpoint in .NET 8.</p><p>If you just want the code, <a href="https://github.com/kova98/BackendCommunicationPatterns.NET">you can find it on my GitHub</a>.</p><pre>app.MapGet(&quot;/&quot;, async (CancellationToken userCt, ItemService itemService) =&gt;<br>{<br>    var cts = CancellationTokenSource.CreateLinkedTokenSource(userCt);<br>    cts.CancelAfter(TimeSpan.FromSeconds(30));<br><br>    while (!cts.IsCancellationRequested)<br>    {<br>        if (itemService.AnyNewItems())<br>        {<br>            return Results.Ok(itemService.GetNewItem());<br>        }<br>        <br>        // smaller delay makes server more responsive, but decreases performance<br>        await Task.Delay(50);<br>    }<br><br>    return Results.NoContent();<br>});</pre><p>As you can see, the code is pretty simple. We create a <strong>linked Cancellation Token Source </strong>so that the loop can be canceled by the user, as well as the timeout.</p><p>We set up a <strong>30-second timeout</strong>.</p><p>While the cancellation is not requested, we check if there’s a new item. If there is, we return the item with a <strong>200 Ok</strong> result and complete the request.</p><p>On timeout, we return a <strong>204 No Content</strong> result to let the client know the request timed out and they should send a new one.</p><h4>A more efficient implementation</h4><p>This implementation is fine if the ItemService does an in-memory check, such as checking a message buffer in <a href="https://github.com/kova98/Chat">a chat application</a>.</p><p>However, most production apps persist data in a database. In this case, the ItemService should be a <strong>Singleton service </strong>that provides a <strong>Task Completion Source </strong>that could get triggered from a separate process, eg. an event handler or a call from another service.</p><pre>app.MapGet(&quot;/&quot;, async (CancellationToken userCt, ItemService itemService) =&gt;<br>{<br>    var cts = CancellationTokenSource.CreateLinkedTokenSource(userCt);<br>    cts.CancelAfter(TimeSpan.FromSeconds(30));<br>    <br>    var timeoutTask = Task.Delay(-1, cts.Token);<br>    var itemArrivedTask = itemService.WaitForNewItem();<br>    <br>    var completedTask = await Task.WhenAny(itemArrivedTask, timeoutTask);<br>    if (completedTask == itemArrivedTask)<br>    {<br>        var item = await itemArrivedTask;<br>        itemService.Reset();<br>        return Results.Ok(item);<br>    }<br><br>    return Results.NoContent();<br>});</pre><p>In this implementation, we do the same as before, except, instead of waiting in a while loop, we wait for <strong>either </strong>the <strong>itemArrivedTask</strong> or a <strong>new Task with our cancellation token</strong> to complete.</p><p>When either of them is completed, we return a result based on which one it is.</p><p>Before returning a new item, we make sure to <strong>reset</strong> the Task Completion Source so it can be reused — remember, the service is a Singleton.</p><h3>Conclusion</h3><p>I have shown you how to implement a more efficient polling technique in .NET.</p><p>Even though this is a really niche technique and not used very often, it is important for every backend engineer to be familiar with it.</p><p>Fun fact: <strong>SignalR</strong> uses Long Polling as the last fallback!</p><p>In the following articles, we will explore other options that are preferred, such as<strong> Server-Sent Events</strong> and <strong>WebSockets.</strong></p><p>Are you interested in reading about those? Consider <a href="https://subscribe.rokokovac.com/">subscribing</a>.</p><p>Any thoughts? Comments are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08caa91000cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pub-Sub in .NET with MassTransit]]></title>
            <link>https://medium.com/@kova98/pub-sub-in-net-with-masstransit-44cb27024497?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/44cb27024497</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 07:08:18 GMT</pubDate>
            <atom:updated>2024-12-31T09:10:05.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pub-Sub in .NET with MassTransit</h3><h4>Integrating Scalable, Distributed .NET Systems With RabbitMQ</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCm9ZeEwCw2oFm4ClX2HcQ.png" /></figure><h3>Introduction</h3><p>There are many ways to implement backend communication using HTTP Request-Response, ranging from simple techniques like <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">Short and Long Polling</a>, to more sophisticated, push-like patterns such as <a href="https://medium.com/@kova98/server-sent-events-in-net-7f700b21cdb7">Server-Sent Events</a> or <a href="https://medium.com/@kova98/webhooks-in-net-e79530f0d764">Webhooks</a>.</p><p>However, there comes a point when you hit a ceiling with Request-Response and simply need a performant, scalable, full-blown Pub-Sub messaging system.</p><p>In this article, I will cover what problems Pub-Sub solves, and a high-level implementation in .NET using a very useful library called MassTransit.</p><p>Bored of reading? Try my interactive tutorials over at <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>!</p><h3>Publish-Subscribe</h3><p>Publish-Subscribe, or Pub-Sub in short, is a messaging pattern that solves many problems inherent to Request-Response.</p><h4>Asynchronous communication</h4><p>Request-Response is synchronous by nature, which poses an issue when solving problems that require asynchronous behavior.</p><p>It is possible to implement asynchronous communication with Request-Response using something like <a href="https://medium.com/@kova98/webhooks-in-net-e79530f0d764">webhooks</a>, but such solutions don’t scale very well and come with another important problem — tight coupling.</p><h4>Decoupling Senders from Receivers</h4><p>A Publish-Subscribe system decouples the <strong>publishers</strong> (senders) of the messages from the <strong>subscribers</strong> (receivers) by introducing a middleman.</p><p>Not only does this allow for multiple senders and receivers to send messages to each other, but it also makes the system more resilient to change and easier to <strong>scale</strong>.</p><h4>Scalability</h4><p>As the subscribers are decoupled from the publishers, scaling becomes much simpler. If you need to process messages faster, you can simply add more subscribers. Want to have multiple sources of a single event? Add more publishers.</p><h3>The Key Components</h3><p>There are a few key components in every message broker implementation.</p><h4>Message</h4><p>The source of information. It usually represents a domain event, e.g. an item being created.</p><h4>Broker</h4><p>This is a generic term for a messaging middleman. It receives messages and knows how and where to forward them.</p><h4>Producer</h4><p>A Producer (sender, publisher) <strong>produces </strong>messages to the broker<strong>.</strong></p><h4>Consumer</h4><p>A Consumer (receiver, subscriber) <strong>consumes </strong>messages from the broker<strong>.</strong></p><h4>Queue</h4><p>A queue is a buffer between producers and consumers. This is where the messages stay until they’re consumed.</p><p>It typically operates as any other queue — first in, first out.</p><p>Multiple consumers can consume messages from a single queue, but a single message can be consumed from a queue only once.</p><h4>Topic</h4><p>A topic is the central point of a message broker Pub-Sub system. It forwards messages to all queues that are <strong>subscribed </strong>to that specific topic.</p><h4>Subscription</h4><p>A subscription, or <strong>binding, </strong>is the connection between a queue and a topic. Each queue that is interested in a topic needs to <strong>subscribe </strong>to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjsOojQo7D-uq6ZhAYSZJQ.png" /><figcaption>A typical Pub-Sub System using a Message Broker</figcaption></figure><p>With the general terminology out of the way, we can take a closer look at RabbitMQ.</p><h3>RabbitMQ</h3><p>RabbitMQ is a popular and feature-rich, open-source message broker.</p><p>Because of the amount of features it supports, it can be overwhelming to work with when first starting out. However, MassTransit makes it really easy to set up efficient Pub-Sub messaging with just a few lines of code.</p><h3>Exchanges</h3><p>Without going into too much detail on RabbitMQ, let’s go over some basics of exchanges so that we can understand the default MassTransit message topology.</p><p>In RabbitMQ, <strong>exchanges </strong>are the middlemen between producers and queues. They are the equivalent of the Topic we defined earlier, with a few caveats.</p><p>There are 3 types of exchanges, each with a different way of routing messages. The 3 types are <strong>direct</strong>, <strong>fanout </strong>and <strong>topic</strong>. In addition, exchanges can also bind to each other, allowing for complex routing rules.</p><p><strong>MassTransit </strong>mainly uses <strong>fanout exchanges</strong>, which is an exchange that simply routes messages to <strong>all bound queues and exchanges</strong>.</p><p>Exchanges can be <strong>durable </strong>(persisted on disk, survive restarts), or <strong>transient </strong>(persisted in memory, don’t survive restarts).</p><h3>Message Topology</h3><p>MassTransit follows the design principle of <a href="https://martinfowler.com/articles/microservices.html#SmartEndpointsAndDumbPipes">Smart Endpoints and Dumb Pipes</a>, using the broker only for the basic delivery of messages, and keeping the routing rules on it to the bare minimum.</p><p>MassTransit will create a <strong>durable</strong>, <strong>fanout</strong> <strong>exchange </strong>for each <strong>message type</strong> and a <strong>durable</strong>, <strong>fanout</strong> <strong>exchange </strong>for each <strong>queue.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*qohu4brRc0XyX7CIPdBkpw.png" /><figcaption>A default MassTransit RabbitMQ message topology</figcaption></figure><h3>Single Queue Per Consumer Type</h3><p>MassTransit creates a queue for each consumer type, which is important in a Pub-Sub system.</p><p>To understand why, let’s go over a real-life example.</p><p>In a service-oriented architecture, if you want to scale up a service to handle increased traffic, you simply spin up another replica of the service (Consumer 2 on the diagram above).</p><p>You want these two replicas (Consumer 2.1 and Consumer 2.2) to share the load of processing the ItemCreated message. This is done by subscribing them to the same queue. Since a single message in a queue can be consumed only once, the queue effectively becomes a <strong>load balancer</strong>.</p><p>On the other hand, you wouldn’t want a service (Consumer 1) to miss a message because the other service (Consumer 2) consumed it. This is why you need a separate queue for each consumer type.</p><h3>Naming</h3><p>MassTransit requires all contracts to be defined within a namespace, and uses that namespace when creating exchanges.</p><p>For example, if we define an <strong>ItemCreated </strong>message in a namespace called <strong>Contracts</strong>, the exchange for that message will be called <strong>Contracts:ItemCreatedMessage.</strong></p><p>The consumer exchange and queue are named after the message type, in this case, <strong>ItemCreatedMessage</strong>.</p><p>If you don’t like these conventions, you can configure them in the setup. To keep things simple, we will use the default convention.</p><h3>Creating The Project</h3><p>If you want to skip creating the project yourself, the<strong> source code </strong>is on my <a href="https://github.com/kova98/BackendCommunicationPatterns.NET">GitHub</a>.</p><p>We’re going to create three projects: Producer, Consumer, and Contracts.</p><pre>dotnet new console -n Producer<br>dotnet new console -n Consumer<br>dotnet new classlib -n Contracts</pre><p>For the Producer and Consumer, we’re going to need some packages.</p><pre>dotnet add package MassTransit.RabbitMQ<br>dotnet add package Microsoft.Extensions.DependencyInjection</pre><p>If you don’t have a RabbitMQ instance running, you can run it on your local machine easily using Docker.</p><pre>docker run -d --name rabbitmq -p 15672:15672 -p 5672:5672 rabbitmq:management</pre><h3>Defining The Contract</h3><p>In the Contracts project, we will define the ItemCreatedMessage. We’re keeping it simple with just a Name and a Price.</p><p>Keep in mind, contracts are required to be within a namespace.</p><pre>namespace Contracts;<br><br>public record ItemCreatedMessage(string Name, double Price);</pre><h3>Creating a RabbitMQ Producer</h3><p>Let’s create a RabbitMQ producer and set it up to publish the ItemCreatedMessage on keypress.</p><p>We will connect to the local RabbitMQ instance and use the default endpoint configuration.</p><p>It is possible to create an IBusControl without using the service collection, but we will use it to keep the code consistent with an ASP.NET Core app.</p><pre>using MassTransit;<br>using Contracts;<br>using Microsoft.Extensions.DependencyInjection;<br><br>var services = new ServiceCollection();<br>services.AddMassTransit(x =&gt;<br>{<br>    x.UsingRabbitMq((context, cfg) =&gt;<br>    {<br>        cfg.Host(&quot;localhost&quot;, &quot;/&quot;, h =&gt;<br>        {<br>            h.Username(&quot;guest&quot;);<br>            h.Password(&quot;guest&quot;);<br>        });<br>        cfg.ConfigureEndpoints(context);<br>    });<br>});<br><br>var serviceProvider = services.BuildServiceProvider();<br>var bus = serviceProvider.GetRequiredService&lt;IBusControl&gt;();<br>await bus.StartAsync(); <br><br>Console.WriteLine(&quot;Press any key to send a message...&quot;);<br>while (true)<br>{<br>    Console.ReadKey(true);<br>    await bus.Publish(new ItemCreatedMessage(Name: &quot;Bucket&quot;, Price: 12.55));<br>    Console.WriteLine(&quot;Message sent.&quot;);<br>}</pre><h3>Creating a Consumer</h3><p>In the Consumer project, we will define the consumer class.</p><p>The consumer interface is very simple, it requires a single Consume method that accepts the context with the message type.</p><p>In the Consume method, we will simply print out the created item info.</p><pre>using MassTransit;<br>using Contracts;<br><br>namespace Consumer;<br><br>public record ItemCreatedMessageConsumer : IConsumer&lt;ItemCreatedMessage&gt;<br>{<br>    public Task Consume(ConsumeContext&lt;ItemCreatedMessage&gt; context)<br>    {<br>        Console.WriteLine(<br>            $&quot;Item &#39;{context.Message.Name}&#39; &quot; +<br>            $&quot;with price &#39;{context.Message.Price}&#39; created.&quot;);<br><br>        return Task.CompletedTask;        <br>    }<br>}</pre><p>In the Program.cs, we will use a similar setup as with the producer.</p><p>We connect to the local RabbitMQ instance and use the default convention-based endpoint configuration. This will create our exchange and queue (if they don’t exist), open a connection, and bind our consumer to the queue.</p><pre>using MassTransit;<br>using MessageBroker.Consumer;<br>using Microsoft.Extensions.DependencyInjection;<br><br>var services = new ServiceCollection();<br><br>services.AddMassTransit(x =&gt;<br>{<br>    x.AddConsumer&lt;ItemCreatedMessageConsumer&gt;();<br>    <br>    x.UsingRabbitMq((context, cfg) =&gt;<br>    {<br>        cfg.Host(&quot;localhost&quot;, &quot;/&quot;, h =&gt;<br>        {<br>            h.Username(&quot;guest&quot;);<br>            h.Password(&quot;guest&quot;);<br>        });<br><br>        cfg.ConfigureEndpoints(context);<br>    });<br>});<br><br>var serviceProvider = services.BuildServiceProvider();<br>var bus = serviceProvider.GetRequiredService&lt;IBusControl&gt;();<br>await bus.StartAsync();<br><br>Console.WriteLine(&quot;Waiting for messages...&quot;);<br>Console.ReadLine();</pre><p>Let’s try to run this and see if it works. We will run a single Producer and a single Consumer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CqKZKzQZngsZSHKgmqCaQ.png" /><figcaption>One Producer, One Consumer</figcaption></figure><p>Looks good. Let’s try with multiple consumers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdkB6EME88VX3ZY7nugRzA.png" /><figcaption>One Producer, Multiple Consumers</figcaption></figure><p>As you can see, we sent two messages but they each got a single message.</p><p>This is because we used the default endpoint configuration in our Consumer setup, which means MassTransit bound both of our consumers to the same queue: ItemCreatedMessage.</p><p>If you’re developing a microservice, this is probably the behavior you would want. You want to balance the load equally between all replicas of the same service. In the context of the diagram we looked at earlier, these would be the Consumer 2.1 and Consumer 2.2.</p><p>However, just to test that our Pub/Sub setup is working, let’s add a queue parameter</p><pre>Console.Write(&quot;Enter queue name: &quot;);<br>var queue = Console.ReadLine();</pre><p>…and configure the endpoint manually.</p><pre>// cfg.ConfigureEndpoints(context);<br>cfg.ReceiveEndpoint(queue, e =&gt;<br>{<br>    e.Consumer&lt;ItemCreatedMessageConsumer&gt;();<br>});</pre><p>Let’s try running them now. We will recreate the setup from the diagram we looked at earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDtgOSSDHTmUPxZO7S595Q.png" /><figcaption>One Producer, Multiple Consumer Types, Multiple Consumers</figcaption></figure><p>When sending two messages, Consumer 1, which is bound to queue 1, received both of them.</p><p>On the other hand, Consumer 2.1 and Consumer 2.2 received one message each, since they’re bound to the same queue — queue 2.</p><h3>Conclusion</h3><p>I have shown you how to quickly set up a RabbitMQ Producer and Consumer using MassTransit.</p><p>To keep the article short and simple, I omitted many advanced features that a messaging system would use.</p><p>Having said that, we have covered everything you need to introduce messaging into your system and evolve it over time.</p><p>If you don’t want to use RabbitMQ, MassTransit supports many other brokers, and the setup to use them is equally as simple.</p><p>If you‘re interested in .NET <strong>topics</strong>, consider <a href="https://subscribe.rokokovac.com/"><strong>subscribing</strong></a> to get notified when i <strong>publish </strong>more 😉</p><p>Any thoughts? Leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44cb27024497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webhooks in .NET]]></title>
            <link>https://medium.com/@kova98/webhooks-in-net-e79530f0d764?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79530f0d764</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 10:46:00 GMT</pubDate>
            <atom:updated>2024-12-31T09:10:14.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Webhooks in .NET</h3><h4>Implementing The Lightweight Publish — Subscribe Alternative</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yy2b_YQ5nOrec-cFp94jw.png" /></figure><h3>Introduction</h3><p>The <a href="https://medium.com/@kova98/request-response-in-net-with-httpclient-5ed73941e037">Request — Response</a> pattern is powerful and elegant but comes with limitations, some of which gave birth to patterns like Publish — Subscribe.</p><p>However, the complexity of implementing and maintaining the infrastructure needed to support a Pub — Sub messaging system can be costly.</p><p>In this article, we will explore the middle ground — Webhooks.</p><p>I will go over what problem webhooks solve, and how to implement them in .NET.</p><p>Bored of reading? Try my interactive tutorials over at <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>!</p><h3>The Problem With Request — Response</h3><p>One of the issues with Request — Response is the <strong>synchronous nature</strong> of the pattern.</p><p>Let’s look at a practical real-world example.</p><p>You want to check if a new item has arrived in stock. Pretty easy, you query the Warehouse and ask if there’s a new item in stock since your last check.</p><p>But what if you want to be notified as soon as a new item arrives?</p><p>With the regular Request — Response approach, we would be using some sort of <strong>polling </strong>technique (querying in set terminals), either regular polling (less efficient) or <a href="https://medium.com/@kova98/long-polling-in-net-08caa91000cd">long polling</a> (more efficient). In both approaches, we would still be querying the server regularly, which wastes precious resources and <strong>doesn’t scale very well</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OY5c6FXAIATwe1nL1qohcg.png" /><figcaption>Polling</figcaption></figure><p>We need some kind of a way to allow clients to <strong>subscribe</strong> to receive news about a <strong>topic, </strong>and for the server to <strong>publish</strong> those news to the subscribers, without them asking for it.</p><h3>What Is a Webhook?</h3><p>Webhooks are somewhat of a middle ground between Request — Response communication and a full-blown <a href="https://medium.com/@kova98/pub-sub-in-net-with-masstransit-44cb27024497">Publish — Subscribe</a> system.</p><p>They solve the problem of asynchronous communication, without the complexity of broker infrastructure.</p><p>They are essentially <strong>a callback mechanism implemented over a network</strong>.</p><p>They allow a client to <strong>subscribe to a topic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llYmuJvBfIUsi0xbC15f9Q.png" /></figure><p>… and the server to <strong>inform the client</strong> on the <strong>news </strong>about the <strong>topic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4oszQt8toN-TD8sJiwt_g.png" /></figure><h3>The Building Blocks</h3><p>There are a few essential building blocks in a webhook system.</p><h4>Subscription</h4><p>This is the model that contains the necessary information to inform a single client subscribed to a topic. It must contain the <strong>topic </strong>and the <strong>callback </strong>URI.</p><h4><strong>Topic</strong></h4><p>This is the topic of the subscription. It usually represents a domain event, for example, a new item being created.</p><h4>Callback</h4><p>The callback URI is what the server sends the payload to. It is the responsibility of the client to implement an API endpoint on this URI and ensure that it accepts the payload the server sends.</p><h4>Payload</h4><p>This is a simple message containing the information about the event. Usually a serialized JSON representation of an event.</p><h4><strong>Trigger</strong></h4><p>This is what triggers the webhook. Domain-wise, it is an event on a certain topic. Technically-wise, It can be anything from a simple in-process method call to an event handler that consumed a message from another part of the system.</p><h3>Implementing a Webhok Server</h3><p>To implement a webhook server, let’s set up a single API endpoint.</p><pre>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddSingleton&lt;WebhookService&gt;();<br><br>var app = builder.Build();<br><br>app.MapPost(&quot;/subscribe&quot;, (WebhookService ws, Subscription sub) <br>    =&gt; ws.Subscribe(sub));<br><br>app.Run();</pre><p>This endpoint will call our <strong>WebhookService</strong>, where we will implement the business logic.</p><p>We define the <strong>Subscription </strong>model, which simply contains a <strong>topic</strong> and a <strong>callback</strong>.</p><p>We implement a single <strong>Subscribe </strong>method.</p><p>For demonstration purposes, we keep a list of subscriptions in memory. Usually, you would want to store this in a database.</p><pre>public record Subscription(string Topic, string Callback);<br><br>public class WebhookService<br>{<br>    private readonly List&lt;Subscription&gt; _subscriptions = new();<br>    <br>    public void Subscribe(Subscription subscription)<br>    {<br>        _subscriptions.Add(subscription);<br>    }<br>}</pre><h3>Adding the Trigger</h3><p>Next, we need to add the trigger mechanism. For the purpose of testing, we will add another API endpoint which will call our <strong>PublishMessage </strong>method in the WebhookService.</p><pre>app.MapPost(&quot;/publish&quot;, async (WebhookService ws, PublishRequest req) <br>    =&gt; await ws.PublishMessage(req.Topic, req.Message));<br><br>record PublishRequest(string Topic, object Message);</pre><p>Let’s implement it inside our <strong>WebhookService.</strong></p><p>Whenever a message is published on a <strong>topic</strong>, we will get all the subscriptions for that topic and send them the message<strong> </strong>as the <strong>payload</strong>.</p><pre>public class WebhookService<br>{<br>    private readonly List&lt;Subscription&gt; _subscriptions = new();<br>    private readonly HttpClient _httpClient = new(); <br>    <br>    public void Subscribe(Subscription subscription)<br>    {<br>        _subscriptions.Add(subscription);<br>    }<br><br>    public async Task PublishMessage(string topic, object message)<br>    {<br>        var subscribedWebhooks = _subscriptions.Where(w =&gt; w.Topic == topic);<br>        <br>        foreach (var webhook in subscribedWebhooks)<br>        {<br>            await _httpClient.PostAsJsonAsync(webhook.Callback, message);<br>        }<br>    }<br>}</pre><h3>Implementing a Webhook Client</h3><p>Our Webhook client will subscribe to the <strong>item.new</strong> topic. It will provide a callback URI, and implement the endpoint with a simple log to the console.</p><p>We will run the <strong>server </strong>on <strong>http://localhost:5003</strong> and the <strong>client </strong>on<strong> http://localhost:5004.</strong></p><pre>const string server = &quot;http://localhost:5003&quot;;<br>const string callback = &quot;http://localhost:5004/wh/item/new&quot;;<br>const string topic = &quot;item.new&quot;;<br><br>var client = new HttpClient();<br><br>Console.WriteLine($&quot;Subscribing to topic {topic} with callback {callback}&quot;);<br>await client.PostAsJsonAsync(server + &quot;/subscribe&quot;, new { topic, callback });<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddLogging();<br><br>var app = builder.Build();<br>app.MapPost(&quot;/wh/item/new&quot;, (object payload, ILogger&lt;Program&gt; logger) =&gt;<br>{<br>    logger.LogInformation(&quot;Received payload: {payload}&quot;, payload);<br>});<br>app.Run();</pre><h3>Triggering the Webhook</h3><p>Now that we’ve set up a simple webhook server and a client, it’s time to test it.</p><p>Let’s invoke the trigger endpoint using Powershell. If you’re on mac on linux, you can use curl.</p><p>In the body, we will set the <strong>topic</strong> to <strong>item.new. </strong>The <strong>message </strong>will contain simple information about the item — a <strong>name </strong>and a <strong>price</strong>.</p><pre>$body = @{<br>    Topic = &quot;item.new&quot;<br>    Message = @{<br>        Name = &quot;Some Item&quot;<br>        Price = &quot;2.55&quot;<br>    }<br>} | ConvertTo-Json<br><br>Invoke-RestMethod -Uri &quot;http://localhost:5003/publish&quot; -Method POST -Body $body -ContentType &quot;application/json&quot;</pre><p>If everything is set up correctly, you should see this in the Client’s console:</p><pre>info: Program[0]<br>      Received payload: {&quot;Price&quot;:&quot;2.55&quot;,&quot;Name&quot;:&quot;Some Item&quot;}</pre><p>You can find the <a href="https://github.com/kova98/BackendCommunicationPatterns.NET/tree/master/PublishSubscribe/Webhook">full source code on my GitHub</a>.</p><h3>Conclusion</h3><p>In this article, we covered everything you need to know to understand and implement a webhook system.</p><p>We covered the theory, and implemented a working proof of concept.</p><p>In a production setting, you might consider things like retry policies and security, but that is beyond the scope of this guide.</p><p>If you want to see more .NET related content, consider <a href="https://subscribe.rokokovac.com/">subscribing</a>.</p><p>Any thoughts? Leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79530f0d764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating .NET Deployment with GitHub Actions and Docker]]></title>
            <link>https://medium.com/@kova98/automating-net-deployment-with-github-actions-and-docker-d43109d34f88?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d43109d34f88</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 15:48:45 GMT</pubDate>
            <atom:updated>2024-12-31T09:10:22.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating .NET Deployment with GitHub Actions and Docker</h3><h4>Save Time By Setting Up a CI/CD Pipeline For Your .NET Project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82ZxhhdxfBH-zcljwwft0g.png" /></figure><h3>Introduction</h3><p>The process of <strong>building and deploying</strong> applications is boring, repetitive, and tedious, but needs to be done <strong>frequently</strong> and <strong>100% right 100% of the time</strong>. This makes it a perfect candidate for automation.</p><p>In this article, I will show you how to automate the deployment of your .NET projects to a machine using GitHub Actions and Docker.</p><p>I will briefly cover why and how to use Docker, as well as explain CI/CD in simple terms.</p><p>Bored of reading? Try my interactive tutorials over at <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>!</p><h3>Why Docker?</h3><p>We will be deploying an ASP.NET Core application to a virtual machine with Docker installed.</p><p>If you’re not familiar with <strong>Docker</strong>, it’s a containerization tool. We use it to <strong>isolate apps</strong> from the <strong>host machine</strong> and simplify deployment.</p><p>You could also deploy by copying the project output folder to the VM, or even pulling the git repo and building on the server, but then you would have to maintain the dotnet and asp.net runtimes on the server, as well as the rest of the configuration, which is a huge pain.</p><p>Dockerizing your app makes deployment and maintenance much easier, even with simple architectures such as a single web app.</p><h3>Prerequisites</h3><ul><li>A virtual machine with Docker installed</li><li><a href="https://hub.docker.com/">Docker Hub account (it’s free)</a></li><li>Repository hosted on GitHub</li></ul><p>The VM should be able to <strong>accept requests on port 80</strong>. You should have an <strong>SSH key</strong> set up, preferably a new one specifically for GitHub Actions. I will not be covering how to set up a VM in this article.</p><p>If you’re looking to set up a cheap VM, I highly recommend <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-an-ubuntu-20-04-server-on-a-digitalocean-droplet">DigitalOcean</a>.</p><h3>Dockerizing an ASP.NET Core App</h3><p>To Dockerize our ASP.NET Core App, we will create a file named “Dockerfile” at the root of our project.</p><p>It should look like this:</p><pre># Build<br>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build<br>WORKDIR /app<br>COPY . .<br>RUN dotnet restore<br>RUN dotnet publish -c Release -o out<br><br># Run<br>FROM mcr.microsoft.com/dotnet/aspnet:7.0<br>WORKDIR /app<br>COPY --from=build /app/out .<br>ENV ASPNETCORE_URLS=http://*:80<br>CMD dotnet App.dll</pre><p>The first step (Build) of the Dockerfile uses the official <strong>.net 7.0 SDK </strong>image as the base to build the app and saves it in the “out” folder.</p><p>The second step (Run) uses the official <strong>ASP.NET 7.0 runtime </strong>image as the base, copies the build output from the previous step, and runs the compiled dll. Obviously, you should replace “App” with the name of your project.</p><p>At the time of writing this article, the Kestrel inside the ASP.NET Core runtime image is by default configured to listen to port 80. However, this is going to change in .NET 8, so we will explicitly set it in our Dockerfile.</p><p>This Dockerfile will allow Docker to build our container.</p><h3>CI/CD</h3><p>Let’s say that we want to deploy our app whenever we <strong>merge code into the main branch</strong>.</p><p>Whenever we do that, we want to start a “job” that will <strong>build our container</strong>, <strong>upload it to our VM</strong> somehow, and <strong>start it there</strong>.</p><p>In other words, this job will <strong>continuously </strong>check for new code that’s <strong>integrated </strong>into the main branch<strong> </strong>and <strong>deploy it</strong>.</p><p>There could be more than one of these jobs, or steps (such as build, test, and deploy), all <strong>lined up</strong> one after another.</p><p>Those jobs would form a<strong> Continuous Integration / Continuous Deployment</strong> pipeline, or <strong>CI/CD</strong> for short.</p><h3>Writing a CI/CD Workflow in GitHub Actions</h3><p>Let’s write a CI/CD pipeline (GitHub calls them Workflows) in GitHub Actions.</p><h4>YAML</h4><p>Workflows in GitHub Actions are written in YAML, which is a simple and elegant data serialization language that relies on indenting for structure and has minimal syntax.</p><h4>Creating a Workflow File</h4><p>To create a GitHub Action workflow, we create a file in the root of the repo:</p><p>~/.github/workflows/deploy.yml</p><p>In the file, we can start by giving the workflow a name:</p><pre>name: Backend Deployment</pre><h4>Steps</h4><p>It’s time to write out the pipeline. Let’s quickly reiterate our desired steps:</p><ol><li>When code is merged into the main branch</li><li>Build the container</li><li>Upload it to the VM</li><li>Start the server</li></ol><h4>1. Trigger when code is merged into main</h4><p>First, we set up the trigger for the main branch:</p><pre>on:<br>  push:<br>    branches: [ &quot;main&quot; ]</pre><p>Then, we define the job. We will run it on Ubuntu.</p><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest</pre><h4>2. Build the container</h4><p>Next, we need to define the job steps. These steps are what you would usually do manually. To build the containers, you would first need to pull the git repository. You could write all the commands for this yourself, but there’s a better way.</p><p><a href="https://github.com/marketplace?type=actions">GitHub Marketplace</a> contains a lot of pre-written actions that you can reuse. One of them is <a href="https://github.com/marketplace/actions/checkout">checkout</a><em>. </em>With it, you can pull the repository in a single line.</p><pre>    steps:<br>    - uses: actions/checkout@v3</pre><p>If you’re wondering how a fresh VM can pull your repository, <strong>GitHub Runners</strong> (the VMs running the workflows) are <strong>automatically </strong>set up with an <strong>auth token</strong> that has access to your repo. It’s stored as a secret and deleted after the job finishes.</p><p>Now that we have the main branch pulled, we want to <strong>build the container</strong>. Docker is pre-installed on GitHub Runners, so all we have to do is run a command.</p><p>We define custom steps by giving them a <em>name </em>and a <em>run </em>field. We also need to set the <em>working-directory </em>if the Dockerfile is not in the root of the repository.</p><pre>    - name: Build the Docker image<br>      working-directory: path<br>      run: docker build . -t docker-hub-username/container-name:latest</pre><p>Make sure the <em>path </em>is correct. It is the path where the Dockerfile is located, relative to the root of your repository.</p><p>The <em>docker-hub-username</em> should be replaced with your DockerHub username. This is because we will be pushing the container image to the <strong>DockerHub container registry</strong>. The <em>container name </em>can be anything you like.</p><h4>3. Upload to VM</h4><p>To get the container into the VM, we will first upload it to the registry, and then pull it from the VM.</p><p>To upload the image we built to the registry, first, we need to log in. For that, we will use <em>login-action@v2</em>.</p><pre>    - name: Log into Docker Hub<br>      uses: docker/login-action@v2<br>      with:<br>        username: ${{ secrets.DOCKERHUB_USERNAME }}<br>        password: ${{ secrets.DOCKERHUB_TOKEN }}</pre><p>As you can see, we’re using variables. The GitHub Runner will replace these with the secrets defined in our repo. We will set those up later.</p><p>After logging in, we can push the image to the container registry.</p><pre>    - name: Push the images to Docker Hub<br>      run: docker push docker-hub-username/container-name</pre><p>Next, we need to pull it onto our VM. We will SSH into the VM and pull the image. We will use an existing action to simplify SSH connection.</p><pre>    - name: Pull the image to VM<br>      uses: appleboy/ssh-action@v1.0.0<br>      with:<br>        host: ${{ secrets.SSH_HOST }}<br>        username: ${{ secrets.SSH_USERNAME }}<br>        key: ${{ secrets.SSH_KEY }}<br>        script: | <br>          docker pull ${{ secrets.DOCKERHUB_USERNAME }}/hello:latest<br></pre><h4>4. Run the Image</h4><p>And finally, to the <strong>script </strong>parameter of the <em>ssh-action, </em>we will add lines to stop the existing container and run one with the new image.</p><p>Remembering the ENV variable we set in the Dockerfile earlier (<strong>ASPNETCORE_URLS</strong>), we bind the <strong>host’s port 80</strong> to the <strong>port 80 in our container</strong>.</p><pre>          docker stop hello || true<br>          docker rm hello || true<br>          docker run -d -p 80:80 --name hello ${{ secrets.DOCKERHUB_USERNAME }}/hello:latest</pre><p>The finished workflow file should look something like this:</p><pre>name: Backend Deployment<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>    - uses: actions/checkout@v3<br>    <br>    - name: Build the Docker image<br>      working-directory: Dockerized/Hello<br>      run: docker build . -t docker-hub-username/container-name:latest<br><br>    - name: Log into Docker Hub<br>      uses: docker/login-action@v2<br>      with:<br>        username: ${{ secrets.DOCKERHUB_USERNAME }}<br>        password: ${{ secrets.DOCKERHUB_TOKEN }}<br><br>    - name: Push the image to Docker Hub<br>      run: docker push docker-hub-username/container-name<br><br>    - name: Pull the image to VM<br>      uses: appleboy/ssh-action@v1.0.0<br>      with:<br>        host: ${{ secrets.SSH_HOST }}<br>        username: ${{ secrets.SSH_USERNAME }}<br>        key: ${{ secrets.SSH_KEY }}<br>        script: <br>          docker pull ${{ secrets.DOCKERHUB_USERNAME }}/hello:latest<br>          docker stop hello || true<br>          docker rm hello || true<br>          docker run -d -p 80:80 --name hello ${{ secrets.DOCKERHUB_USERNAME }}/hello:latest</pre><h3>Generate a Docker Hub Access Token</h3><p>Before adding secrets to GitHub, you will need to generate an <strong>access token</strong> for Docker Hub.</p><p>Log in, then navigate to <a href="https://hub.docker.com/settings/security">https://hub.docker.com/settings/security</a> and click <strong>New Access Token.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wv-r6WL0hk3DgOITsSov8Q.png" /></figure><p>In the description, put whatever you like. Give it all access, and click Generate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdL9QBci4lG2lfXuVBEdLQ.png" /></figure><p>Copy it and close the prompt.</p><p>This is your <strong>DOCKERHUB_TOKEN</strong>.</p><p>Before we can test the pipeline, we need to add the secrets to our repository.</p><p>Navigate to <strong>Settings &gt; Secrets and variables &gt; Actions</strong> and click <strong>New repository secret.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yaup8tu7pT5fpA6CSjBe5A.png" /></figure><p>Add the following:</p><ul><li><strong>DOCKERHUB_TOKEN </strong>: the token you created earlier</li><li><strong>DOCKERHUB_USERNAME </strong>: your Docker Hub username</li><li><strong>SSH_HOST </strong>: your VM’s address</li><li><strong>SSH_USERNAME </strong>: your username on the VM</li><li><strong>SSH_KEY </strong>: your private SSH key</li></ul><h3>Running the Workflow</h3><p>This should be everything you need, time to test!</p><p>As we have set the workflow to trigger on pushes to the <em>main </em>branch, all you need to do to test it is commit this file.</p><p>I would suggest that you open<strong> a new branch for testing workflows</strong>, since you will be pushing a lot of commits. After you’re done, simply change the trigger back to “main” and <strong>squash merge it to <em>main</em></strong>.</p><p>You can find all Workflows in the “<strong>Actions</strong>” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*KoorUxTX2g7I_0aYNTOAig.png" /></figure><h3>Conclusion</h3><p>I have shown you how to set up a <strong>simple </strong>CI/CD pipeline using GitHub Actions and Docker.</p><p>More advanced deployment strategies will be covered in the future.</p><p>If you liked this article, consider <a href="https://subscribe.rokokovac.com/">subscribing</a> to get notified when I post more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43109d34f88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster Request-Response in .NET with gRPC]]></title>
            <link>https://medium.com/@kova98/faster-request-response-in-net-with-grpc-d0b7b4604cb9?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0b7b4604cb9</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 08:58:09 GMT</pubDate>
            <atom:updated>2024-12-31T09:10:29.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Faster Request-Response in .NET with gRPC</h3><h4>Leveraging Protocol Buffers over HTTP/2 to Build Faster, Strongly Typed APIs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh-GpQ2MPrJKt-LH3m05sA.png" /></figure><h3>Introduction</h3><p><a href="https://medium.com/@kova98/request-response-in-net-with-httpclient-5ed73941e037">REST</a> is the most widely adopted architectural style for building APIs. It produces simple, human-readable interfaces that are easy to understand, implement and consume. However, it is not without shortcomings.</p><p>In this article, I will briefly go over those shortcomings, how gRPC addresses them, and then show you how to implement a gRPC client and server in .NET.</p><p>Bored of reading? Try my interactive tutorials over at <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>!</p><h3>REST vs gRPC</h3><p>First, let’s briefly go over the main differences between the two.</p><p><strong>REST </strong>is an <strong>architectural style </strong>that<strong> </strong>enables communication using<strong> JSON </strong>messages over <strong>HTTP/1.1.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*rtmDt-mvrYT49PtUodnNig.png" /><figcaption><strong>REST</strong> communication</figcaption></figure><p><strong>gRPC </strong>is a <strong>protocol </strong>that enables communication using <strong>Protocol Buffer</strong> messages over<strong> HTTP/2.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*COtZ7uqgKzYn64vBIFvQ3g.png" /><figcaption><strong>gRPC</strong> communication</figcaption></figure><p><strong>Protocol buffers </strong>are a <strong>strongly typed</strong>, <strong>binary format</strong>, while <strong>JSON</strong> is a <strong>text-based format</strong>. This makes it <strong>7 to 10 times faster</strong> to serialize/deserialize and produces a <strong>much smaller payload</strong>.</p><p>This significant performance improvement comes at the expense of the messages not being human-readable and the <strong>lack of browser support</strong>.</p><p>This is why gRPC is mostly used for <strong>communication between services.</strong></p><p>In addition to unary calls (request-response), gRPC also supports streaming. However, this is beyond the scope of this article.</p><h3>Creating a gRPC Server</h3><p>Let’s move onto the implementation.</p><p>First, we will create a new gRPC Server project. We will use the <strong>grpc template</strong> provided by Microsoft and name it <strong>Grpc.Server</strong>.</p><pre>dotnet new grpc -o Grpc.Server</pre><p>Let’s unpack what exactly this template contains.</p><h4>.csproj</h4><p>The project references the Grpc.AspNetCore package, which implicitly brings in Google.Protobuf (the runtime library), Grpc.Tools (ProtoBuf compilers), the standard ASP.NET Core libraries, as well as some extension methods to make registering gRPC services easy.</p><p>It also references the greet.proto file, and sets the GrpServices options to “Server” to stop the tool from generating Client files since we don’t need them.</p><pre>&lt;ItemGroup&gt;<br>  &lt;Protobuf Include=&quot;Protos\greet.proto&quot; GrpcServices=&quot;Server&quot; /&gt;<br>&lt;/ItemGroup&gt;<br><br>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;Grpc.AspNetCore&quot; Version=&quot;2.49.0&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><h4>appSettings</h4><p>As gRPC uses HTTP/2, an entry is added in the appSettings that configures Kestrel endpoints’ default protocol to HTTP/2.</p><h4>ProtoBuf File</h4><p>As we mentioned earlier, gRPC is a protocol that uses <strong>strongly typed</strong> ProtoBuf contracts. These Protocol Buffer contracts are defined in <strong>.proto</strong> files.</p><p>In the Protos folder, there is a <strong>greet.proto</strong> file.</p><pre>syntax = &quot;proto3&quot;;<br><br>option csharp_namespace = &quot;Grpc.Server&quot;;<br><br>package greet;<br><br>service Greeter {<br>  rpc SayHello (HelloRequest) returns (HelloReply);<br>}<br><br>message HelloRequest {<br>  string name = 1;<br>}<br><br>message HelloReply {<br>  string message = 1;<br>}</pre><p>The syntax should be reasonably clear for any C# developer.</p><p>There’s a declaration specifying the version of the proto file, a C# specific namespace option (more on that later), and a definition of the methods and messages which resemble request, response, and entity DTOs in a REST API.</p><p>One thing that stands out is that <strong>each field has a unique id</strong>. In ProtoBuf, these are called <strong>field numbers</strong>. They are used for more efficient encoding while allowing for APIs to evolve without breaking old versions, as long as you don’t reuse or change the IDs in the new versions.</p><h4>GreeterService</h4><p>In GreeterService.cs, we inherit from the <strong>GreeterBase </strong>and override the implementations for our service’s methods.</p><pre>using Grpc.Core;<br><br>namespace Grpc.Server.Services;<br><br>public class GreeterService : Greeter.GreeterBase<br>{<br>    public override Task&lt;HelloReply&gt; SayHello(HelloRequest request, ServerCallContext context)<br>    {<br>        return Task.FromResult(new HelloReply<br>        {<br>            Message = &quot;Hello &quot; + request.Name<br>        });<br>    }<br>}</pre><p>As you can see, most of the code is hidden in the <strong>Base class</strong>.</p><p><strong>But where does this base class come from</strong>?</p><p>Whenever you build your project, the <strong>Grpc Tools</strong> will scan for any changes within the <strong>.proto</strong> files that are <strong>included in your project</strong> and <strong>generate C# code</strong> according to the definitions in them.</p><p>In our case, the <strong>ProtoBuf compiler</strong> reads our <strong>greet.proto</strong> and generates a <strong>Greeter.Greeter</strong> service base class.</p><p>You can see it in action if you inspect the build log:</p><pre>&gt;C:\Users\Roko\.nuget\packages\grpc.tools\2.49.0\tools\windows_x64\protoc.exe <br> --csharp_out=obj\Debug\net7.0\Protos <br> --plugin=protoc-gen-grpc=C:\Users\Roko\.nuget\packages\grpc.tools\2.49.0\tools\windows_x64\grpc_csharp_plugin.exe <br> --grpc_out=obj\Debug\net7.0\Protos <br> --grpc_opt=no_client <br> --proto_path=C:\Users\Roko\.nuget\packages\grpc.tools\2.49.0\build\native\include <br> --proto_path=. <br> --dependency_out=obj\Debug\net7.0\12fbc7ffe642ca7e_greet.protodep <br> --error_format=msvs Protos\greet.proto</pre><p>In your build folders, it generates two folders with partial implementations of the base class. These files should never be manually modified or included in version control. The only thing you should ever change is the .proto file.</p><h4>The program.cs</h4><p>In the program.cs file, we call a few extension methods.</p><pre>using Grpc.Server.Services;<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddGrpc();<br><br>var app = builder.Build();<br>app.MapGrpcService&lt;GreeterService&gt;();<br>app.Run();</pre><p>The AddGrpc() method adds routing, options, and everything required to handle Grpc services.</p><p>The MapGrpcService adds route mapping to the GreeterService we implemented.</p><p>This is everything you need for a simple gRPC server.</p><h3>Creating a gRPC Client</h3><p>To consume the API, we will create a simple console application and install the required packages.</p><pre>dotnet new console -o Grpc.Client<br>cd Grpc.Client<br>dotnet add package Grpc.Net.Client<br>dotnet add package Google.Protobuf<br>dotnet add package Grpc.Tools</pre><p>We will copy over the Proto folder with our greet service definition. We will also reference it in our .csproj, but this time we will make sure only the Client is generated.</p><pre>&lt;ItemGroup&gt;<br>  &lt;Protobuf Include=&quot;Protos\greet.proto&quot; GrpcServices=&quot;Client&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>If you build the project now, you can see from the build log that the Client has been generated.</p><pre>Grpc.Client -&gt; C:\...\Grpc.Client\bin\Debug\net7.0\Grpc.Client.dll</pre><p>Let’s use it to send a request.</p><pre>using Grpc.Net.Client;<br>using Grpc.Server; // defined in greet.proto csharp_namespace option<br><br>var channel = GrpcChannel.ForAddress(&quot;http://localhost:5143&quot;);<br>var client = new Greeter.GreeterClient(channel);<br><br>var reply = client.SayHello(new HelloRequest { Name = &quot;World&quot; });<br>Console.WriteLine(&quot;Greeting: &quot; + reply.Message);</pre><p>Make sure the server is <strong>running </strong>and the <strong>address is right</strong>.</p><p>If you run the client now, you should see the following in the console:</p><pre>Greeting: Hello World</pre><h3>Using a gRPC Client with Dependency Injection</h3><p>In a real-world application, you will probably want to inject the client instead of instantiating inside a class that uses it, like in the following example.</p><pre>using Grpc.Server;<br><br>namespace Grpc.Client;<br><br>public class GreeterService<br>{<br>    private readonly Greeter.GreeterClient _client;<br><br>    public GreeterService(Greeter.GreeterClient client)<br>    {<br>        _client = client;<br>    }<br><br>    public async Task&lt;string&gt; SayHelloAsync(string name)<br>    {<br>        var reply = await _client.SayHelloAsync(new HelloRequest { Name = name });<br>        return reply.Message;<br>    }<br>}</pre><p>To add the client to the Service collection, The package Grpc.Net.ClientFactory provides an easy-to-use extension method.</p><pre>dotnet add package Grpc.Net.ClientFactory</pre><p>The usage resembles an <a href="https://medium.com/@kova98/request-response-in-net-with-httpclient-5ed73941e037">HttpClientFactory</a>.</p><pre>var services = new ServiceCollection();<br>services.AddTransient&lt;GreeterService&gt;();<br>services.AddGrpcClient&lt;Greeter.GreeterClient&gt;(o =&gt;<br>{<br>    o.Address = new Uri(&quot;https://localhost:5143&quot;);<br>});</pre><pre>public class GreeterService<br>{<br>    private readonly Greeter.GreeterClient _client;<br><br>    public GreeterService(Greeter.GreeterClient client)<br>    {<br>        _client = client;<br>    }<br><br>    public async Task&lt;string&gt; SayHelloAsync(string name)<br>    {<br>        var reply = await _client.SayHelloAsync(new HelloRequest { Name = name });<br>        return reply.Message;<br>    }<br>}</pre><p>You can find the full source code on my <a href="https://github.com/kova98/BackendCommunicationPatterns.NET">GitHub</a>.</p><h3>Conclusion</h3><p>I have shown you how to achieve faster Request-Response communication in .NET using gRPC.</p><p>gRPC has much more to offer, and some of the features will be explored in future articles.</p><p>Any thoughts? Leave a comment.</p><p>If you liked the article, consider <a href="https://subscribe.rokokovac.com/">subscribing</a> to be notified when I post more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0b7b4604cb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Failing Fast in .NET]]></title>
            <link>https://medium.com/@kova98/failing-fast-in-net-c10aab781a44?source=rss-91bca95035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10aab781a44</guid>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Roko Kovač]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 12:40:45 GMT</pubDate>
            <atom:updated>2024-12-31T09:10:42.527Z</atom:updated>
            <content:encoded><![CDATA[<h3>Failing Fast in .NET</h3><h4>Avoid Hours of Debugging, Frustration, and Wasted Time by Employing This Simple Method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYUHzXNmTWH9TSMzsnG6oA.png" /></figure><h3>Introduction</h3><p>Have you ever spent hours investigating a bug by researching the exception details, only to find out that <strong>the exception thrown had nothing to do with the issue</strong>?</p><p>In this article, I will explain the concept of failing fast in .NET, the motivation behind it, and why it helps solve these issues.</p><p>Bored of reading? Try my interactive tutorials over at <a href="https://www.codeinteractive.dev/">codeinteractive.dev</a>!</p><h3>The Causes</h3><p>Cryptic and/or difficultly traceable exceptions are a common issue, and I have identified the two main culprits (if we ignore deliberately throwing wrong exceptions):</p><ul><li><strong>not validating input</strong></li><li><strong>defensive programming</strong></li></ul><p>Let me explain.</p><h3>Not Validating Input</h3><p>Let’s look at an example where we don’t write any validation.</p><p>We’re getting a connection string from our Configuration and using it to add a Postgres database to the service collection of our ASP.NET Core application.</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    var connStr = Configuration.GetConnectionString(&quot;DefaultConnection&quot;);<br>    services.AddDbContext&lt;AppDbContext&gt;(options =&gt; options.UseNpgsql(connStr));<br>}</pre><p>Somewhere in our startup, we’re making sure that the database is migrated.</p><pre>context.Database.Migrate();</pre><p>Now, if you run your code without setting up the connection string properly, you will get the following error:</p><pre>System.ArgumentException: Host can&#39;t be null</pre><p>You might ask yourself: “<strong>What the hell does that mean?</strong> Which argument? What host? ”</p><p>And your question would be completely reasonable.</p><h3>Failing As Late As Possible</h3><p>The reason why you’re getting confused, and why the message is so cryptic, is that we didn’t do our due diligence and <strong>validated the input</strong> from an external source <strong>as soon as we got it</strong>.</p><p>In this case, we didn’t validate that the <strong>connection string taken </strong>from the Configuration <strong>actually exists</strong>.</p><p>By doing so, we ensured that the app will fail <strong>as late as possible</strong>, at an <strong>unpredictable time</strong>, and in unpredictable conditions.</p><p>You may argue that it’s not that big of a deal since you can easily debug it and might even recognize the error, but what if you get this error in a test environment, or even <strong>production</strong>? On a Kubernetes cluster?</p><p>What if a colleague who didn’t update his<strong> config</strong> gets it? What if a pipeline is not updated with <strong>new environment variables</strong>? What if it’s something more serious than just a missing connection string?</p><p><strong>How many hours will be lost debugging this mess?</strong></p><p>Before discussing the remedy, let’s take a look at another way we, developers, make our lives harder.</p><h3>Defensive Programming</h3><p>An even better way to make sure our application fails in unpredictable ways at unpredictable times is to program overly defensively and introduce <strong>default </strong>and <strong>fallback </strong>values for <strong>critical input</strong>.</p><p>The “critical” part is emphasized. It’s not the end of the world if the translation service is experiencing a transient failure and you have to rely on the default translations.</p><p>It is, however, a huge issue if critical information is missing.</p><p>Consider this example of a method that loads and returns the RabbitMQ configuration.</p><pre>public RabbitMqConfiguration GetRabbitMqConfiguration()<br>{<br>    var host = Configuration[&quot;RabbitMq:Host&quot;] ?? &quot;localhost&quot;;<br>    var queueName = Configuration[&quot;RabbitMq:QueueName&quot;] ?? &quot;defaultQueue&quot;;<br>    var valid = int.TryParse(Configuration[&quot;RabbitMq:Port&quot;], out var parsed);<br>    var port = valid ? parsed : 5672;<br>    <br>    return new RabbitMqConfiguration<br>    {<br>        Host = host,<br>        QueueName = queueName,<br>        Port = port<br>    };<br>}</pre><p>The code is deployed, however, the team forgets to add the QueueName environment variable.</p><p>Best case scenario: the queue doesn’t exist, and RabbitMQ will throw an unhelpful exception when trying to send information to it. You will know that something is wrong, but will still spend a lot of time figuring out what.</p><p>More probable: the message will be sent to an existing, but wrong queue. You will spend <strong>hours </strong>investigating and debugging code, infrastructure, and deployment environments.</p><h3>The Solution</h3><p>The solution is simple. Do NOT code defensively. Fail FAST. Fail informatively. Throw exceptions.</p><p>When handling any input, ask yourself: Is this input <strong>critical </strong>to the scope you’re working with (application, HTTP request, Event Bus handler…)?</p><p>If yes, validate it and, if it’s not what’s expected, throw an exception <strong>immediately</strong>.</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    var connStr = Configuration.GetConnectionString(&quot;DefaultConnection&quot;);<br>    if (string.IsNullOrEmpty(connStr)<br>    {<br>        throw new ConfigurationMissingException(&quot;DefaultConnection&quot;);<br>    }<br><br>    services.AddDbContext&lt;AppDbContext&gt;(options =&gt; options.UseNpgsql(connStr));<br>}</pre><p>Any thoughts? Leave a comment.</p><p>Interested about .NET content? Consider <a href="https://subscribe.rokokovac.com/">subscribing</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10aab781a44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>