<?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 Recep Serit on Medium]]></title>
        <description><![CDATA[Stories by Recep Serit on Medium]]></description>
        <link>https://medium.com/@rserit?source=rss-f82b03bf7611------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RyKufjrsAsW9zRIUeijyiA.png</url>
            <title>Stories by Recep Serit on Medium</title>
            <link>https://medium.com/@rserit?source=rss-f82b03bf7611------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:48:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rserit/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[Using .NET Guid.CreateVersion7() — Why the UUIDv7 Structure Matters]]></title>
            <link>https://medium.com/@rserit/using-net-guid-createversion7-why-the-uuidv7-structure-matters-4a91829ee60e?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a91829ee60e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 20:06:42 GMT</pubDate>
            <atom:updated>2026-07-09T20:06:42.482Z</atom:updated>
            <content:encoded><![CDATA[<p>The GUID class is one of the most unquestioned building blocks in the software world. You call Guid.NewGuid(), use the returned value as a primary key, and go about your business. But in a world of distributed systems, microservice architectures, and high-volume databases, this randomness actually carries a hidden yet very expensive cost. The Guid.CreateVersion7() method introduced in .NET 9 targets exactly this cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8SUPudWJ8hAwMlkXgRt3g.jpeg" /></figure><h3>RFC 4122</h3><p>The classic Guid.NewGuid() generates a version 4 UUID as defined by RFC 4122. Nearly all of the 128 bits consist of cryptographically secure random numbers. The purpose of this design is to make unpredictability and the probability of collision practically zero. And to be fair, it does achieve that goal.<br>While this is a sensible approach from a security standpoint, it creates a difficult structure from a database perspective. It comes with a number of disadvantages.</p><h3>Database Structure</h3><p>In SQL database structures, the primary key typically forms the basis of the clustered index and determines the physical order of rows on disk. On every INSERT, a random GUID gets forced into a random point in the B-Tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*HPiKa3qTquOb1WE0MgiSiQ.jpeg" /></figure><p>The diagram above shows two scenarios:<br><strong>Sequential key (int / UUIDv7):</strong> The leaf pages are arranged in order by key range: 1–10, 11–20, 21–30, 31–40. When a new row arrives (say, 41), this value doesn’t fit into any of the existing pages. It gets appended to a new page at the very end of the sequence. All the engine has to do is write to the last page. None of the existing pages are disturbed.<br><strong>Random key (UUIDv4): </strong>The same four pages exist, but the incoming values are completely random. When a value like 17 is generated, it falls into the 11–20 range in the middle of the B-Tree. The problem is, that page is already full. The engine doesn’t have three options to choose from — it only has one.</p><p>First, it splits the full page in two. Then it moves roughly half of the rows to a new page. Next, it places the new row into the appropriate page. Finally, it updates the higher-level index nodes (non-leaf pages) to point to the new page.</p><p>That’s quite a lot of work for a single INSERT operation, isn’t it?<br>And this is exactly what UUIDv7 solves. Because the timestamp comes first, the generated values always arrive in ascending order. This means new rows almost always land at the end of the sequence.</p><h3>RFC 9562</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*08wkwpz3hVCTLtDZSZ6pVg.jpeg" /></figure><p>The official source on this topic is RFC 9562. One of the most important changes introduced by this standard is the definition of UUID versions 6, 7, and 8</p><p><strong>UUIDv6:</strong> Reorders the bit layout of the old UUIDv1 (based on MAC address + timestamp) to make it sortable. It’s focused on backward compatibility. <strong>UUIDv7:</strong> Designed from the ground up to be database-friendly. UUIDv8: Leaves room for vendor-specific experimental use cases.</p><p>The IETF’s reason for making this change was exactly the practical problem described above. The goal was to be able to generate unique identifiers in distributed systems without needing a central ID generator (unlike auto-increment), but without sacrificing index locality in the process. As the RFC itself puts it, because the timestamp sits at the front of the UUID, sequentially generated values end up positioned close to one another in the index, which enables better clustering of objects and better performance.<br>The bit layout that RFC 9562 defines for UUIDv7 is detailed within the IETF document itself.</p><h3><strong>Guid.CreateVersion7()</strong></h3><p>.NET 9 added a static method to the System.Guid type that directly implements this RFC.</p><pre>var guid = Guid.CreateVersion7();<br>var timedGuid = Guid.CreateVersion7(DateTimeOffset.UtcNow.AddDays(-1));</pre><p>Generation is time-based. The first 48 bits carry a Unix epoch timestamp with millisecond precision. By looking at a GUID, you can tell roughly when it was generated.<br>When GUID values generated in sequence are compared byte by byte, they form an ascending order. It essentially behaves like an auto-incrementing integer. It’s database-friendly. In clustered index structures, every INSERT gets appended to the end of the index. Page splits are reduced dramatically.<br>It still contains 122 bits of randomness. Only 6 bits are fixed, while the remaining space still guarantees uniqueness. So while you gain ordering, unpredictability isn’t entirely sacrificed.<br>If used as a correlation ID, especially in event-driven architectures, traceability becomes much easier. This is a very valuable improvement for logging purposes.</p><h3>Conclusion</h3><p>Guid.CreateVersion7() is an addition that comes natively integrated into the .NET ecosystem, but behind it lies a serious standardization effort (RFC 9562) and the resolution of a decade-old practical problem.<br>If you’re working within a microservice architecture where your services need to generate identifiers independently of one another, Guid.CreateVersion7() should probably be your default choice from now on. If you have a single monolithic database and you’re chasing raw performance, bigint is still unmatched. The right choice between the two depends on how distributed your architecture is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a91829ee60e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable Code with Factory Pattern in C#]]></title>
            <link>https://medium.com/@rserit/building-scalable-code-with-factory-pattern-in-c-d0e088eb0dd8?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e088eb0dd8</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Sun, 24 May 2026 21:25:09 GMT</pubDate>
            <atom:updated>2026-05-24T21:25:09.097Z</atom:updated>
            <content:encoded><![CDATA[<p>As software projects grow, managing how and when objects are created can turn into complete chaos. Constantly instantiating objects binds classes together over time, leading to the issue of tight coupling. As a result, you lose flexibility in your project. This is why design pattern solutions exist. The Factory Pattern, which manages object instantiation processes from a single central point and abstracts them, is one of the most frequently used solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziVNmT2sYwzKVJvLhcmUnA.jpeg" /></figure><h3>The Factory Pattern</h3><p>The Factory Pattern is one of the most widely used design patterns. Its primary purpose is to hide the creation logic of an object from the section that will actually use it (the client side). In other words, the place where you call the object (for example, code you are writing inside a Controller) does not need to know what the concrete class is or how it is instantiated. The client simply requests an object that meets its criteria, and the design pattern handles the rest.</p><p>This pattern works perfectly when you have multiple class families in your system that share the same interface or abstract class but possess different business rules behind the scenes. It will be much easier to understand with examples.</p><p>It is frequently implemented in payment systems (such as Stripe or Iyzico) or notification services (SMS, email, push notifications).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vYzd-sW_zB-I31s1Hrw18w.jpeg" /></figure><h3>How to Implement the Factory Pattern</h3><p>To better understand this structure, let’s build a scenario. Imagine we are developing a search engine for a legal and academic research platform. Users should be able to perform searches across three different categories: legislations, court rulings, or legal literature. However, each of these categories relies on entirely different search algorithms and target databases.</p><p>If we were to build this without using the pattern, the code block triggered the moment the search button is clicked would probably look like this:</p><pre>public enum SearchType { Mevzuat, MahkemeKarari, Eserler }<br><br>public class SearchController<br>{<br>    public void ExecuteSearch(SearchType type, string keyword)<br>    {<br>        if (type == SearchType.Mevzuat)<br>        {<br>            MevzuatSearch mevzuatService = new MevzuatSearch();<br>            mevzuatService.Search(keyword);<br>        }<br>        else if (type == SearchType.MahkemeKarari)<br>        {<br>            MahkemeKarariSearch mahkemeService = new MahkemeKarariSearch(); <br>            mahkemeService.Search(keyword);<br>        }<br>        else if (type == SearchType.Eserler)<br>        {<br>            BookSearch bookService = new BookSearch();<br>            bookService.Search(keyword);<br>        }<br>    }<br>}</pre><p>This is a terrible design. Why? If we need to introduce a new search category tomorrow, we would have to add another if-else block inside this class. This directly violates the Open/Closed principle of SOLID. Even if you put those principles aside, you can clearly see that the objects bound to specific search types are tightly coupled inside the SearchController.</p><p>Now, let’s refactor this by applying the Factory Pattern.</p><p>Our first step is to create a common interface that all search types can share:</p><pre>public interface ISearchService<br>{<br>    void Search(string keyword);<br>}</pre><p>Next, let’s implement this interface across our specialized search classes:</p><pre>public class MevzuatSearch : ISearchService<br>{<br>    public void Search(string keyword) =&gt; Console.WriteLine($&quot;Mevzuat veri tabanında &#39;{keyword}&#39; arandı.&quot;);<br>}<br><br>public class MahkemeKarariSearch : ISearchService<br>{<br>    public void Search(string keyword) =&gt; Console.WriteLine($&quot;Mahkeme kararlarında &#39;{keyword}&#39; arandı.&quot;);<br>}<br><br>public class EserSearch : ISearchService<br>{<br>    public void Search(string keyword) =&gt; Console.WriteLine($&quot;Eserler arşivinde &#39;{keyword}&#39; arandı.&quot;);<br>}</pre><p>Now, let’s build our factory class. It will instantiate and return the appropriate class based on the parameters it receives:</p><pre>public static class SearchFactory<br>{<br>    public static ISearchService CreateSearchService(SearchType type)<br>    {<br>        return type switch<br>        {<br>            SearchType.Mevzuat =&gt; new MevzuatSearch(),<br>            SearchType.MahkemeKarari =&gt; new MahkemeKarariSearch(),<br>            SearchType.Eserler =&gt; new EserSearch(),<br>            _ =&gt; throw new ArgumentException(&quot;Geçersiz arama türü!&quot;)<br>        };<br>    }<br>}</pre><p>The factory component is ready. Now we can refactor our poorly designed controller and invoke the factory instead:</p><pre>public class SearchController<br>{<br>    public void ExecuteSearch(SearchType type, string keyword)<br>    {<br>        // The client does not see the concrete classes; it interacts strictly with the interface.<br>        ISearchService searchService = SearchFactory.CreateSearchService(type);<br>        <br>        // Polymorphism ensures the correct search method is triggered.<br>        searchService.Search(keyword);<br>    }<br>}</pre><p>Once the Factory Pattern is in place, adding a brand-new search type — such as international treaties — is child’s play. All you need to do is implement a new class derived from the ISearchService interface and add it to the switch expression inside the SearchFactory. The SearchController class remains completely unaware of this change. As a result, your project scales much more safely and reliably.</p><h3>Avoid Common Mistakes</h3><p>When implementing the Factory Pattern, there are several mistakes that developers frequently make. These errors can compromise the design pattern’s structure and defeat its original purpose:</p><p><strong>Creating Factories for Everything: </strong>In a project with only a few concrete classes where future expansion is not expected, setting up a factory structure introduces unnecessary complexity.</p><p><strong>Executing Business Logic Inside the Factory: </strong>A factory has one single responsibility: to instantiate and return the object. Incorporating business rules, such as fetching database records during object creation, goes against the core purpose of this design pattern.</p><p><strong>Allowing the Factory Class to Overgrow: </strong>When using a Simple Factory, constantly expanding the switch-case block with every newly added class can eventually make the codebase unmanageable. In such cases, you should consider transitioning to reflection mechanisms or a pattern like the Strategy Pattern. Managing this growth carefully is crucial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e088eb0dd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Discovery with Eureka Server and Steeltoe in .NET Microservices]]></title>
            <link>https://medium.com/devopsturkiye/service-discovery-with-eureka-server-and-steeltoe-in-net-microservices-84d67ac7a753?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d67ac7a753</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 15:10:18 GMT</pubDate>
            <atom:updated>2026-04-30T05:57:37.477Z</atom:updated>
            <content:encoded><![CDATA[<p>While microservice architectures provide flexibility by breaking systems into independently manageable components, they also bring significant operational complexity. When one service needs to communicate with another, it must know the target service’s network location (IP and port). In traditional monolithic structures, this could be handled via static configurations; however, in a modern, dynamically scaling world, using fixed IP addresses is not sustainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GGqMFVmF7YVMqiLAvI3tQ.jpeg" /></figure><p>To elaborate, your appsettings.json files are not identical across all environments, such as localhost, test, pre-prod, and prod. In each environment, address information, variables, and environment-specific data may vary. You must manage and distribute these files properly. Furthermore, forgetting to update one of these configurations when adding a new service or moving an existing one to a different node can lead to runtime errors.</p><h3>The Role of Service Discovery</h3><p>At this point, the Service Discovery mechanism provides a critical infrastructure that allows microservice applications to find each other through a dynamic and intelligent directory rather than manual entry. Technically, there are two primary models:</p><p><strong>Client-Side Discovery: </strong>The client queries the service registry, retrieves the list of available services, performs the load balancing logic itself, and decides which instance to connect to.</p><p><strong>Server-Side Discovery:</strong> The client sends a request to a load balancer. The load balancer then queries the service registry and routes the request to the appropriate destination.</p><h3>Service Registry and Client</h3><p>The Service Registry is a centralized component that maintains a list of currently running microservice instances and their corresponding network locations. The Service Registry Client, on the other hand, is the component within your microservice applications used to query the registry for other services they need to communicate with.</p><p>There are two widely preferred applications used for service discovery:</p><p><strong>Netflix Eureka: </strong>An open-source, REST-based service registration and discovery server provided by Netflix. It acts as a directory containing microservice address information and provides the essential data for inter-service load balancing and failover.</p><p><strong>HashiCorp Consul: </strong>A multi-functional service mesh and configuration management tool. Beyond service discovery, it provides health checking, a KV store (key-value store), and secure service communication.</p><p>In this article, I will elaborate using Eureka. For the client library, we will use Steeltoe. Steeltoe is an open-source library that enables .NET applications to align with cloud-native architectures, specifically the Spring Cloud ecosystem. It allows .NET applications to communicate with tools like Eureka and Consul. It is commonly used when adding .NET microservices to an existing Spring-based infrastructure or when developing a new .NET cloud-native architecture.</p><p>How the system works:<br>Registration: When an OrderService you developed starts up, it sends a message to Eureka via the Steeltoe library. This message includes its IP and port information, which the registry then adds to its list.</p><p>Discovery: When another service, such as PaymentService, needs to reach OrderService to verify an order, it does not know the IP address. It asks the Registry for the “OrderService address.”</p><p>Address Retrieval: The Registry returns the current address of OrderService (e.g., 192.168.1.50:5001) from its up-to-date list. PaymentService now knows where to send the request.</p><p>If the system were static, you would have to manually hardcode the following inside PaymentService:</p><pre>var orderServiceUrl = &quot;http://192.168.1.50:5001&quot;;</pre><p>However, when using a Service Registry Client, your code transforms into this:</p><pre>var orderServiceUrl = &quot;http://OrderService&quot;;</pre><p><strong>Steeltoe</strong> resolves this logical name into the actual IP in the background. Consequently, even if OrderService moves to a different server tomorrow and its IP address changes, the Registry Client automatically finds the updated address, and you don’t need to change a single line of code.</p><h3>Setting Up the Eureka Service Registry</h3><p>Eureka does not offer native support as a standalone Windows executable. Therefore, we will set up Eureka using Docker. You can spin up the container with the following command:</p><pre>docker run -d -p 8761:8761 - name eureka-server springcloud/eureka</pre><p>The Eureka Server configuration file is application.yml. You can organize its content as follows:</p><pre>server:<br> port: 8761<br>eureka:<br> client:<br> registerWithEureka: false<br> fetchRegistry: false<br> server:<br> waitTimeInMsWhenSyncEmpty: 0</pre><p>Alternatively, you can run it on Docker with the same configuration using environment variables:</p><pre>docker run -d `<br> - name eureka-server `<br> -p 8761:8761 `<br> -e &quot;EUREKA_CLIENT_REGISTERWITHEUREKA=false&quot; `<br> -e &quot;EUREKA_CLIENT_FETCHREGISTRY=false&quot; `<br> springcloud/eureka</pre><p>-p 8761:8761: Maps port 8761 inside the container to your localhost.</p><p>REGISTERWITHEUREKA=false: Prevents the Eureka server from registering itself as a client in the list.</p><p>FETCHREGISTRY=false: Stops the server from trying to pull a registry list from another server, as it is running in standalone mode.</p><p>With this setup, a Eureka server starts running in the background on Windows, and you can access it directly at <strong>localhost:8761</strong>. This method allows you to run it without dealing with Java or Maven.</p><p>Alternatively, <strong>Consul</strong> can be downloaded directly as a .exe for Windows. To set it up, simply place the consul.exe file in a folder and run consul agent -dev in your terminal. Consul will launch immediately, and you can access its web interface. Since the Steeltoe library supports both Eureka and Consul, your .NET code will remain virtually identical.</p><p>Because these tools are typically server-side components, they are designed to be executed via Docker or through Java/Go runtimes rather than through a traditional Windows installation wizard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*_gOpzfPa10i2TDPIG0NUbw.png" /></figure><h3>Registering the Microservice</h3><p>In this section, we focus on how to register a microservice with the service registry. To ensure our legal service (LegalConsultantService) can be discovered by other services, we will add the necessary definitions to the Startup.cs class. We only need to add a single line to both the ConfigureServices and Configure methods.</p><p>First, let’s install the Steeltoe package:</p><pre>dotnet add package Steeltoe.Discovery.ClientCore</pre><p>Now, we need to add the discovery client inside Startup.cs:</p><pre>using Steeltoe.Discovery.Client;<br><br>namespace LegalConsultantService<br>{<br>    public class Startup<br>    {<br>        public Startup(IConfiguration configuration)<br>        {<br>            Configuration = configuration;<br>        }<br><br>        public IConfiguration Configuration { get; }<br><br>        public void ConfigureServices(IServiceCollection services)<br>        {<br>            services.AddDiscoveryClient(Configuration);<br>            <br>        }<br><br>        public void Configure(IApplicationBuilder app, IHostingEnvironment env)<br>        {<br>            app.UseDiscoveryClient();<br>        }<br>    }<br>}</pre><p>The final and most important step is configuring the appsettings.json file. This file determines the identity with which our service will register on the Eureka side.</p><pre>{<br>  &quot;spring&quot;: {<br>    &quot;application&quot;: {<br>      &quot;name&quot;: &quot;LegalConsultantService&quot;<br>    }<br>  },<br>  &quot;eureka&quot;: {<br>    &quot;client&quot;: {<br>      &quot;shouldRegisterWithEureka&quot;: true,<br>      &quot;serviceUrl&quot;: &quot;http://localhost:8761/eureka&quot;,<br>      &quot;ValidateCertificates&quot;: false<br>    },<br>    &quot;instance&quot;: {<br>      &quot;appName&quot;: &quot;LegalConsultantService&quot;,<br>      &quot;hostName&quot;: &quot;localhost&quot;,<br>      &quot;port&quot;: &quot;5040&quot;<br>    }<br>  }<br>}</pre><p>spring.application.name: The official name of our service across the entire system.</p><p>eureka.client.shouldRegisterWithEureka: This setting determines whether the service will register itself with Eureka. Setting this to true allows it to be called by other services.</p><p>serviceUrl: The address of the Eureka server.</p><p>instance: Defines how the service appears in Eureka:</p><p>appName: The name other services will use when searching for us.</p><p>hostName and port: The hostname and port number where the service is running and listening for requests.</p><p>Once you run your service with this configuration, you can visit the Eureka dashboard (localhost:8761) to verify that it has successfully registered.</p><p><strong>Why do we define the port and host manually?</strong><br>This can be explained by the concepts of Network Address Translation (NAT) and Isolation. When you run a .NET application inside a Docker container, the application usually sees itself on an internal IP like 172.17.0.x and port 80. If the application tells Eureka, “My IP is 172.17.0.x,” other services outside that specific Docker network will not be able to reach it.</p><p>Therefore, this structure — which may seem manual but actually gives control to the developer — is designed to minimize network errors. When you establish a bridge between Docker containers, these settings ensure that services can communicate with each other seamlessly.</p><blockquote>You can find the documentation for Eureka client configuration here:<br><a href="https://steeltoe.io/docs/v4/discovery/index.html#1-2-2-eureka-client-settings">https://steeltoe.io/docs/v4/discovery/index.html#1-2-2-eureka-client-settings</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Q2HPh8sQ6B5MQJxT0ZdAUA.jpeg" /></figure><h3>Requests Between Microservices</h3><p>Our first step, just as we did previously for LegislationService, is to add the Eureka client configuration to the client side. Now we are ready to call one service from another. In our specific example, since we need legal data from the LegislationService during the creation phase of a case file, we will call the LegislationService from within the LegalCaseService.</p><pre>using Microsoft.Extensions.Configuration;<br>using Polly;<br>using LegislationService.Api.Queries;<br>using RestEase;<br>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br>using Steeltoe.Common.Discovery;<br><br>namespace LegalCaseService.RestClients<br>{<br><br>    public interface ILegislationClient<br>    {<br>        [Get(&quot;api/legislation/{id}&quot;)]<br>        Task&lt;LegislationDetail&gt; GetLegislationDetailAsync([Path] int id);<br>    }<br><br>    public class LegislationClient : ILegislationClient<br>    {<br>        private readonly ILegislationClient client;<br><br>        // Retry pattern<br>        private static IAsyncPolicy _retryPolicy = Policy<br>            .Handle&lt;Exception&gt;()<br>            .WaitAndRetryAsync(3, i =&gt; TimeSpan.FromSeconds(3));<br><br>        public LegislationClient(IConfiguration configuration, IDiscoveryClient discoveryClient)<br>        {<br>            var handler = new DiscoveryHttpClientHandler(discoveryClient);<br>            <br>            var httpClient = new HttpClient(handler, false)<br>            {<br>                BaseAddress = new Uri(configuration.GetValue&lt;string&gt;(&quot;LegislationServiceUri&quot;))<br>            };<br><br>            // RestEase HTTP client<br>            client = RestClient.For&lt;ILegislationClient&gt;(httpClient);<br>        }<br><br>        public Task&lt;LegislationDetail&gt; GetLegislationDetailAsync(int id)<br>        {<br>            return retryPolicy.ExecuteAsync(async () =&gt; await client.GetLegislationDetail(id));<br>        }<br>    }<br>}</pre><p>We have written an interface representing the operations offered by the LegislationService. Subsequently, we created an implementation that retrieves the address from the Eureka service registry, integrated with Polly and RestEase.</p><p>The key component is the HTTP handler:</p><pre>var handler = new DiscoveryHttpClientHandler(discoveryClient);</pre><p><strong>DiscoveryHttpClientHandler</strong> resolves the service name in the URL to a real IP address via Eureka. Consequently, the address in appsettings.json is no longer a physical network address, but the service’s name:</p><pre>&quot;LegislationServiceUri&quot; : &quot;http://LegislationService&quot;</pre><p>When the code sees <a href="http://legislationservice/">http://LegislationService</a>, it goes to Eureka, retrieves the corresponding address (e.g., 192.168.x.x:5040), and routes the request there.</p><p>Now, we must add this client to the IoC (Inversion of Control) container. We use a RestClientsInstaller class for this:</p><pre>public static class RestClientsInstaller<br>{<br>    public static IServiceCollection AddLegislationRestClient(this IServiceCollection services)<br>    {<br>        services.AddSingleton&lt;ILegislationClient, LegislationClient&gt;();<br>        return services;<br>    }<br>}</pre><p>Now, anywhere in the project (such as a Controller or Service class), you can inject the ILegislationClient interface and use the LegislationService as if you were calling a local method. Address resolution, connection establishment, and retries in case of failure are all handled automatically in the background.</p><h3>Conclusion</h3><p>Eureka provides us with a dashboard, but that is only a snapshot. For true monitoring, health checks are essential. Simply appearing on the Eureka list is not enough; thanks to the Health Actuators provided by Steeltoe, you should monitor whether the service is actually functional (e.g., checking database connectivity).</p><p>On the server side, you must track whether services are up. Occasionally, a service might crash but its registration might not be dropped from Eureka immediately. Therefore, the operations team should monitor the red alerts on the Eureka dashboard. This is, of course, a team effort.</p><p>In conclusion, the problem of service discovery and stable communication — one of the biggest hurdles in microservice architectures — transforms into a self-managing ecosystem through the combination of Eureka and Steeltoe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d67ac7a753" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devopsturkiye/service-discovery-with-eureka-server-and-steeltoe-in-net-microservices-84d67ac7a753">Service Discovery with Eureka Server and Steeltoe in .NET Microservices</a> was originally published in <a href="https://medium.com/devopsturkiye">Devops &amp; AI Türkiye☁️ 🐧 🐳 ☸️</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Read Preferences and Write Concerns — Consistency Models]]></title>
            <link>https://medium.com/@rserit/mongodb-read-preferences-and-write-concerns-consistency-models-b5f479e6533b?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f479e6533b</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[consistency]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 03:48:21 GMT</pubDate>
            <atom:updated>2026-04-20T03:48:21.155Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern microservice architectures and high-scale systems require balancing the speed of an operation with how reliably it is persisted — one of the most critical decisions for software architects. MongoDB provides two fundamental levers to manage this balance dynamically: Read Preferences and Write Concerns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oY_XnG-8bXP168JxTF7Stw.jpeg" /></figure><p>In MongoDB’s distributed architecture, the Read Preference and Write Concern parameters manage data integrity and are core configurations that determine operational behavior on a cluster.</p><p>Write Concern defines the durability level by specifying how many replica set members (e.g., w: 1, w: majority, or journaled) must durably commit the data for a write operation to be considered successful.</p><p>Read Preference controls which nodes in the topology (primary, secondary, nearest, etc.) queries are routed to, directly affecting whether the system follows an eventual consistency or strong consistency model.</p><p>These features are used in systems of any scale that require data consistency sensitivity. For example, in e‑commerce systems, using writeConcern: majority for payment records and stock updates ensures data is written to at least two or more nodes. To avoid overloading the live system, you can use readPreference: secondary to route reporting queries to replicas rather than the primary server.</p><p>Proper configuration of these mechanisms minimizes latency in high‑traffic systems while also reducing the risk of data loss, thereby optimizing the system’s fault tolerance.</p><h3>Read Preferences</h3><p>Read preferences are the mechanism that determines which node (primary or secondary) within a replica set client‑side queries are routed to. By default, all read operations are performed on the primary node, which guarantees the most up‑to‑date data. However, depending on performance needs, queries can be routed to the nearest node or to secondary nodes.</p><p>After data is written to the primary server, it takes milliseconds to replicate to secondary servers. If you read that data from the primary, you will find the data you just wrote. If you read from a secondary, the data might not have been replicated yet — meaning that when a user updates their profile information, there is a chance they might see the old information for a short while. In banking, using the primary is mandatory, but if you see a post’s like count a few seconds late, it’s not a problem; therefore, secondary can be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UBExU8JIi4s9uIGWNv6IAw.jpeg" /></figure><h3>Server Selection Algorithm</h3><p>The MongoDB Driver uses a server selection algorithm to choose which replica set member to use, or which mongos instance to use when connected to multiple mongos instances. It requires no additional operations. When you specify in your code that data should be read from a secondary (ReadPreference = Secondary), the driver repeatedly performs all the remaining work — ping measurement, bucket creation, and random selection — on your behalf, many times within seconds.</p><p>Let’s clarify what this means. The MongoDB Driver has an intelligent selection strategy. Suppose you have three servers and your code uses ReadPreference = Secondary. How does the MongoDB Driver decide which secondary server to go to? Does it query all of them, or does it pick one? It does this using its own algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AJg89SQMZEMkngcxigD_jg.jpeg" /></figure><p>The driver continuously monitors the servers in the background. Then it makes its decision as follows:</p><ol><li>First, it maintains a list of all servers in the cluster.</li><li>Then it regularly “pings” each one. Based on the ping results, let’s assume Secondary A returns 10ms, Secondary B 12ms, and Secondary C 30ms. The driver finds the fastest one in this list.</li><li>It adds the default tolerance of 15ms to the fastest time. That is, 10ms (fastest) + 15ms (tolerance) = 25ms is accepted.</li><li>All servers with a latency of 25ms or less are placed into a bucket. In our example, Secondary A and Secondary B go into the bucket. The others are excluded.</li><li>In the final step, the query is sent randomly to either server A or B.</li></ol><blockquote>To learn this topic in detail: <a href="https://www.mongodb.com/docs/manual/core/read-preference-mechanics/">https://www.mongodb.com/docs/manual/core/read-preference-mechanics/</a></blockquote><h3>Write Concern</h3><p>In a distributed system, a write operation is not just about writing to disk — it is also the process of replicating data to replica set members. Write Concern is a setting that determines how many servers must acknowledge receiving the data for a write operation to be considered successful. It is managed using the w (number of servers) and wtimeout (waiting time) parameters.</p><p>MongoDB receives the data and waits until the specified w value is reached. Once the required number of acknowledgments is achieved, the driver receives a success (acknowledged) signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*DZNccTW7T-8EdhLXxkdycQ.jpeg" /></figure><p>Write Concern options:</p><p><strong>w: 0 (Unacknowledged): </strong>At this level, the driver considers the operation complete as soon as it sends the data over the socket. It does not wait for any ACK message. The TCP packet is sent, and control returns to the code. If an error occurs (e.g., disk full), the application is not notified.</p><p><strong>w: 1 (Acknowledged — Default):</strong> This is MongoDB’s default setting. It is sufficient for the write operation to be acknowledged only by the primary node.</p><p><strong>w: majority (Data Durability): </strong>The safest standard level. It waits for the data to be acknowledged by the strict majority of replica set members (e.g., 2 out of 3 nodes). The primary writes the data and then propagates it to secondary nodes. The primary does not return an ACK response to the driver until the majority of nodes have reported that they received the data. This level guarantees that data will not be lost in a failover scenario. It is ideal for critical operations where data loss is unacceptable, such as financial transactions, inventory management, and domain registration processes.</p><p><strong>w: (Custom Replication Count):</strong> Used to wait for acknowledgment from a specific number of nodes (e.g., w: 2, w: 3). A total of the specified number of nodes (including the primary) must acknowledge the data. If the number of active nodes in the cluster is less than the number you specified (e.g., you have 3 servers but set w: 4), the operation will return an error.</p><p><strong>w: “tag” (Tag-Aware): </strong>This works based on tags assigned to replica set members. For example, if you tag your servers geographically ({ “dc”: “Gebze” }), you can set a rule like w: “GebzeDC” to ensure data is written specifically to nodes in Gebze. You may be required by legal regulations to guarantee data reaches certain locations.</p><p>Example connection in MongoDB driver:</p><pre>var secureWrite = new WriteConcern(WriteConcern.WValue.Majority) <br>{ <br>    WTimeout = TimeSpan.FromMilliseconds(500) <br>};<br><br>var settings = new MongoClientSettings();<br>settings.WriteConcern = secureWrite;</pre><p>Additionally, you can use the Journal parameter to enable logging. The j: true setting writes data from RAM to a log file on disk. MongoDB does not impose a fixed set of database rules; rather, it offers advanced configuration for read and write operations. The task of a software architect is to choose the most appropriate balance for each function of the application, making the system both fast and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f479e6533b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing CQRS Pattern and MediatR in .NET]]></title>
            <link>https://medium.com/@rserit/implementing-cqrs-pattern-and-mediatr-in-net-03211104ab97?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/03211104ab97</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 20:51:29 GMT</pubDate>
            <atom:updated>2026-03-13T20:52:47.508Z</atom:updated>
            <content:encoded><![CDATA[<p>In traditional software architectures, for many years, data reading and writing operations were carried out through the same data models and service structures. However, as systems have grown more complex and user numbers have increased, this ‘one-size-fits-all’ approach has begun to create significant challenges. In an e-commerce platform, viewing a product thousands of times versus updating its stock information just once are operations with completely different natures. While read operations demand speed and flexibility, write operations focus on data consistency and security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxBf17FYhovAYV2HYrGg1A.jpeg" /></figure><p><strong>CQRS (Command Query Responsibility Segregation)</strong> was born out of the need to overcome the sluggishness caused by confining these two opposite worlds within the same models and classes. Imagine you have a LegalService class in your project. This service would provide API methods for creating lawsuit files, updating legal processes, and allowing other departments to query this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*mQ7MTtvBeMlwNWths8ASmw.jpeg" /><figcaption><em>Image source: ByteByteGo</em></figcaption></figure><p>Imagine that this LegalService class performs too many operations. It contains dozens of methods, such as opening a lawsuit, updating a petition, assigning an attorney, listing all cases, and retrieving case details.</p><p>This situation brings along the following problems:</p><p>Complexity: As the code grows, it becomes impossible to predict the side effects of a single change.</p><p>Time Loss: It takes weeks for a new developer to understand this massive structure.</p><p>Performance: Since read and write operations use the same models, even a simple listing operation can get bogged down by complex background business rules (validations).</p><h3>What Does CQRS Solve?</h3><p>CQRS is an architectural pattern that tells us to separate commands that change data from operations that only read data.</p><p>In a microservice, write operations usually require strict business rules and validation, whereas read operations are focused on speed and caching. CQRS increases the scalability and maintainability of the service by separating these two worlds.</p><p>Returning to our example, when we decompose a traditional LegalService class structure according to CQRS rules, the following structure emerges:</p><p><strong>1. Queries: </strong>These only read data and do not change the state of the system. Example methods could be:</p><p>FindAllLawsuitsQuery: Returns a list of cases.</p><p>GetCaseDetailsByNumberQuery: Retrieves case details based on a specific case number.</p><p><strong>2. Commands:</strong> These perform an action in the system and modify the data state. Example methods could be:</p><p>CreateLawsuitHandler: Creates a lawsuit draft. It takes a DTO as input and adds a new record to the system.</p><p>UpdateCaseHandler: Updates the status of an existing lawsuit.</p><p>When we split our code into commands and queries, how do we know which command will be processed in which class? This is where the Mediator pattern comes into play.</p><p>The Mediator’s job is to take a request and route it to the correct handler. In this way, your services are not tightly coupled. Your code becomes more modular, testable, and free from the risk of ‘spaghetti code’.</p><h3>CQRS and Event Sourcing</h3><p>While the CQRS architecture begins to manage system complexity by separating read and write responsibilities, storing only the latest state of data on the command side can sometimes result in incomplete log data. In a traditional database approach, when the status of a legal file is updated from ‘Open’ to ‘Closed,’ the old data is deleted and overwritten by the new one. However, in microservice projects with high traffic and critical business logic, not just the final state of the data, but how it reached that state is of vital importance. At this point, Event Sourcing comes into play as a mechanism that enhances the separation offered by CQRS.</p><p>Instead of storing the current state of an object, Event Sourcing records all changes occurring on that object as a chronological timeline. In our example, rather than simply looking at the final status of a case within the LegalService, all occurring events such as ‘Case Opened,’ ‘Attorney Assigned,’ and ‘Petition Submitted’ are kept sequentially in an Event Store. This approach becomes much more powerful when combined with CQRS. The Command side merely validates and fires new events, while the Query side listens to these events to create its own fast, optimized, and specialized models. These two patterns are often mentioned together because they naturally fulfill the need for a comprehensive Audit Log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vfsAXcIqBUoRN3wZ56RGzA.jpeg" /><figcaption>Image source: ByteByteGo</figcaption></figure><h3><strong>Implementation with MediatR</strong></h3><p>MediatR is a popular open-source library used in the .NET ecosystem that implements the <strong>Mediator design pattern</strong>. It acts as an in-memory messaging bus, allowing different components within your application to communicate through a mediator rather than talking to each other directly.</p><p>You send a command or a query from a single point; MediatR receives this message and routes it to the specific handler responsible for processing it.</p><p>Let’s look at an example through an MVC structure. The Controller does not depend on repository classes that perform database operations. Instead, the Controller simply passes a ‘get a file’ message to MediatR. In other words, the Controller does not care who performs the task or how it is done.</p><p>To add MediatR to your project, use the following command:</p><pre>Install-Package MediatR</pre><p>Next, we need to register this structure in the Dependency Injection (DI) container. You can activate MediatR by adding the following line to the service configuration section of your .NET project:</p><pre>builder.Services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));</pre><p>To create a query with MediatR, we need to define a class that implements the IRequest interface and specify the return type the query expects. In our example, we will query a lawsuit file by its number:</p><pre>public class GetCaseDetailsByNumberQuery : IRequest&lt;LawsuitDto&gt;<br>{<br>    public string CaseNumber { get; set; }<br>}</pre><p>How do we handle the parameters of this model at the Controller level? We pass the case number coming from an endpoint to MediatR as follows:</p><pre>private readonly IMediator _mediator;<br>public LawsuitsController(IMediator mediator)<br>{<br>    _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));<br>}<br>// GET api/lawsuits/{number}<br>[HttpGet(&quot;{number}&quot;)]<br>public async Task&lt;ActionResult&gt; GetByNumber([FromRoute] string number)<br>{<br>     // We send the query to the mediator<br>     var result = await _mediator.Send(new GetCaseDetailsByNumberQuery { CaseNumber = number });<br>     return Ok(result);<br>}</pre><p>In this structure, the Controller carries no business logic workload. Its sole responsibility is to receive the incoming request, forward it to the mediator, and return the result to the client as JSON.</p><h3>Defining the Handler</h3><p>The most critical part of our CQRS solution is the class that will handle the message. In other words, we need to define a handler (processing class) to respond to each type of message. With MediatR, this process is quite standardized:</p><pre>public class GetLawsuitByNumberHandler : IRequestHandler&lt;GetLawsuitByNumberQuery, LawsuitDto&gt;<br>{<br>    private readonly ILawsuitRepository _lawsuitRepository;<br><br>    public GetLawsuitByNumberHandler(ILawsuitRepository lawsuitRepository)<br>    {<br>        _lawsuitRepository = lawsuitRepository ?? throw new ArgumentNullException(nameof(lawsuitRepository));<br>    }<br>}</pre><p>This class uses the IRequestHandler interface to define the input (GetLawsuitByNumberQuery) and output (LawsuitDto) types. It also mandates the implementation of the Handle method, where the actual logic is executed.</p><pre>public async Task&lt;LawsuitDto&gt; Handle(GetLawsuitByNumberQuery request, CancellationToken cancellationToken)<br>{<br>    // Repository call<br>    var result = await _lawsuitRepository.FindByNumber(request.CaseNumber);<br><br>    if (result == null) return null;<br><br>    // Mapping<br>    return new LawsuitDto<br>    {<br>        CaseNumber = result.CaseNumber,<br>        Title = result.Title,<br>        Description = result.Description,<br>        OpeningDate = result.OpeningDate,<br>        CurrentStatus = result.Status,<br>        AttorneyName = result.Attorney?.FullName,<br>        Documents = result.Documents != null ? LawsuitMapper.ToDocumentDtoList(result.Documents) : null<br>    };<br>}</pre><p>The mapping process is also performed within the handler class. Depending on your needs, you can customize this by using packages like Mapster or AutoMapper.</p><p>Now, let’s define a command class and look at an example:</p><pre>// Handler<br>public class CreateLawsuitCommandHandler : IRequestHandler&lt;CreateLawsuitCommand, Guid&gt;<br>{<br>    private readonly ILawsuitRepository _repository;<br>    private readonly IUnitOfWork _uow;<br><br>    public CreateLawsuitCommandHandler(ILawsuitRepository repository, IUnitOfWork uow)<br>    {<br>        _repository = repository;<br>        _uow = uow;<br>    }<br><br>    public async Task&lt;Guid&gt; Handle(CreateLawsuitCommand request, CancellationToken cancellationToken)<br>    {<br>        var existingCase = await _repository.FindByNumber(request.CaseNumber);<br>        if (existingCase != null)<br>            throw new Exception(&quot;File already exists&quot;);<br><br>        var lawsuit = new Lawsuit(<br>            Guid.NewGuid(),<br>            request.CaseNumber,<br>            request.Title,<br>            request.CaseType<br>        )<br>        {<br>            Description = request.Description,<br>            OpeningDate = request.OpeningDate,<br>            Status = &quot;New Application&quot;<br>        };<br><br>        await _repository.AddAsync(lawsuit);<br>        await _uow.SaveChangesAsync(cancellationToken);<br><br>        return lawsuit.Id;<br>    }<br>}<br><br>// Endpoint<br>[HttpPost]<br>public async Task&lt;IActionResult&gt; Create([FromBody] CreateLawsuitCommand command)<br>{<br>    var lawsuitId = await _mediator.Send(command);<br>    return CreatedAtAction(nameof(GetByNumber), new { id = lawsuitId }, command);<br>}</pre><h3>MediatR Notifications and Event Handling</h3><p>When a command is successfully completed, it is often necessary to notify other parts of the application that something has changed. If you write the email-sending code directly inside the CommandHandler, you would have to modify that class every time a new requirement arises. The Notification structure frees us from this dependency.</p><p>With this approach, when a new feature is added, you don’t touch the existing CreateLawsuit code; you simply add a new INotificationHandler class. Even if the email service is down at that moment, the lawsuit will have been successfully saved to the database. Additionally, if this event interests another microservice, you can catch this MediatR Notification and push it to a tool like RabbitMQ or Kafka to initiate inter-service communication.</p><p>Let’s define an event:</p><pre>public class LawsuitCreatedEvent : INotification<br>{<br>    public Guid LawsuitId { get; }<br>    public string CaseNumber { get; }<br>    public string Title { get; }<br><br>    public LawsuitCreatedEvent(Guid lawsuitId, string caseNumber, string title)<br>    {<br>        LawsuitId = lawsuitId;<br>        CaseNumber = caseNumber;<br>        Title = title;<br>    }<br>}</pre><p>We go back into the CreateLawsuitCommandHandler we wrote earlier and publish this event after the save operation is successful:</p><pre>// At the end of the Handle method in the Handler<br>await _uow.SaveChangesAsync(cancellationToken);<br><br>// Event publish<br>await _mediator.Publish(new LawsuitCreatedEvent(lawsuit.Id, lawsuit.CaseNumber, lawsuit.Title));<br><br>return lawsuit.Id;</pre><p>Finally, we write the notification handler class:</p><pre>public class EmailNotificationHandler : INotificationHandler&lt;LawsuitCreatedEvent&gt;<br>{<br>    public async Task Handle(LawsuitCreatedEvent notification, CancellationToken cancellationToken)<br>    {<br>        // Email logic here<br>        Console.WriteLine($&quot;{notification.CaseNumber} file created&quot;);<br>        await Task.CompletedTask;<br>    }<br>}</pre><h3>Conclusion</h3><p>In the world of microservices, CQRS gives us the power to manage read and write loads independently. The duo of CQRS and MediatR offers not just a technical toolkit, but a discipline. The greatest benefit of this discipline is the reduction of cognitive load. Being able to focus solely on the relevant command and notification classes when you want to add a new rule to the system — without the fear of breaking other parts of the project — is one of the greatest luxuries of modern software development.</p><p>However, you must know your project well before implementing this duo. In a project that performs simple CRUD operations, it might be overkill. But in a structure with heavy business logic, high data throughput, and frequent queries, it can be an excellent architectural choice. Therefore, you should understand your needs thoroughly and choose the design pattern accordingly.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03211104ab97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Domain-Driven Design (DDD) in .NET]]></title>
            <link>https://towardsdev.com/understanding-domain-driven-design-ddd-in-net-95ec22eab8c6?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/95ec22eab8c6</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 22:50:36 GMT</pubDate>
            <atom:updated>2026-02-18T07:13:19.800Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding Domain-Driven Design (DDD) in .NET — Aggregates, Bounded Contexts and Application Services</strong></h3><p>Domain-Driven Design is a domain-centric approach that treats the software development process not merely as a coding activity, but as a combination of human relationships, architectural strategies, and business principles. The core philosophy of DDD is to effectively address the complex business problems at the heart of software, and to foster strong communication between the business team (such as business analysts and product owners) and the development team (the technical team). This approach argues that the primary goal of a project should be the business problem to be solved, rather than the technological tools used. I will explain this more clearly through examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KiRywzt-b8_gqm0pp5whg.jpeg" /></figure><p>In projects where DDD practices are not applied, poor communication is often the biggest obstacle. When the technical team speaks a technology-oriented language and the business unit adopts a purely process-driven language, serious deviations occur during the translation of requirements into code. Over time, this causes the project to turn into a technology-driven knot of problems.</p><p>In traditional approaches, anonymous or generic class names frequently appear in the codebase, such as “Manager,” “Helper,” or “GlobalService.” These classes obscure where the business logic truly belongs and move us away from Object-Oriented Programming principles.</p><p>One of the most common technical issues is the Anemic Domain Model — objects that merely hold data but exhibit no behavior. Since these models do not carry business rules within themselves, maintaining and extending the system eventually becomes nearly impossible. When Entity objects contain no methods and consist only of { get; set; } properties, this contradicts OOP principles. An object should encapsulate both data and the behavior that operates on that data.</p><blockquote>Martin Fowler described this problem in 2003 in his article “Anemic Domain Model”: <a href="https://www.martinfowler.com/bliki/AnemicDomainModel.html">https://www.martinfowler.com/bliki/AnemicDomainModel.html</a></blockquote><p>With the principles it offers, DDD promises to transform this chaos into a manageable structure. First, it establishes a shared language between teams, improving communication efficiency. Thus, if a business analyst refers to something as a “reseller,” it is developed in the codebase with the same name and the same rules. DDD shifts the focus of software away from technological tools (such as databases or caches) and toward building a core architectural model.</p><h3>Choosing DDD</h3><p>Adopting DDD is not merely an engineering preference; it is a business investment decision. Whether to use this architecture can be determined by evaluating two main criteria.</p><p>First, you must ask: Does it provide a competitive advantage in your project? For example, for an e-commerce company, a campaign engine is a competitive advantage, whereas an employee leave management system is merely a supporting function.</p><p>The second question is even more important: DDD requires teams to collaborate closely and often increases development time due to continuous discussions and refinement. Is the complexity of the problem worth this cost?</p><p>I clearly remember spending two weeks on my own converting the complex entity–repository structure of a mid-sized legal project into a DDD-based architecture. This slightly delayed the delivery of new features to subscribers, but when new developers opened the project, every domain was clearly separated, each entity had its own methods, and the namespace structure was clean and well-organized.</p><p>Of course, if the business logic is simple (such as projects that only involve CRUD operations), using DDD would be like firing a cannon to kill a fly — an unnecessary cost.</p><h3>Ubiquitous Language</h3><p>This term refers to the language of communication — a shared vocabulary that both the business unit and the technical team use to understand each other. Let’s make this more concrete.</p><p>If the business team says “Membership Suspended,” the developer should not internally translate this into something like IsActive = false or Status = 2. Instead, the code should explicitly express the concept as SuspendMembership().</p><pre>public class Membership<br>{<br>    public Guid Id { get; private set; }<br>    public string MemberName { get; private set; }<br>    public MembershipStatus Status { get; private set; }<br>    public string SuspensionReason { get; private set; }<br>    public DateTime? SuspendedAt { get; private set; }<br><br>    public Membership(string name)<br>    {<br>        Id = Guid.NewGuid();<br>        MemberName = name;<br>        Status = MembershipStatus.Active;<br>    }<br><br>    public void SuspendMembership(string reason)<br>    {<br>        if (Status == MembershipStatus.Suspended)<br>        {<br>            throw new InvalidOperationException(&quot;Member already suspended&quot;);<br>        }<br><br>        if (string.IsNullOrWhiteSpace(reason))<br>        {<br>            throw new ArgumentException(&quot;Üyeliği askıya almak için bir sebep belirtilmelidir.&quot;);<br>        }<br><br>        this.Status = MembershipStatus.Suspended;<br>        this.SuspensionReason = reason;<br>        this.SuspendedAt = DateTime.UtcNow;<br><br>        // Event publish<br>    }<br>}<br><br>public enum MembershipStatus<br>{<br>    Active,<br>    Suspended,<br>    Cancelled<br>}</pre><p>When the business team uses a term (for example, order), the technical team should not immediately think of the orders table in the database. Instead, they should think about the rules under which that order can be canceled and the stages it goes through.</p><h3>Bounded Context</h3><p>To truly understand the concept of Bounded Context, one must first resolve its “chicken-and-egg” relationship with microservices. Bounded Context is not used exclusively in microservice architectures; however, it is essential for designing a well-structured microservice architecture.</p><p>If you do not adopt this structure, as your project grows it will eventually turn into a Big Ball of Mud — an unstructured and tangled system.</p><p>You cannot manage a large and complex software system as a single massive block. Therefore, you must divide it into smaller, loosely coupled parts with clear logical and technical boundaries. In the past, we used to put everything into a single database and a single massive core project. As those projects grew, they became increasingly unmanageable.</p><p>For example, billing and membership are not the same domain, so they should be separated. Each should have its own database, its own models, and its own business rules. If they need to communicate, they should do so without directly depending on each other — instead, through well-defined gateways such as APIs or events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qnp7qRlGMRx5pXKcf5zIA.jpeg" /></figure><p><em>Source: </em><a href="https://blog.bytebytego.com/p/a-crash-course-on-domain-driven-design"><em>ByteByteGo</em></a></p><p>A microservice is a deployment strategy, whereas a Bounded Context is a logical boundary. In an e-commerce system, the person who pays money is a customer for the sales team, but the person who submits a ticket is a customer for the support team. Naturally, if you try to model this with a single Customer class, it will eventually turn into a massive object with 100 properties. With Bounded Context, each team manages its own version of the “customer” model according to its own needs. DDD actually emerged before the microservice world became popular. Even within a large monolithic project, you can create Bounded Contexts using folder structures and modules (Module A, Module B). In microservice architecture, Bounded Context serves as the framework that defines service boundaries. In many cases, each Bounded Context is deployed as a separate microservice. However, the reverse is not always true.</p><h3>Aggregate and Aggregate Root</h3><p>In Domain-Driven Design (DDD), a group of related objects that collectively enforce a specific business rule is defined as an Aggregate. The central managing entity of this group is called the Aggregate Root. For example, in an e-commerce system, entity classes such as Order, OrderProduct, and OrderInvoice are tightly connected. Since they complete a cohesive business flow together, they form an aggregate. In this case, Order becomes the Aggregate Root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*h343B29YSdZwvuSOOT9FvA.jpeg" /></figure><blockquote>Aggregate is a pattern in Domain-Driven Design. A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An example may be an order and its line-items, these will be separate objects, but it’s useful to treat the order (together with its line items) as a single aggregate (<a href="https://martinfowler.com/bliki/DDD_Aggregate.html">Martin Fowler</a>)</blockquote><p>Let’s create a code example for the “Order” aggregate:</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br><br>namespace Domain.Orders<br>{<br>    public interface IAggregateRoot { }<br><br>    // This class manages all operations — the &quot;Aggregate Root&quot;<br>    public class Order : IAggregateRoot<br>    {<br>        public Guid Id { get; private set; }<br>        public Guid BuyerId { get; private set; }<br>        public DateTime OrderDate { get; private set; }<br>        public OrderStatus Status { get; private set; }<br>        public Address ShippingAddress { get; private set; }<br><br>        // Encapsulation<br>        private readonly List&lt;OrderItem&gt; _orderItems = new();<br>        public IReadOnlyCollection&lt;OrderItem&gt; OrderItems =&gt; _orderItems.AsReadOnly();<br><br>        // Required by ORM tools (such as EF, Dapper)<br>        private Order() { }<br><br>        public Order(Guid buyerId, Address shippingAddress)<br>        {<br>            Id = Guid.NewGuid();<br>            BuyerId = buyerId;<br>            ShippingAddress = shippingAddress;<br>            OrderDate = DateTime.UtcNow;<br>            Status = OrderStatus.Submitted;<br>        }<br><br>        // Products can only be added through this method<br>        public void AddOrderItem(Guid productId, string productName, decimal unitPrice, int quantity)<br>        {<br>            if (quantity &lt;= 0) throw new Exception(&quot;Quantity must be greater than zero.&quot;);<br><br>            var existingItem = _orderItems.SingleOrDefault(o =&gt; o.ProductId == productId);<br><br>            if (existingItem != null)<br>            {<br>                existingItem.IncreaseQuantity(quantity);<br>            }<br>            else<br>            {<br>                var newItem = new OrderItem(productId, productName, unitPrice, quantity);<br>                _orderItems.Add(newItem);<br>            }<br>        }<br><br>        public decimal GetTotalAmount() =&gt; _orderItems.Sum(i =&gt; i.UnitPrice * i.Quantity);<br>    }<br><br>    // Entity object — meaningful only within the Aggregate Root<br>    public class OrderItem<br>    {<br>        public Guid Id { get; private set; }<br>        public Guid ProductId { get; private set; }<br>        public string ProductName { get; private set; }<br>        public decimal UnitPrice { get; private set; }<br>        public int Quantity { get; private set; }<br><br>        internal OrderItem(Guid productId, string productName, decimal unitPrice, int quantity)<br>        {<br>            Id = Guid.NewGuid();<br>            ProductId = productId;<br>            ProductName = productName;<br>            UnitPrice = unitPrice;<br>            Quantity = quantity;<br>        }<br><br>        internal void IncreaseQuantity(int quantity) =&gt; Quantity += quantity;<br>    }<br><br>    // Value object — defined only by its values<br>    public record Address(string Street, string City, string Country);<br><br>    public enum OrderStatus { Submitted, Paid, Shipped, Cancelled }<br>}</pre><h3>Entity Object and Value Object</h3><p>If an object has an identity (ID) that remains constant throughout its lifetime, it is called an Entity. Even if its internal data (such as name, quantity, or price) changes, it is still considered the same object. For example, even if you update the name or price of a Product, its identity remains the same because its ID does not change.</p><p>A Value Object, on the other hand, has no identity. It is typically immutable. If the street of an address changes, it becomes a different address altogether. Countries, currency units, and similar concepts are common examples of value objects.</p><p>A small reminder: An Aggregate is not a single object — it is a cluster. One or more entities and/or value objects come together to form an aggregate.</p><h3>Domain Service</h3><p>Classes often named “Manager” in many enterprise architectures (especially in frameworks like ABP Framework) correspond to what DDD literature calls a Domain Service.</p><p>Using repositories inside a Manager can be more convenient, but this is directly related to business logic. You must maintain balance — domain services are not meant for simple CRUD operations.</p><p>If there is a complex business rule and database queries vary depending on multiple conditions, you can use a Manager or Domain Service. From the outside, you simply call _manager.DoWork(), and it handles everything internally.</p><pre>// Domain Service (Manager)<br>public class OrderManager<br>{<br>    private readonly IOrderRepository _orderRepository;<br><br>    public OrderManager(IOrderRepository orderRepository)<br>    {<br>        _orderRepository = orderRepository;<br>    }<br><br>    public async Task ApplyLoyaltyDiscountAsync(Order order)<br>    {<br>        // The manager queries past data from the database<br>        var pastOrdersCount = await _orderRepository.GetTotalOrderCountAsync(order.BuyerId);<br><br>        if (pastOrdersCount &gt; 10)<br>        {<br>            order.ApplyDiscount(0.15m); // 15% discount<br>        }<br>    }<br>}</pre><h3>Application Service</h3><p>The Application Service layer handles requests coming from the outside world (API/UI). It retrieves necessary data from domain repositories and orchestrates domain objects. It acts as a conductor. Database persistence (Unit of Work), logging, caching, and mapping are handled here. It may use domain services, repositories, APIs, and more. We can better understand this by creating an Order Application Service:</p><pre>public class OrderAppService : IOrderAppService<br>{<br>    private readonly IOrderRepository _orderRepository;<br>    private readonly OrderManager _orderManager;<br>    private readonly IUnitOfWork _uow;<br><br>    public OrderAppService(IOrderRepository orderRepo, OrderManager orderManager, IUnitOfWork uow)<br>    {<br>        _orderRepository = orderRepo;<br>        _orderManager = orderManager;<br>        _uow = uow;<br>    }<br><br>    public async Task&lt;OrderDto&gt; CreateOrderAsync(CreateOrderRequest request)<br>    {<br>        var buyer = await _orderRepository.GetBuyerAsync(request.BuyerId);<br><br>        var order = _orderManager.CreateOrderWithDiscount(buyer, request.Items);<br><br>        await _orderRepository.AddAsync(order);<br>        await _uow.SaveChangesAsync();<br><br>        return new OrderDto { Id = order.Id, TotalPrice = order.TotalPrice };<br>    }<br>}</pre><h3>Conclusion</h3><p>Software architecture is not merely about stacking simple code blocks on top of one another. The most important aspect is designing business logic correctly. The DDD approach advocated by developers such as Martin Fowler and Eric Evans invites us to build projects more intelligently. It transforms code from a purely technical necessity into a shared language aligned with the business domain — the Ubiquitous Language. Within this philosophy, the Aggregate Root acts as an authority figure that protects data integrity, while the Domain Service represents pure business logic. Together, inside a clean namespace structure, they help build a sustainable system that knows what it is responsible for. Ultimately, the goal is not just to write functions, but to place business rules at the center of architecture — allowing the software to grow consistently and correctly, like a living organism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95ec22eab8c6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/understanding-domain-driven-design-ddd-in-net-95ec22eab8c6">Understanding Domain-Driven Design (DDD) in .NET</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building API Gateways with Ocelot in .NET Microservice]]></title>
            <link>https://medium.com/@rserit/building-api-gateways-with-ocelot-in-net-microservice-099c3ae5b768?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/099c3ae5b768</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 21:53:49 GMT</pubDate>
            <atom:updated>2026-02-01T21:53:49.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building API Gateways with Ocelot in .NET Microservice</h3><p>The microservices architecture aims to decouple large, monolithic applications into smaller, independent units rather than developing them as a single, unified entity. In this design, each service is built to maintain its own database, lifecycle, and deployment pipeline.</p><p>As a result, the system becomes not only large but inherently <strong>dynamic</strong>. When traffic spikes, auto-scaling mechanisms trigger new instances; over time, certain services may be split further to handle specific loads. This leads to a backend environment with a constantly shifting and expanding service topology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OXVWhgIMqLoHa3gh0pIvQ.jpeg" /></figure><h3>API Gateway Pattern</h3><p>If mobile or web clients attempted to communicate directly with each of these microservices, significant challenges would arise on the client side. Tasks such as tracking the location of every service, updating client-side code whenever service addresses change, and managing disparate authentication schemes or data formats across multiple services would become unmanageable.</p><p>The API Gateway pattern addresses these issues by providing a single point of entry positioned between the client and the backend microservices. With this approach, the client only needs to be aware of the Gateway’s address. The number of backend services, their physical locations, and how they scale are completely abstracted away. In this regard, the API Gateway acts as a Facade pattern, shielding the client from the underlying complexity of the backend infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnyDs0DOIwBPTgKdca-zUg.jpeg" /></figure><p><em>Source: microsoft.com</em></p><p>Technically, an API Gateway is also a microservice that typically runs within a container and is designed to be independently scalable. However, unlike standard business services, its primary distinction is that it should not harbor any business logic. Instead, the gateway focuses on infrastructure-level responsibilities — often referred to as cross-cutting concerns — such as routing, security, protocol translation, and traffic management.</p><p>The most common architectural pitfall regarding this pattern is transforming the gateway into a bloated, centralized component. This is known as the “<strong>Overambitious API Gateway</strong>” problem. When custom developments, complex calculations, or domain-specific decision mechanisms are embedded within the gateway, it rapidly evolves into a “distributed monolith.” This evolution results in longer deployment cycles, reduced testability, and creates a Single Point of Failure (SPOF) for the entire ecosystem.</p><p>One of the most critical responsibilities of the API Gateway is the centralized handling of authentication and authorization. By managing these processes at the entry point, unauthorized or malformed requests are intercepted and blocked at the gateway level before they can ever reach the internal microservice methods.</p><p>Furthermore, one of the most powerful capabilities of this architecture is protocol translation. The gateway can act as a bridge, transforming an incoming external REST (HTTP) request into an internal gRPC call, an event-driven message (such as Kafka or RabbitMQ), or an internal RPC mechanism. This translation layer not only decouples the external interface from internal communication but also significantly enhances overall system performance.</p><h3>Building API Gateways with Ocelot</h3><p>Ocelot is an open-source, lightweight library specifically designed to meet the API Gateway requirements within the .NET ecosystem. While implementing a centralized layer between clients and backend services in microservice architectures, developing a custom gateway from scratch can lead to significant operational and maintenance overhead. This is where Ocelot excels, offering out-of-the-box support for essential API interface needs such as routing, authentication integration, rate limiting, caching, load balancing, and request/response transformation. Since it is built directly on ASP.NET Core, it provides native compatibility with existing .NET projects and significantly flattens the learning curve for developers.</p><p>One of the primary reasons for choosing Ocelot is its ability to deliver results without falling into the trap of “overengineering.” Compared to more complex solutions like full-scale Service Meshes or Kubernetes-native ingress controllers, Ocelot can be deployed rapidly in small to medium-sized microservice architectures. Its configuration is strictly JSON-based; through this file, backend service addresses, upstream-downstream mappings, and security policies can be managed efficiently without writing a single line of additional code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5xN3B110Uf5KE4N6x7x_g.jpeg" /></figure><p><em>Source: microsoft.com</em></p><p>To install Ocelot in your project, run the following command:</p><pre>Install-Package Ocelot</pre><p>The next step is to add the ocelot.json file to our project, which will hold the gateway configuration. This file is the “brain” of our setup, where we define routing rules, target service addresses, and security policies.</p><p>Let’s implement a clean Minimal API style Ocelot setup based on modern .NET 8+ standards. In this scenario, we assume we are managing “Products” and “Orders” services in an e-commerce system through a single gateway.</p><pre>using Ocelot.DependencyInjection;<br>using Ocelot.Middleware;<br>using Microsoft.AspNetCore.Authentication.JwtBearer;<br>using Microsoft.IdentityModel.Tokens;<br>using System.Text;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Integrating JWT Authentication<br>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>    .AddJwtBearer(&quot;GatewayKey&quot;, options =&gt; <br>    {<br>        options.TokenValidationParameters = new TokenValidationParameters<br>        {<br>            ValidateIssuer = true,<br>            ValidateAudience = true,<br>            ValidateLifetime = true,<br>            ValidateIssuerSigningKey = true,<br>            ValidIssuer = &quot;YourIssuer&quot;,<br>            ValidAudience = &quot;YourAudience&quot;,<br>            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(&quot;YourSuperSecretKey123!&quot;))<br>        };<br>    });<br><br>// Loading the ocelot.json configuration<br>builder.Configuration.AddJsonFile(&quot;ocelot.json&quot;, optional: false, reloadOnChange: true);<br><br>// Registering Ocelot services in their simplest form without unnecessary bloat<br>builder.Services.AddOcelot(builder.Configuration);<br><br>var app = builder.Build();<br><br>// Handing over all incoming requests to Ocelot<br>await app.UseOcelot();<br><br>app.Run();</pre><p>The ocelot.json content might look like this:</p><pre>{<br>  &quot;Routes&quot;: [<br>    {<br>      &quot;UpstreamPathTemplate&quot;: &quot;/products/{everything}&quot;,<br>      &quot;UpstreamHttpMethod&quot;: [ &quot;Get&quot; ],<br>      &quot;DownstreamPathTemplate&quot;: &quot;/api/products/{everything}&quot;,<br>      &quot;DownstreamScheme&quot;: &quot;http&quot;,<br>      &quot;DownstreamHostAndPorts&quot;: [<br>        {<br>          &quot;Host&quot;: &quot;product-service-api&quot;,<br>          &quot;Port&quot;: 5001<br>        }<br>      ],<br>      &quot;AuthenticationOptions&quot;: {<br>        &quot;AuthenticationProviderKey&quot;: &quot;GatewayKey&quot;,<br>        &quot;AllowedScopes&quot;: [] <br>      }<br>    }<br>  ],<br>  &quot;GlobalConfiguration&quot;: {<br>    &quot;BaseUrl&quot;: &quot;http://localhost:8099&quot;<br>  }<br>}</pre><p>What happens based on this configuration?<br>The Request: A client application sends a GET request to <a href="http://localhost:8099/products/161">http://localhost:8099/products/161</a>.</p><p>The Match: Ocelot intercepts the request and matches it against the defined routes. It identifies that the {everything} segment corresponds to 161.</p><p>The Translation: Ocelot maps this value to the downstream template.</p><p>The Execution: Internally, the gateway silently issues a GET request to <a href="http://product-service-api:5001/api/products/161">http://product-service-api:5001/api/products/161</a>, retrieves the response, and returns it to the client.</p><p>As a result, the end-user remains completely unaware that a service named “product-service-api” is running on port 5001 in the backend.</p><h3>Service Discovery</h3><p>Technically, it is possible to route incoming requests to backend services using static (hard-coded) URLs without utilizing service discovery, but this is generally considered an anti-pattern. Since service addresses can change every time they are redeployed, keeping the Ocelot configuration manually synchronized with these changes adds unnecessary operational complexity. Ocelot provides native support for Eureka, Consul, and Kubernetes-based service discovery mechanisms.</p><p>Since I prefer using Consul, here is a simple implementation example:</p><pre>dotnet add package Ocelot<br>dotnet add package Ocelot.Provider.Consul</pre><p>Program.cs:</p><pre>builder.Services<br>    .AddOcelot()<br>    .AddConsul();<br><br>var app = builder.Build();<br>await app.UseOcelot();</pre><p>The AddConsul() method activates the service discovery provider, allowing Ocelot to fetch backend addresses dynamically from Consul. In your ocelot.json:</p><pre>&quot;GlobalConfiguration&quot;: {<br>    &quot;ServiceDiscoveryProvider&quot;: {<br>      &quot;Host&quot;: &quot;localhost&quot;,<br>      &quot;Port&quot;: 8500,<br>      &quot;Type&quot;: &quot;Consul&quot;<br>    }<br>}</pre><blockquote><em>For more details: </em><a href="https://ocelot.readthedocs.io/en/latest/features/servicediscovery.html"><em>Ocelot Service Discovery Documentation</em></a></blockquote><h3>Caching and Rate Limiting</h3><p>Ocelot offers a built-in, lightweight caching mechanism at the API Gateway level. This feature is disabled by default. To activate it, you must add the Ocelot.Cache.CacheManager package and configure it:</p><pre>.AddOcelot()<br>.AddCacheManager(x =&gt; { x.WithDictionaryHandle(); })</pre><p>In this approach, the cache is stored in the memory of the gateway instance. This significantly reduces the load on backend services, especially for frequently called and rarely changing GET requests.</p><p>Ocelot also supports Rate Limiting to protect backend services from overloading. To enable rate limiting for a specific route, simply add the following JSON configuration:</p><pre>&quot;RateLimitOptions&quot;: {<br>  &quot;ClientWhitelist&quot;: [],<br>  &quot;EnableRateLimiting&quot;: true,<br>  &quot;Period&quot;: &quot;1s&quot;,<br>  &quot;PeriodTimespan&quot;: 1,<br>  &quot;Limit&quot;: 1<br>}</pre><p>Ocelot has many more features to offer. Depending on your needs, you can explore the following:</p><p>Load Balancing Documentation: <a href="https://ocelot.readthedocs.io/en/latest/features/loadbalancer.html">https://ocelot.readthedocs.io/en/latest/features/loadbalancer.html</a></p><p>Header Transformation Documentation: <a href="https://ocelot.readthedocs.io/en/latest/features/headerstransformation.html">https://ocelot.readthedocs.io/en/latest/features/headerstransformation.html</a></p><h3>Conclusion</h3><p>In the .NET ecosystem, Ocelot was unrivaled until the emergence of YARP. Even today, Ocelot remains highly popular due to the ready-to-use middleware solutions it provides for the microservice landscape.</p><p><strong>YARP</strong> (Yet Another Reverse Proxy) takes a lower-level and more flexible approach. While it offers a high-performance reverse proxy core, it does not provide many of Ocelot’s features (like rate limiting, caching, or service discovery) out of the box. Instead, it expects the developer to implement these capabilities manually. This makes YARP more suitable for teams with specialized requirements who want total control over gateway behavior.</p><p>If your priorities are rapid setup, standard gateway features, and low maintenance, Ocelot is the better choice. Conversely, if you are targeting maximum performance and a highly customizable gateway, YARP stands out. In practice, many teams start with Ocelot for mid-sized systems and migrate to YARP as their requirements become more complex.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=099c3ae5b768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Task Management in .NET with ConfigureAwaitOptions — Advanced ConfigureAwait]]></title>
            <link>https://medium.com/@rserit/modern-task-management-in-net-with-configureawaitoptions-advanced-configureawait-4c01db811f74?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c01db811f74</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 15:48:04 GMT</pubDate>
            <atom:updated>2026-01-20T15:48:04.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modern Task Management in .NET with ConfigureAwaitOptions — Advanced ConfigureAwait</h3><p>The Task.ConfigureAwait(false) we’ve been using for years is no longer enough on its own. With .NET 8, a new enum has been introduced that allows us to determine how the application reacts when a Task completes with much higher precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZBk9H7_gRyFkUOtuPUEGA.jpeg" /></figure><p>ConfigureAwait is one of the most critical and misunderstood concepts of asynchronous programming in the .NET ecosystem. Its primary purpose is to define which context the code should resume on after an await operation. Naturally, because we don’t fully grasp this underlying mechanism, we often struggle to understand the true meaning of the true/false assignments.</p><p>Many developers believe they’ve solved the problem simply by using ConfigureAwait(false). However, if the library you are calling or a method within .NET itself — neglects to use it, the application can still hang.</p><p>Using ConfigureAwait(false) is not a good strategy for preventing deadlocks, primarily because that isn’t its actual purpose. To prevent a deadlock when using direct blocking (such as .Result or .GetResult()), every piece of asynchronous code including libraries and the runtime would have to use ConfigureAwait(false). How feasible do you think that is? It is not a sustainable solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*MQeLw2jsmsyVb87NTTMErw.png" /></figure><blockquote><strong>ConfigureAwait</strong> is applied to the await operation rather than the task itself.</blockquote><p>Consider the following example where ConfigureAwait(false) is ineffective. Since ConfigureAwait(false) is only meaningful for an await operation and there is no await here, the usage has no impact. In fact, there is synchronous blocking involved:</p><pre>FetchAsync().ConfigureAwait(false).GetAwaiter().GetResult();</pre><p>In this case, the result of ConfigureAwait(false) is not being utilized. When you execute await task, it defaults to ConfigureAwait(true) by nature:</p><pre>var task = FetchAsync(); <br>task.ConfigureAwait(false); <br>await task;</pre><p>The correct approach is as follows: await FetchAsync().ConfigureAwait(false);</p><h3>ConfigureAwaitOptions</h3><p>ConfigureAwaitOptions is a new type providing various ways to define how awaitable objects are configured. It is available for use with $Task&lt;T&gt;$. bu options allow you to specify where and how the code continues execution after a task completes. This is particularly important for performance oriented developers.</p><pre>public enum ConfigureAwaitOptions<br>{<br>    None = 0x0,<br>    ContinueOnCapturedContext = 0x1,<br>    SuppressThrowing = 0x2,<br>    ForceYielding = 0x4,<br>}</pre><h3>None and ContinueOnCapturedContext</h3><p>None represents the default behavior and indicates that no specific flag has been assigned. While it forms a basis similar to the standard .ConfigureAwait(false) usage, it follows the system default flow when used alone.</p><p>ContinueOnCapturedContext is identical to the traditional ConfigureAwait(true). When the operation finishes, it forces a return to the awaited context such as SynchronizationContext or TaskScheduler. In UI applications, using this context becomes mandatory to update the interface.</p><p>For instance, a new thread is started while querying a domain. When this flag is used, we ensure that once the task completes its work, we return to the thread that initiated the UI action.</p><pre>public async void OnSearchButtonClick(object sender, EventArgs e)<br>{<br>    txtStatus.Text = &quot;Searching&quot;;<br><br>    await CheckDomainAsync(&quot;recepserit.com&quot;).ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext);<br><br>    txtStatus.Text = &quot;Available!&quot;; <br>}</pre><p>Had we used None, the execution would continue on any available thread from where it left off. By using this flag, we have preserved the context.</p><h3>ConfigureAwaitOptions.SuppressThrowing</h3><p>This is a critical option. Normally, if an error occurs during an await operation, an exception is re-raised at the call site. When this flag is active, no exception is thrown at the await line if the Task results in an error or is canceled. Instead, the task completes silently.</p><p>The SuppressThrowing option improves code readability, especially in cases where the success of an operation is not critical or when you prefer to manually check the error via the Task object. Let us prepare a scenario to understand this better.</p><p>Traditional exception handling with try-catch:</p><pre>public async Task SaveAsync()<br>{<br>    await SaveToDatabaseAsync();<br><br>    try <br>    {<br>        await SendAnalyticsAsync(); <br>    }<br>    catch (Exception ex)<br>    {<br>        Console.WriteLine(ex.Message);<br>    }<br>}</pre><p>With the new method, we can eliminate try-catch clutter because the await line will not throw an error. The exception is suppressed and only the Task completion is observed:</p><pre>using System.Threading.Tasks;<br><br>public async Task SaveDataAsync()<br>{<br>    await SaveToDatabaseAsync();<br><br>    Task analyticsTask = SendAnalyticsAsync().ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);<br>    <br>    await analyticsTask;<br><br>    // Checking if an error occurred<br>    if (analyticsTask.IsFaulted)<br>    {<br>        Console.WriteLine($&quot;Error: {analyticsTask.Exception?.InnerException?.Message}&quot;);<br>    }<br>}</pre><p>The error still resides within the Task object since IsFaulted remains true, but the await operator does not throw this error as a runtime Exception. It should never be used for critical operations like database records or payment processing, as you might overlook a failed process.</p><p>A domain search scenario is an excellent example for using SuppressThrowing. Specifically, when a user searches for a domain name and a new request is sent for every character typed, you want to cancel old requests and ensure a clean start.</p><p>Autocomplete example:</p><pre>private CancellationTokenSource? _cts;<br>private Task? _currentSearchTask;<br><br>public async Task OnSearchChangedAsync(string domainName)<br>{<br>    _cts?.Cancel();<br>    if (_currentSearchTask != null)<br>    {<br>        await _currentSearchTask.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);<br>    }<br><br>    // Create a new cancellation token and task<br>    _cts = new CancellationTokenSource();<br>    <br>    // Start new search<br>    _currentSearchTask = SearchAsync(domainName, _cts.Token);<br>    <br>    await _currentSearchTask;<br>}<br><br>private async Task SearchAsync(string domain, CancellationToken token)<br>{<br>    // API request or database query simulation<br>    await Task.Delay(500, token); <br>    Console.WriteLine($&quot;{domain}&quot;);<br>}</pre><p>What have we achieved here? If a user quickly types “recep,” separate tasks start for “r,” “re,” and “rec.” With every character, the previous task is canceled. Naturally, this example can be further improved; in modern domain search systems, this kind of frequent request approach might trigger rate limit violations.</p><p>When a method returns a Task, the await operation simply waits for the work to complete without returning a value. If we use SuppressThrowing, no exception will be raised. However, if a method returns Task&lt;T&gt;, the await line must produce a value of that specific type upon completion. Since the system cannot make this decision on your behalf, using this flag with Task&lt;T&gt; is not permitted. In other words, you cannot use SuppressThrowing because the question of what the result should be in the event of an error remains unanswered.</p><p>If you attempt such a usage, the line where you use <em>SuppressThrowing</em> will trigger a CA2261 warning and throw an <strong>ArgumentOutOfRangeException</strong> at runtime.</p><pre>Task&lt;bool&gt; task = SearchAsync(&quot;example.com&quot;);<br><br>// This will cause a CA2261 warning and a runtime error<br>bool result = await task.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);</pre><blockquote>CA2261 reference: <a href="https://github.com/dotnet/roslyn-analyzers/pull/6669">https://github.com/dotnet/roslyn-analyzers/pull/6669</a></blockquote><p>A quick note: Normally, when you do not use await and instead use the .GetAwaiter().GetResult() blocking method to wait for completion, any exception within the Task is thrown immediately. SuppressThrowing can now suppress the error during this blocking moment as well.</p><pre>saveTask.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing)<br> .GetAwaiter()<br> .GetResult();<br>Console.WriteLine(&quot;Task completed&quot;);</pre><p>So, what is new here? In older .NET versions, ConfigureAwait(false) only determined where the execution would continue. If an error occurred when calling .GetResult(), that error was thrown regardless, forcing you to write a try-catch block. With .NET 8, ConfigureAwait no longer just configures how you continue, but also how you wait. It prevents errors from leaking out.</p><h3>ConfigureAwaitOptions.ForceYielding</h3><p>Normally, if a Task is already completed, the await operator continues executing the remainder of the code synchronously. When this flag is used, even if the Task is finished, it forces the current thread to be released and mandates an asynchronous scheduling via a yield. Essentially, the ForceYielding option allows the asynchronous method to “courteously” relinquish thread usage.</p><p>If an awaited Task is already complete, the .NET runtime continues execution synchronously on the same thread for the sake of efficiency. However, this can sometimes lead to UI freezes if a long-running thread is involved.</p><pre>using System.Threading.Tasks;<br><br>public async Task ProcessDataAsync()<br>{<br>    for (int i = 0; i &lt; 1000000; i++)<br>    {<br>        DoLightWork(i);<br><br>        // Thanks to ForceYielding, it pauses here and hands over the thread to other tasks (like UI updates).<br>        if (i % 1000 == 0)<br>        {<br>            await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);<br><br>            UpdateStatusText($&quot;Processing: %{i / 10000}&quot;);<br>        }<br>    }<br>}</pre><p>In this scenario, even though the Task is finished, the runtime acts as if the process is still ongoing. This is particularly useful if you have operations that complete very quickly but are repeated thousands of times.</p><p>This feature is most beneficial when used alongside cancellation operations. In some cases, code needs to cancel a task and wait for that existing task to fully complete before starting a new one.</p><h3>ForceYielding | SuppressThrowing</h3><p>Let’s look at an example of using these together. We will develop a method that deletes temporary files for an application. These files might cause errors during deletion. We will test this using both flags.</p><p>By using ForceYielding: The thread used for each file is released to prevent UI freezes. By using SuppressThrowing: Even if a file is in use, it will not throw an exception and will simply move to the next file.</p><pre>using System.Threading.Tasks;<br>using System.IO;<br><br>public async Task RunBackgroundCleanupAsync(string folderPath)<br>{<br>    var files = Directory.GetFiles(folderPath);<br><br>    foreach (var file in files)<br>    {<br>        await DeleteFileAsync(file).ConfigureAwait(<br>            ConfigureAwaitOptions.ForceYielding | ConfigureAwaitOptions.SuppressThrowing<br>        );<br><br>        // Execution continues regardless of individual file errors<br>    }<br>}<br><br>private async Task DeleteFileAsync(string filePath)<br>{<br>    File.Delete(filePath);<br>    await Task.CompletedTask; <br>}</pre><p>Introduced with .NET 8, ConfigureAwaitOptions expands this previously restricted area, offering developers complete mastery over the lifecycle of asynchronous tasks. We can now control not just which thread the code continues on, but the very flow of the execution itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c01db811f74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Transactional Outbox Pattern in .NET Microservices — Ensuring Eventual Consistency]]></title>
            <link>https://towardsdev.com/implementing-transactional-outbox-pattern-in-net-microservices-ensuring-eventual-consistency-6bbc1c1d4830?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bbc1c1d4830</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[micoservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 21:28:10 GMT</pubDate>
            <atom:updated>2026-01-20T07:22:12.718Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Implementing Transactional Outbox Pattern in .NET </strong>Microservices<strong> — Ensuring Eventual Consistency</strong></h3><p>In monolithic systems, database operations rely on ACID principles. A transaction either completes entirely or not at all. However, in microservices, data is distributed. It is not enough for a single service to save data; other services must also be notified of this change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6AgW1t16YBkr8ujQo05Hw.jpeg" /></figure><p>In this article, we will examine how to reduce these two operations into a single atomic unit by implementing the Transactional Outbox Pattern on .NET, and how to guarantee data integrity across systems using the principle of Eventual Consistency.</p><h3>The Dual-Write Problem</h3><p>Let’s look at a code example to better explain this.</p><pre>public async Task SaveAsync(ReserveCarCommand request)<br>{<br>    using (var uow = uowProvider.Create())<br>    {<br>        var car = await uow.Cars.GetById(request.CarId);<br>        car.Reserve(request.CustomerId, request.Days);<br>        uow.Cars.Update(car);<br>        <br>        // Database Commit<br>        await uow.CommitChanges();  <br><br>        // Message Publishing<br>        var evt = new CarReservedEvent(car.Id);<br>        await eventPublisher.PublishMessage(evt);<br><br>        return new ReservationResult {<br>            ReservationId = car.CurrentReservationId,<br>            IsSuccess = true<br>        };<br>    }<br>}</pre><p>The basic strategy used here is to ensure the database record is saved and then inform other services. If we had published the event first and left the database commit for last, a constraint error or connection loss in the database could occur while the message was already on its way. In other words, it is no coincidence that the CommitChanges method precedes PublishMessage. This is an effort to protect data accuracy. If an error occurs during the commit, no data is written to the database, so there is no inconsistency.</p><p>But what happens if the message queue is unreachable or there is a network issue and the message publishing fails? As in the example, the car rental request would exist in our database, but other services would never know about it; therefore, you fail to reach eventual consistency. This issue is known as the “Dual-Write” problem.</p><blockquote>Many developers fall into the trap of thinking, “RabbitMQ never crashes, so there won’t be a problem sending messages.” While RabbitMQ is built on a robust infrastructure (Erlang/OTP) and is self-healing, the network path to it can break, the server’s disk can fill up, or RAM failures can occur. Therefore, you should treat this not as an anomaly, but as an expected scenario.</blockquote><p>“Retry” mechanisms provided by libraries like Polly only serve to tolerate momentary and transient network outages; they mitigate symptoms rather than solving the root cause. Technically, this approach still carries a risk to the entire system because it keeps the message in the application’s memory (RAM). If Polly exceeds its retry limits, that message will be deleted and lost forever. Thus, while the Polly package mathematically reduces the probability of error, it does not architecturally eliminate the “Dual-Write” problem.</p><p>How do you permanently solve data inconsistency by establishing an atomic bond between database operations and the message queue in a microservice architecture?</p><h3>The Outbox Pattern</h3><p>Instead of sending a message directly to the message queue over the network, with the Outbox Pattern, we save the message to our own microservice database as part of the existing transaction. This ensures internal consistency within our service. If the transaction is rolled back, no message is ever “sent.” Since our message is now stored in an “Outbox table” within the database, we need a process to relay it to the message queue. By creating a background job that polls this table at specific intervals and attempts to publish the messages, we can update the status in the table based on the result. Consequently, we ensure that the event is published with absolute certainty.</p><p>Let’s explain this using our previous example. When a customer reserves a car, updating the car’s status to “reserved” and writing the “Car Reserved” message into the Outbox table becomes a single, atomic database package. This guarantees internal consistency; the likelihood of telling the billing service to “issue an invoice” without actually reserving the car is eliminated.</p><p>If the background worker attempts to send the same message a second time, a “duplicate message” issue may arise, but this must be handled on the consumer side. The receiving service checks the ID within the message, realizes “I have already issued an invoice for this reservation,” and discards the duplicate message. The error is gone!</p><p>Thanks to the Outbox Pattern, you can prevent your primary system from being affected by network failures, guarantee that no messages are lost, and make the system entirely secure by shifting the only remaining risk (the duplicate message problem) to the receiver.</p><blockquote>Another article where I discuss the Outbox Pattern structure: <a href="https://medium.com/@rserit/understanding-sql-and-nosql-distributed-transaction-problem-in-c-transactional-outbox-pattern-69ded2dad63c">https://medium.com/@rserit/understanding-sql-and-nosql-distributed-transaction-problem-in-c-transactional-outbox-pattern-69ded2dad63c</a></blockquote><h3>Practical Implementation</h3><p>Here is a simple example of an Outbox table in SQL:</p><pre>CREATE TABLE app.OutboxMessages<br>(<br>    [Id] UNIQUEIDENTIFIER NOT NULL,<br>    [CreatedDate] DATETIME2 NOT NULL,<br>    [Type] VARCHAR(255) NOT NULL,<br>    [Data] VARCHAR(MAX) NOT NULL,<br>    [IsProcessCompleted] BIT NOT NULL<br>)</pre><p>The entity object we create for this table might look like this:</p><pre>public class OutboxMessage<br>{<br>    public Guid Id { get; private set; }<br>    public DateTime CreatedDate { get; private set; }<br><br>    /// &lt;summary&gt;<br>    /// Full name of the message type.<br>    /// &lt;/summary&gt;<br>    public string Type { get; private set; }<br><br>    /// &lt;summary&gt;<br>    /// Serialized to JSON.<br>    /// &lt;/summary&gt;<br>    public string Data { get; private set; }<br><br>    public bool IsProcessCompleted { get; private set; }<br><br>    private OutboxMessage() { }<br><br>    internal OutboxMessage(string type, string data)<br>    {<br>        this.Id = Guid.NewGuid();<br>        this.CreatedDate = DateTime.Now;<br>        this.Type = type;<br>        this.Data = data;<br>        this.IsProcessCompleted = false;<br>    }<br>}</pre><p><strong>Persisting the Messages</strong><br>Now, let’s move on to saving the messages. Manually writing the code to add a message to the Outbox table inside every single command handler would be a poor design choice. Instead, we need to centralize this process.</p><p>We must bundle the user data and the Outbox message into the same atomic package before sending them to the database. The database will then either accept both or reject both. This eliminates the risk where the database is updated but the message is lost. Furthermore, writing explicit Outbox registration code every time leads to unnecessary repetition. The system should handle this automatically.</p><p><strong>Implementing the Unit of Work</strong></p><pre>public async Task&lt;int&gt; CommitAsync(CancellationToken token = default)<br>{<br>    var notifications = await _domainEventsDispatcher.DispatchEventsAsync(this);<br><br>    if (!notifications.Any())<br>    {<br>        return await base.SaveChangesAsync(token);<br>    }<br><br>    var messages = notifications.Select(notification =&gt; <br>    {<br>        var type = notification.GetType().FullName;<br>        var data = JsonSerializer.Serialize(notification);<br>        return new OutboxMessage(type, data);<br>    }).ToList();<br><br>    await this.OutboxMessages.AddRangeAsync(messages, token);<br>    return await base.SaveChangesAsync(token);<br>}</pre><p>The line DispatchEventsAsync(this) is not the moment events are actually published to message queues or other services. Instead, it is the final preparation stage before these events are packaged and stored in the database. During this process, all domain events accumulated on the domain entities up to that point are collected and converted into “notification” objects suitable for database storage.</p><p>We must write this data securely into the “Outbox” table. By doing so, the actual database record and the notifications to be sent to other services are wrapped in the same database transaction, guaranteeing full system consistency.</p><p><strong>Creating the Domain Event</strong></p><pre>public record OrderCreatedEvent(Guid OrderId, decimal TotalAmount, Guid CustomerId) : IDomainEvent;<br><br>public class OrderCreatedNotification : DomainNotificationBase&lt;OrderCreatedEvent&gt;<br>{<br>    public Guid OrderId { get; init; }<br>    public decimal TotalAmount { get; init; }<br><br>    public OrderCreatedNotification(OrderCreatedEvent domainEvent) : base(domainEvent)<br>    {<br>        this.OrderId = domainEvent.OrderId;<br>        this.TotalAmount = domainEvent.TotalAmount;<br>    }<br><br>    // This constructor is used during the deserialization process.<br>    [JsonConstructor]<br>    public OrderCreatedNotification(Guid orderId, decimal totalAmount) : base(null)<br>    {<br>        this.OrderId = orderId;<br>        this.TotalAmount = totalAmount;<br>    }<br>}</pre><p>The OrderCreatedNotification class features two constructors. The first is designed to create a notification from a domain event. The second is related to the processing phase; it allows the system to recreate the object via deserialization when reading records back from the database.</p><p><strong>Implementing the Asynchronous Process</strong></p><p>To implement our asynchronous process, we will utilize BackgroundService. While we could use packages like Hangfire or Quartz.NET, they might be overkill for a small-scale solution. Instead, we prefer using native .NET Core features. While those libraries offer advanced features like persistent job storage and automatic retries for failed tasks, they introduce unnecessary complexity for a simple application that merely scans a table and sends messages.</p><p>For more details, see the official documentation: <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice">BackgroundService in .NET</a></p><p><strong>The Hosted Service Structure</strong></p><p>We need a timer that triggers at specific intervals — for example, every 10 seconds. To prevent race conditions where the function might be called twice simultaneously (potentially leading to duplicate sends), we ensure sequential execution. When the function runs, it reads the outbox queue and attempts to send each message. For each message, we try to publish it using our message bus (e.g., RawRabbit); if successful, we remove the message from the database.</p><p>Processor:</p><pre>public class OutboxProcessor<br>{<br>    private readonly AppDbContext _context;<br>    private readonly IMessageBus _bus;<br><br>    public OutboxProcessor(AppDbContext context, IMessageBus bus)<br>    {<br>        _context = context;<br>        _bus = bus;<br>    }<br><br>    public async Task ProcessMessagesAsync()<br>    {<br>        var messages = await _context.OutboxMessages<br>            .OrderBy(m =&gt; m.CreatedDate)<br>            .Take(100)<br>            .ToListAsync();<br><br>        foreach (var message in messages)<br>        {<br>            try <br>            {<br>                var notificationType = Type.GetType(message.Type);<br>                var notification = JsonSerializer.Deserialize(message.Data, notificationType);<br><br>                // Event publish<br>                await _bus.PublishAsync(notification);<br><br>                // If successful, remove the message<br>                _context.OutboxMessages.Remove(message);<br>                await _context.SaveChangesAsync();<br>            }<br>            catch (Exception ex)<br>            {<br>                // Log the error<br>                Console.WriteLine($&quot;Error: {ex.Message}&quot;);<br>                break; // Stop processing the batch and retry in the next cycle<br>            }<br>        }<br>    }<br>}</pre><p>The Background Service:</p><pre>public class OutboxSendingService : BackgroundService<br>{<br>    private readonly IServiceProvider _serviceProvider;<br>    private readonly TimeSpan _period = TimeSpan.FromSeconds(5);<br><br>    public OutboxSendingService(IServiceProvider serviceProvider)<br>    {<br>        _serviceProvider = serviceProvider;<br>    }<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            using (var scope = _serviceProvider.CreateScope())<br>            {<br>                var processor = scope.ServiceProvider.GetRequiredService&lt;OutboxProcessor&gt;();<br>                await processor.ProcessMessagesAsync();<br>            }<br><br>            // Since we await the delay, a new loop won&#39;t start until the previous one finishes.<br>            await Task.Delay(_period, stoppingToken);<br>        }<br>    }<br>}</pre><p>In the BackgroundService, we use await Task.Delay, which ensures that one cycle finishes before the next begins. Since database contexts (DbContext) typically have a Scoped lifetime and background services are Singletons, using CreateScope() to access the database in each iteration is a technical requirement.</p><p>Program.cs:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>// Must be Scoped because it accesses the DbContext<br>builder.Services.AddScoped&lt;OutboxProcessor&gt;();<br><br>builder.Services.AddSingleton&lt;IMessageBus, RabbitMQBus&gt;();<br><br>// Enters an infinite loop in the background as soon as the app starts<br>builder.Services.AddHostedService&lt;OutboxSendingService&gt;();<br><br>var app = builder.Build();<br>app.Run();</pre><h3>Conclusion</h3><p>In conclusion, this architecture reliably solves the most common data inconsistency problem in distributed systems. By using the Transactional Outbox Pattern, you keep both your primary business data and the associated notifications under the same transaction, completely eliminating the risk of one succeeding while the other fails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bbc1c1d4830" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/implementing-transactional-outbox-pattern-in-net-microservices-ensuring-eventual-consistency-6bbc1c1d4830">Implementing Transactional Outbox Pattern in .NET Microservices — Ensuring Eventual Consistency</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-Performance Dictionary Strategies in .NET — Immutable and Frozen Dictionary]]></title>
            <link>https://towardsdev.com/high-performance-dictionary-strategies-in-net-immutable-and-frozen-dictionary-c54ffb05f8ce?source=rss-f82b03bf7611------2</link>
            <guid isPermaLink="false">https://medium.com/p/c54ffb05f8ce</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[high-performance]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Recep Serit]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 21:09:33 GMT</pubDate>
            <atom:updated>2026-01-14T06:47:07.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>High-Performance Dictionary Strategies in .NET — Immutable and Frozen Dictionary</h3><p>In high-traffic .NET systems, performance and thread-safety are of critical importance. Small differences between data structures can lead to significant variances in CPU and memory usage in scenarios where thousands of requests are processed per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5c-qAu5R7RJZnysf5CGs_Q.jpeg" /></figure><p>The Dictionary structures used within .NET are fundamental classes that allow for the efficient storage and retrieval of data. They create a list by taking a unique TKey and a TValue. The primary advantage of using a Dictionary is the fast lookup capability, as every element possesses a unique key.</p><p>When we discuss “Dictionaries” in a high-traffic system, we are essentially debating data mutability and access speed.</p><h3>Cloned Dictionary</h3><p>It is important to note that “Cloned Dictionary” is not an actual class name in .NET literature; this is a common point of confusion. Rather, it is a design pattern used in high-traffic systems. In essence, it refers to taking a full copy of a standard Dictionary object’s current state to create an independent instance. This is typically achieved by copying an existing element (e.g., new Dictionary(existingDict)).</p><pre>var original = new Dictionary&lt;int, string&gt; { { 1, &quot;Data&quot; } };<br>var clone = new Dictionary&lt;int, string&gt;(original);<br><br>var filteredClone = original.Where(x =&gt; x.Key &gt; 0).ToDictionary(x =&gt; x.Key, x =&gt; x.Value);</pre><p>This structure is fully mutable; however, every cloning operation occupies new space in memory. If you intend to perform a bulk update and then only read from the collection, creating and cloning a Dictionary is much more CPU-friendly.</p><p>The disadvantage is that as the number of elements in the dictionary increases, the allocation cost grows accordingly. Large new areas of memory are allocated for every operation.</p><h3>Immutable Dictionary</h3><p>In the .NET system, the standard Dictionary is mutable by nature, meaning its content can be updated dynamically. In contrast, ImmutableDictionary has an immutable (unchangeable) structure, which preserves data integrity. In this structure, every update operation returns a new instance containing the change instead of modifying the original dictionary.</p><p>Once an immutable dictionary is created, its content cannot be altered. This means values for existing keys cannot be updated, new keys cannot be added, and existing keys cannot be deleted. If a change is required, the current dictionary remains preserved, and a new dictionary instance (a new reference) containing the change is returned. This guarantees that the data always remains constant.</p><p>This structure is provided within the System.Collections.Immutable library. When you expose data via an ImmutableDictionary, the process involves merely passing a memory address (reference) because the data itself is unchangeable. Your resource cost is near zero.</p><p>However, the immutability rule mandates that for every new element added, a brand-new object containing that change must be allocated in memory rather than updating the existing structure. This creates a significant performance overhead during write operations. Furthermore, these collections are built on a hierarchical tree structure rather than the high-speed “hash table” architecture used by standard dictionaries. In this structure, you traverse branches to find a key rather than accessing it directly, which makes the lookup process heavier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*YB4p4MPtWHRGJpplI06-9w.png" /></figure><p>One of the most critical reasons for using immutable structures is the thread-safety problem. Due to its inherent nature, a standard Dictionary requires synchronization when accessed by multiple threads simultaneously. Because concurrent requests occur, locks must be implemented, which inevitably leads to performance degradation. Since data within an Immutable Dictionary never changes, it can be read safely by multiple threads without any locking overhead.</p><p>You can initialize an immutable dictionary directly or convert an existing one:</p><pre>using System.Collections.Immutable;<br><br>// Direct initialization<br>var dict = ImmutableDictionary&lt;int, string&gt;.Empty<br>            .Add(1, &quot;Domain&quot;)<br>            .Add(2, &quot;Hosting&quot;);<br><br>// Converting from a standard Dictionary<br>var source = new Dictionary&lt;int, string&gt; { { 3, &quot;Cloud&quot; } };<br>ImmutableDictionary&lt;int, string&gt; immutableDict = source.ToImmutableDictionary();</pre><p>For better performance during the creation phase (to avoid creating multiple intermediate instances), you can use the <strong>Builder</strong> pattern:</p><pre>var builder = ImmutableDictionary.CreateBuilder&lt;int, string&gt;();<br>builder.Add(1, &quot;EPP&quot;);<br>builder.Add(2, &quot;API&quot;);<br>builder.Add(3, &quot;XML&quot;);<br><br>ImmutableDictionary&lt;int, string&gt; finalDict = builder.ToImmutable();</pre><h3>Frozen Dictionary</h3><p>Introduced as a newer class in .NET, the FrozenDictionary is a structure specifically optimized for “read-heavy, write-rarely” datasets in high-traffic systems. It is a highly engineered collection.</p><p>A standard Dictionary always assumes new data might be added; therefore, it uses a flexible but slower architecture to manage potential collisions. In contrast, a FrozenDictionary knows all its data at the time of creation. This allows it to run a specialized algorithm that positions every key perfectly within the hash table. During a read operation, there is no need for collision checks because the location of the data is determined instantly.</p><p>FrozenDictionary stores data close together in memory, ensuring it fits efficiently within the CPU cache. Once the structure is “frozen,” its layout is fixed. While thousands of threads perform simultaneous reads, no locks or tracking mechanisms are required. This results in extraordinary execution speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*9Zomaf3CWN0unPmKsxBbPA.jpeg" /></figure><p>This speed, of course, comes at a price. When you call the ToFrozenDictionary() method, .NET analyzes all keys in the background and calculates the most efficient hash function possible. It then builds a brand-new, optimized table in memory. Consequently, if you have thousands of records and attempt to “freeze” them frequently, you will encounter a significant write-operation cost.</p><p>Let’s create a cache class using FrozenDictionary to illustrate its practical use:</p><pre>using System.Collections.Frozen;<br><br>public class LocalizationProvider<br>{<br>    // Created once, read by thousands of threads throughout the app lifecycle.<br>    private static readonly FrozenDictionary&lt;string, string&gt; ErrorRegistry;<br><br>    static LocalizationProvider()<br>    {<br>        var sourceData = new Dictionary&lt;string, string&gt;<br>        {<br>            { &quot;AUTH_001&quot;, &quot;Invalid Credentials&quot; },<br>            { &quot;AUTH_002&quot;, &quot;Token Expired&quot; },<br>            { &quot;SYS_001&quot;, &quot;Internal Server Error&quot; }<br>        };<br><br>        // .NET performs a deep analysis here to create a &quot;Perfect Hash Table&quot;.<br>        ErrorRegistry = sourceData.ToFrozenDictionary();<br>    }<br><br>    public string GetMessage(string code)<br>    {<br>        // Read speed is significantly faster than a standard Dictionary.<br>        return ErrorRegistry.GetValueOrDefault(code, &quot;Unknown Error&quot;);<br>    }<br>}</pre><h3>Benchmarks</h3><p>To help you decide which structure to use, I have created a simple benchmark comparison. You can test these in your own environment to see the performance delta.</p><pre>using BenchmarkDotNet.Attributes;<br>using BenchmarkDotNet.Running;<br>using System.Collections.Immutable;<br>using System.Collections.Frozen;<br><br>namespace DictionaryBenchmarks<br>{<br>    [MemoryDiagnoser]<br>    public class HighTrafficBenchmarks<br>    {<br>        private Dictionary&lt;int, string&gt; _sourceData;<br>        <br>        // 1. Source for Cloned Dictionary scenario<br>        private Dictionary&lt;int, string&gt; _standardDict;<br>        <br>        // 2. Instance for Immutable Dictionary scenario<br>        private ImmutableDictionary&lt;int, string&gt; _immutableDict;<br>        <br>        // 3. Instance for Frozen Dictionary scenario<br>        private FrozenDictionary&lt;int, string&gt; _frozenDict;<br><br>        private int _searchKey;<br><br>        [GlobalSetup]<br>        public void Setup()<br>        {<br>            // Prepare a dataset with 10,000 elements<br>            _sourceData = Enumerable.Range(1, 10000)<br>                                    .ToDictionary(i =&gt; i, i =&gt; $&quot;Value-{i}&quot;);<br><br>            _standardDict = new Dictionary&lt;int, string&gt;(_sourceData);<br>            _immutableDict = _sourceData.ToImmutableDictionary();<br>            _frozenDict = _sourceData.ToFrozenDictionary();<br>            <br>            // Look up a key in the middle of the range<br>            _searchKey = 5000;<br>        }<br><br>        // SCENARIO 1: User permissions (cloning)<br>        [Benchmark]<br>        public Dictionary&lt;int, string&gt; Clone_UserPermissions_Benchmark()<br>        {<br>            return new Dictionary&lt;int, string&gt;(_standardDict);<br>        }<br><br>        // SCENARIO 2: Metadata tags (thread-safe read)<br>        [Benchmark]<br>        public string Immutable_MetadataTags_Lookup()<br>        {<br>            return _immutableDict[_searchKey];<br>        }<br><br>        // SCENARIO 3: Currency rates (ultra-fast read)<br>        [Benchmark]<br>        public string Frozen_CurrencyRates_Lookup()<br>        {<br>            return _frozenDict[_searchKey];<br>        }<br>    }<br><br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var summary = BenchmarkRunner.Run&lt;HighTrafficBenchmarks&gt;();<br>        }<br>    }<br>}</pre><p>I have designed the following scenarios to test the specific strengths and weaknesses of each collection type:</p><p><strong>Cloned Dictionary </strong>(User Permissions): In this test, we implemented a user permissions example. The operation involves calling new Dictionary(_standardDict). Here, we are measuring the creation cost rather than the read speed. This benchmark demonstrates exactly how expensive it is to clone an item on every request in a high-traffic environment.</p><p><strong>Immutable Dictionary</strong> (Metadata Tags): For this structure, we used a metadata tags example. We measure the read speed using _immutableDict[_searchKey]. Because this structure utilizes a Tree-based architecture, you will notice the results are slower than FrozenDictionary, yet it remains natively thread-safe.</p><p><strong>Frozen Dictionary</strong> (Currency Rates): We applied a currency rates example, measuring the read speed with _frozenDict[_searchKey]. Since the read operation is performed via perfect hashing, this method yields the lowest (fastest) values in the benchmark results. This should be the definitive choice for global, static reference data queried millions of times per second across an application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*JDKLEUZMIV0O4TUWrcpg9w.jpeg" /></figure><h3>Conclusion</h3><p>Achieving high performance in high-traffic .NET applications is not just about writing correct code. It is about selecting the data structure that best fits the lifecycle of your data.</p><p>For Static or Periodically Updated Data: If your data consists of constant references that never change during the application’s lifetime (such as ISO codes, language, or country lists) or data that updates periodically (such as currency rates), the “perfect hash” optimization offered by FrozenDictionary (introduced in .NET 8) is indisputably the fastest and most efficient solution.</p><p>For Functional Architectures and Data Integrity: On the other hand, in functional architectures where data changes frequently and thread-safety is the primary concern, ImmutableDictionary should be your go-to choice.</p><p>Ultimately, the choice depends on your priority: if you can tolerate a high initial write/creation cost in exchange for the absolute fastest read speeds, choose Frozen. If you need to ensure data integrity at every step of a transformation, choose Immutable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c54ffb05f8ce" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/high-performance-dictionary-strategies-in-net-immutable-and-frozen-dictionary-c54ffb05f8ce">High-Performance Dictionary Strategies in .NET — Immutable and Frozen Dictionary</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>