<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ihar Maiseyeu's blog]]></title><description><![CDATA[Software engineer with 15 years of experience. Developed web and desktop applications using C# and Angular. My points of interest are .NET, Microservices, Azure]]></description><link>https://iharmaiseyeu.net</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 19:51:05 GMT</lastBuildDate><atom:link href="https://iharmaiseyeu.net/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Saga Pattern: Coordinating Transactions Across Microservices]]></title><description><![CDATA[Saga pattern for consistent, resilient microservices transactions. Learn Choreography, Orchestration & compensating actions for distributed workflows.]]></description><link>https://iharmaiseyeu.net/saga-pattern-coordinating-transactions-across-microservices</link><guid isPermaLink="true">https://iharmaiseyeu.net/saga-pattern-coordinating-transactions-across-microservices</guid><category><![CDATA[saga]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[distributed-transactions]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Wed, 09 Sep 2026 08:33:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/7c3c0c92-2600-4555-b557-8517043e8e45.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>In a monolithic application, transactions are straightforward: if something fails, you roll back the entire operation. But in a microservices architecture, where each service owns its database (and may even use different technologies), this approach breaks down. Services might be written in different languages, use NoSQL databases, or avoid databases entirely.</p>
<p>In such an environment, we cannot guarantee that an operation will succeed immediately or at all. This is where the Saga pattern comes in. It provides a way to coordinate transactions across multiple services, ensuring consistency even when direct rollbacks aren’t possible.</p>
<h1>What Is the Saga Pattern?</h1>
<h2>The Problem</h2>
<p>Let’s illustrate the problem with an online shop:</p>
<ol>
<li><p>A customer adds items to their cart and creates an order.</p>
</li>
<li><p>The <strong>Order Service</strong> saves the order and triggers a payment.</p>
</li>
<li><p>The <strong>Accounting Service</strong> processes the payment.</p>
</li>
<li><p>The <strong>Warehouse Service</strong> reserves the items.</p>
</li>
<li><p>The <strong>Delivery Service</strong> schedules shipping.</p>
</li>
</ol>
<p>It can be represented in the following flow:</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/f7e086f8-4110-4b67-9b21-76d87019843c.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi82MGYzNDgwMS05ZTAyLTQzNWEtOGFjMy0wODQ2YjI0NjNiMmEvMDEuc3ZnIiwidHlwZSI6ImF0dGFjaG1lbnQiLCJpYXQiOjE3ODg1MDUyMDAsImV4cCI6MTc4OTExMDAwMH0.Hvs0EzMLom5tM6nS9_S3pHD21WcmOanlbVu0HQn30Yg" alt="" style="display:block;margin:0 auto" />

<p>But what if the warehouse runs out of stock after payment?<br />Now, the system is in an inconsistent state:</p>
<ul>
<li><p>The customer’s money is taken (<strong>Accounting</strong>).</p>
</li>
<li><p>The order exists (<strong>Order Service</strong>).</p>
</li>
<li><p>The items can’t be shipped (<strong>Warehouse</strong>).</p>
</li>
<li><p>The delivery is created (<strong>Delivery</strong>).</p>
</li>
</ul>
<p>This mismatch between the actual and desired state is the problem the Saga pattern solves.</p>
<h2><strong>Compensating Transactions</strong></h2>
<p>The Saga pattern addresses this by defining compensating transactions. These are not true transactions but new operations that reverse the effect of previous steps, and they may not perfectly undo the original action.</p>
<p>Additionally compensating actions may introduce their own issues if they fail or are implemented incorrectly. A retry or escalating mechanism needs to be implemented.</p>
<p>Look at the actions from our example and their compensating transactions in the table below:</p>
<table>
<thead>
<tr>
<th><strong>Service</strong></th>
<th><strong>Action</strong></th>
<th><strong>Compensating transaction</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Order</td>
<td>CreateOrder</td>
<td>CancelOrder</td>
</tr>
<tr>
<td>Accounting</td>
<td>CompletePayment</td>
<td>RefundPayment</td>
</tr>
<tr>
<td>Warehouse</td>
<td>BookInventory</td>
<td>ReleaseInventory</td>
</tr>
<tr>
<td>Delivery</td>
<td>CreateDelivery</td>
<td>CancelDelivery</td>
</tr>
</tbody></table>
<p>These compensating actions ensure the system can roll back to a consistent state, even if the original flow fails.</p>
<p>For a better understanding of how it works better to look at the graph representation of the flow with compensating transactions.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/ed5c2641-e6d5-48a4-98ea-fa110ca94546.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi8xOTg0ZWQ0My03ZWI4LTQ1ODgtYjA4MS04ODcyZWUxY2UwOWQvMDMuc3ZnIiwidHlwZSI6ImF0dGFjaG1lbnQiLCJpYXQiOjE3ODg1MDUyMDAsImV4cCI6MTc4OTExMDAwMH0.jGEt9KSyqgFGSPBdNC3z_5fvEFaauPyZhJrvzsyXSbI" alt="" style="display:block;margin:0 auto" />

<p>On the left we have the normal flow of events and on the right the compensating transactions for these events. It is worth to draw such diagrams when you work with sagas, because it can clearly show you all compensating transactions in the system and when they are used.</p>
<blockquote>
<p>When we hear the word “transaction" we think about the transaction in the relational database which either executes completely or revert all changes. Compensating transactions rely on events and they completely lack of isolation. Thus they cannot be considered as ACID-compliant, but rather ACD.</p>
</blockquote>
<p>There are two common ways to implement the Saga pattern: <a href="https://iharmaiseyeu.net/choreography-pattern-in-microservices">Choreography</a> and <a href="https://iharmaiseyeu.net/orchestration-pattern-in-microservices">Orchestration</a>.</p>
<h2>Choreography saga</h2>
<p>In a Choreography-based Saga, services communicate asynchronously via events, acting as both producers and consumers. There is no central controller so that each service reacts to events and publishes its own.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/c69e5a18-d08f-4b3e-a1fc-10aac3fd676a.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi80ZjEzYTRhYi1mY2YyLTRiZmQtYWFjYi05NjBkMjQyOTcxMzAvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4ODUwNTIwMCwiZXhwIjoxNzg5MTEwMDAwfQ.0SQPKktI4kXsZyd1xqBdfErG0fvuQmLWkgg7k0of8hA" alt="" style="display:block;margin:0 auto" />

<h3><strong>How it works</strong>:</h3>
<ol>
<li><p>A user makes a request to create an order. The <strong>Order Service</strong> creates the order in its database and publishes the event <strong>OrderCreated</strong>.</p>
</li>
<li><p>The <strong>Message Broker</strong> sends the <strong>OrderCreated</strong> event to the <strong>Warehouse</strong> and <strong>Delivery</strong> services.</p>
</li>
<li><p>The <strong>Order Service</strong> makes a request to the <strong>Accounting Service</strong> to process the payment from the user. As soon as the payment is successfully processed the service stores the billing information regarding the order in its database and publishes the event <strong>OrderPaid</strong>.</p>
</li>
<li><p>The <strong>Warehouse Service</strong> receives the <strong>OrderPaid</strong> event. It tries to book inventory, but there are no inventory left and instead of publishing the <strong>InventoryBooked</strong> event it publishes the <strong>InventoryBookingFailed</strong> event.</p>
</li>
<li><p>All services receive the <strong>InventoryBookingFailed</strong> event and apply compensating actions:</p>
<ul>
<li><p><strong>Order</strong>: Cancels the order.</p>
</li>
<li><p><strong>Accounting</strong>: Refunds money to the customer.</p>
</li>
<li><p><strong>Delivery</strong>: Cancels the delivery.</p>
</li>
</ul>
</li>
</ol>
<h3><strong>Pros</strong>:</h3>
<ul>
<li><p><strong>Loose coupling</strong>: Services only need to know about the events they produce/consumed.</p>
</li>
<li><p><strong>Resilience</strong>: No single point of failure.</p>
</li>
<li><p><strong>Scalability</strong>: A decentralized nature avoids bottlenecks.</p>
</li>
</ul>
<h3><strong>Cons</strong>:</h3>
<ul>
<li><p><strong>Complex debugging</strong>: Distributed logic makes it hard to trace issues.</p>
</li>
<li><p><strong>Eventual consistency</strong>: Services may temporarily disagree on the system state.</p>
</li>
</ul>
<h3><strong>When to use</strong>:</h3>
<ul>
<li><p>Simple workflows with a few services.</p>
</li>
<li><p>Systems where scalability and loose coupling are priorities.</p>
</li>
</ul>
<h3>Implementation</h3>
<p>In this implementation, events are the backbone of the saga. Let's define them:</p>
<pre><code class="language-csharp">public record OrderCreatedEvent(
    Guid OrderId,
    Guid CustomerId,
    List&lt;OrderItem&gt; Items,
    DateTime CreatedAt);

public record OrderPaidEvent(
    Guid OrderId,
    decimal Amount,
    DateTime PaidAt);

public record InventoryBookedEvent(
    Guid OrderId,
    List&lt;InventoryItem&gt; BookedItems);

public record InventoryBookingFailedEvent(
    Guid OrderId,
    string Reason);
</code></pre>
<p>The following events are used:</p>
<ul>
<li><p><code>OrderCreated</code> begins the flow when the order is created by the <code>OrderService</code>. This event is used as an indicator for other services that a new order has been created and they should wait further instructions.</p>
</li>
<li><p><code>OrderPaid</code> is published be the <code>AccountingService</code> when the order has been successfully paid for by the customer.</p>
</li>
<li><p><code>InventoryBooked</code> is an indicator that the warehouse has the necessary products and has successfully booked them for the order.</p>
</li>
<li><p><code>InventoryBookingFailed</code> indicates that something has happened during the inventory booking process at the warehouse and the flow should be reverted. This event starts the compensating actions.</p>
</li>
</ul>
<p>The code-snippet for <code>OrderService</code> is below:</p>
<pre><code class="language-csharp">public class OrderService
{
    private readonly IOrderRepository _orderRepository;
    private readonly IEventBus _eventBus;

    public async Task&lt;Guid&gt; CreateOrder(CreateOrderRequest request)
    {
        var order = new Order
        {
            Id = Guid.NewGuid(),
            CustomerId = request.CustomerId,
            Items = request.Items,
            Status = OrderStatus.Created,
            CreatedAt = DateTime.UtcNow
        };

        await _orderRepository.Save(order);
        await _eventBus.Publish(new OrderCreatedEvent(
            order.Id,
            order.CustomerId,
            order.Items,
            order.CreatedAt));

        return order.Id;
    }
}
</code></pre>
<p><code>CreateOrder</code> is the first step of the saga so it does not publish any failure events. In this step other services know nothing about the order.</p>
<p>The <code>WarehouseService</code> handles the <code>OrderPaid</code> event and tries to book the inventory for the order:</p>
<pre><code class="language-csharp">public class WarehouseService
{
    private readonly IInventoryRepository _inventoryRepository;
    private readonly IEventBus _eventBus;

    public async Task Handle(OrderPaidEvent @event)
    {
        // Check if inventory is available
        var isAvailable = await _inventoryRepository.CheckAvailability(@event.Items);
        if (!isAvailable)
        {
            await _eventBus.Publish(new InventoryBookingFailedEvent(
                @event.OrderId,
                "Insufficient stock"));
            return;
        }

        // Book inventory
        await _inventoryRepository.BookItems(@event.OrderId, @event.Items);
        await _eventBus.Publish(new InventoryBookedEvent(
            @event.OrderId,
            @event.Items));
    }
}
</code></pre>
<p>When the product items are not available in the stock we publish the <code>InventoryBookingFailed</code> event, otherwise we book the items and publish <code>InventoryBooked</code>.</p>
<p>The <code>OrderService</code> should react to the <code>InventoryBookingFailed</code> event and cancel the order. To do this, it changes the status of the order from <strong>Created</strong> to <strong>Cancelled</strong>.</p>
<pre><code class="language-csharp">public async Task Handle(InventoryBookingFailedEvent @event)
{
    await _orderRepository.CancelOrder(@event.OrderId);
}
</code></pre>
<p>The <code>Cancelled</code> status makes the order is invalid. In this implementation it is important to define which status transitions are available. For example, <strong>Created → Cancelled</strong> is allowed, but <strong>Cancelled → Created</strong> is not allowed.</p>
<h2>Orchestration saga</h2>
<p>An Orchestration saga is suitable when you need a central orchestrator for your flow due to its complexity. In this case it is responsible for triggering the compensating transactions and retries.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/80f300c6-7a2d-4324-a46e-a1a09144aeb2.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi9kZjA4ZGUzNi1hZTkwLTRlYjEtYWU0NS1mN2NhODA0ZWI2ODIvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4ODUwNTIwMCwiZXhwIjoxNzg5MTEwMDAwfQ._Fcs6010G_QcLgVHDezwqBldGysH5Vw7ZeVyrD2-Fcw" alt="" style="display:block;margin:0 auto" />

<h3>How it works:</h3>
<ol>
<li><p>A user makes a request to create an order.</p>
</li>
<li><p>The <strong>Orchestrator</strong> sends the request to the <strong>Order Service</strong> and receives a successful response.</p>
</li>
<li><p>The <strong>Orchestrator</strong> sends the request for payment to the <strong>Account Service</strong> and receives a successful response.</p>
</li>
<li><p>The <strong>Orchestrator</strong> sends the request to the <strong>Warehouse Service</strong> for booking the inventory and a receives failure response.</p>
</li>
<li><p>The <strong>Orchestrator</strong> sends compensating transactions to the <strong>Account</strong> and <strong>Order</strong> services and if the delivery was created than to the <strong>Delivery</strong> service as well.</p>
</li>
</ol>
<h3>Pros:</h3>
<ul>
<li><strong>Ease of debugging</strong>. The flow is centralized in one place.</li>
</ul>
<h3>Cons:</h3>
<ul>
<li><p><strong>Additional coupling:</strong> Services are tightly coupled to the orchestrator which must know the contracts for each service to be able to communicate with them.</p>
</li>
<li><p><strong>Moderate resilience:</strong> The orchestrator is the single point of failure, but this can be mitigated with the following strategies:</p>
<ul>
<li><p><strong>State persistence</strong>. Store the Saga’s state to restore the orchestrator after a crash.</p>
</li>
<li><p><strong>Requests Retry</strong>. If a call to the service fails than a retry mechanism is used.</p>
</li>
<li><p><strong>Additional Orchestrator Instance</strong>. Deploy an additional instance of the orchestrator which can start processing the requests as soon as the main orchestrator fails.</p>
</li>
</ul>
</li>
</ul>
<p>While orchestration-based Saga introduces tight coupling to the orchestrator, scalability challenges, and a single point of failure, these issues are manageable with the right design. The trade-off is often worth it for complex workflows, where the orchestrator’s centralized control simplifies debugging and coordination.</p>
<h3>Implementation</h3>
<p>An Orchestrator can be implemented using various technologies and approaches: event-based, direct call or a mix of both. Let’s look at a direct call Saga orchestrator:</p>
<pre><code class="language-csharp">public class OrderSagaOrchestrator
{
    private readonly ISagaStateRepository _stateRepository;
    private readonly IOrderClient _orderClient;
    private readonly IPaymentClient _paymentClient;
    private readonly IInventoryClient _inventoryClient;
    private readonly IDeliveryClient _deliveryClient;

    public async Task Handle(CreateOrderRequest request)
    {
        // Step 1: Create order
        var order = await _orderClient.CreateOrder(request);
    
        var sagaState = new OrderSagaState { OrderId = order.OrderId, OrderCreated = true };
        await _stateRepository.Save(sagaState);

        try
        {
            // Step 2: Process payment
            await _paymentClient.ProcessPayment(order.OrderId, order.Amount);
            sagaState.PaymentProcessed = true;
            await _stateRepository.Update(sagaState);

            // Step 3: Book inventory
            await _inventoryClient.BookInventory(order.OrderId, order.Items);
            sagaState.InventoryBooked = true;
            await _stateRepository.Update(sagaState);
            
            // Step 4: Create delivery
            await _deliveryClient.CreateDelivery(order.OrderId, order.Address);
            sagaState.DeliveryScheduled = true;
            await _stateRepository.Update(sagaState);
        }
        catch (Exception ex)
        {
            sagaState.FailureReason = ex.Message;
            await _stateRepository.Update(sagaState);
            await Compensate(sagaState);
        }
    }

    private async Task Compensate(OrderSagaState sagaState)
    {
        await _orderClient.CancelOrder(sagaState.OrderId);
        
        if (sagaState.PaymentProcessed)
            await _paymentClient.RefundPayment(sagaState.OrderId);

        if (sagaState.InventoryBooked)
            await _inventoryClient.ReleaseInventory(sagaState.OrderId);
            
        if(sagaState.DeliveryScheduled)
            await _deliveryClient.CancelDelivery(sagaState.OrderId);
    }
}

public class OrderSagaState
{
    public Guid OrderId { get; set; }
    public bool OrderCreated { get; set; }
    public bool PaymentProcessed { get; set; }
    public bool InventoryBooked { get; set; }
    public bool DeliveryScheduled { get; set; }
    public string FailureReason { get; set; }
}
</code></pre>
<p>There are a few differences when comparing this with the Choreography saga:</p>
<ul>
<li><p><code>OrderSagaState</code> contains the state of the saga, so it is possible to track the saga state using a database.</p>
</li>
<li><p>The flow is in one place. If something has happened it is possible to check which state is next and which steps were processed.</p>
</li>
</ul>
<h2><strong>Comparison Table: Choreography vs. Orchestration</strong></h2>
<table>
<thead>
<tr>
<th><strong>Aspect</strong></th>
<th><strong>Choreography</strong></th>
<th><strong>Orchestration</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Coupling</strong></td>
<td>Loose (services only know about events).</td>
<td>Tight to the orchestrator, but not to each other.</td>
</tr>
<tr>
<td><strong>Scalability</strong></td>
<td>High (no central bottleneck).</td>
<td>Moderate (orchestrator can be a bottleneck, but is scalable with additional effort).</td>
</tr>
<tr>
<td><strong>Resilience</strong></td>
<td>High (no single point of failure).</td>
<td>Moderate (orchestrator is a single point of failure, but can be made resilient).</td>
</tr>
<tr>
<td><strong>Debugging</strong></td>
<td>Hard (distributed logic).</td>
<td>Easier (centralized logic).</td>
</tr>
<tr>
<td><strong>Complexity</strong></td>
<td>High (services must handle compensating logic).</td>
<td>Moderate (orchestrator manages flow).</td>
</tr>
</tbody></table>
<h1>Problems and Considerations</h1>
<h2>Idempotency</h2>
<p>Regardless of the implementation the idempotency is a key element of the saga. If an event is redelivered due to network issue or other reasons the service must handle it without side effects.</p>
<p>Imagine a situation when the <strong>RefundPayment</strong> event arrives multiple times. The <strong>Accounting Service</strong> should process it only once, and all others attempts should be skipped.</p>
<pre><code class="language-csharp">public class AccountingService
{
    private readonly IPaymentService _paymentService;
    private readonly IPaymentRepository _paymentRepository;

    public async Task Handle(RefundPaymentEvent @event)
    {
        // Check if this refund was already processed
        var existingPayment = await _paymentRepository.GetByOrderId(@event.OrderId);
        if (existingPayment == null || existingPayment.State == PaymentState.Refunded)
            return; // Idempotency: Skip if already processed
            
        await _paymentService.RefundOrder(@event.OrderId);
        await _paymentRepository.MarkPaymentRefunded(@event.OrderId);
    }
}
</code></pre>
<h2>Eventual Consistency</h2>
<p>Eventual consistency means the system will eventually reach a consistent state, but not necessarily immediately. The Choreography Saga relies on events thus it cannot guarantee that all of them will be processed immediately due to its asynchronous nature. The orchestration saga has a similar issue and even if it uses direct communication with services via HTTP or gRPC it cannot guarantee that services will react immediately.</p>
<h2>Irreversible Steps</h2>
<p>Some operations cannot be truly reversible (for example, sending a confirmation email or shipping a real product). Such actions are supposed to be implemented as late in the flow as possible. For example, instead of sending the confirmation email to the customer after the initial creation of the order, send it only when the saga is completed.</p>
<h2>Error Handling and Retries</h2>
<p>Services can temporarily fail due to various issues, but this should not break the whole flow. For example, when the Warehouse Service is down, the saga should wait until it is online and then continue. Otherwise, the saga may hang indefinitely, which may introduce cascade failures in other services.</p>
<h3>Solutions</h3>
<ul>
<li><p><strong>Exponential backoff for retries</strong>: Do not retry with a constant interval between attempts. Use increasing delays to avoid overwhelming the system.</p>
</li>
<li><p><strong>Circuit breakers</strong>: Temporarily stop retries if a service is repeatedly failing.</p>
</li>
<li><p><strong>Dead-letter queues</strong>: If an event cannot be processed correctly after a few attempts, it should be moved to the DLQ and the development team should be notified.</p>
</li>
<li><p><strong>Timeouts</strong>: If a request takes too long, it is better to fail it with a timeout. This helps prevent overloading the service further.</p>
</li>
</ul>
<h1>Summary</h1>
<p>The Saga pattern is the de facto standard for managing distributed transactions in microservices, where traditional ACID transactions cannot span multiple services. By breaking workflows into local transactions paired with compensating actions, Sagas ensure your system can recover from failures and maintain eventual consistency - even when services operate independently.</p>
<p>Sagas are not a silver bullet, but they are the most practical solution for coordinating transactions in microservices. Start with Choreography if your workflow is simple and services are loosely coupled. Use Orchestration for complex workflows where centralized control outweighs the added complexity.</p>
<h1>Links</h1>
<p><a href="https://www.pollydocs.org/">Polly: The .NET resilience library</a></p>
<p><a href="https://en.wikipedia.org/wiki/ACID">ACID</a></p>
<p><a href="https://iharmaiseyeu.net/choreography-pattern-in-microservices">Choreography Pattern in Microservices</a></p>
<p><a href="https://iharmaiseyeu.net/orchestration-pattern-in-microservices">Orchestration Pattern in Microservices</a></p>
<p>Image credits: <a href="https://www.instagram.com/jane__ml/"><strong>Jane__ml</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Orchestration Pattern in Microservices]]></title><description><![CDATA[In my previous article about Choreography, I outlined that it does not suit situations with complicated workflows or where strong consistency is required…]]></description><link>https://iharmaiseyeu.net/orchestration-pattern-in-microservices</link><guid isPermaLink="true">https://iharmaiseyeu.net/orchestration-pattern-in-microservices</guid><category><![CDATA[Orchestration]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[message broker]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Mon, 03 Aug 2026 07:16:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/3683d617-7b89-46ab-8920-f0014b890ac0.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>In my previous article about <a href="https://iharmaiseyeu.net/choreography-pattern-in-microservices">Choreography</a>, I outlined that it does not suit situations with complicated workflows or where strong consistency is required. So, it was logical to discuss Orchestration, the pattern that helps solve - if not all - many of the issues of Choreography.</p>
<h1>What Is the Orchestration Pattern?</h1>
<p>If we compare Choreography to dancers following each other, we can imagine Orchestration as an orchestra following a conductor who knows where and when each musician should start their part. The main idea behind this pattern is to have one service that understands the business process and the order in which operations should be called.</p>
<p>When we talk about the business process, we do not mean that the orchestrator should implement the business logic. On the contrary, it should not implement any business logic—only call the services that implement parts of the business logic, check the results, and decide whether the process should continue.</p>
<p>The diagram below outlines a simple orchestration process.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/928764ad-662b-4acd-bfa5-655ecec240c9.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi85ZGM2YTEzNC05N2FjLTQyYzMtOWI1OS03MzIyMDkwZjhhMGUvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4NDgzMDcxMSwiZXhwIjoxNzg1NDM1NTExfQ.eJO3I08U5WkzUthuL-6K7jRLM9F5yl4YedWasoT366c" alt="" style="display:block;margin:0 auto" />

<p>What we see is that a user sends a request to an orchestrator, which knows which requests to send to Service 1, Service 2, and Service 3. When the orchestrator receives the result of an operation, it responds to the user with it.</p>
<p>The order of the requests (or events) depends on the business process, so the orchestrator does not force you to make calls in parallel or sequentially. As such, it does not force you to use HTTP, gRPC, or a message broker. All of these are implementation details that depend entirely on you.</p>
<p>Let's imagine we have the following flow to buy some products:</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/b0371a19-cd21-4b31-8066-828d3d45a35f.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi80NzdmMzVlZi1iMmY3LTQwYjUtOTQ0MS1hMWU4NDM3YzE0NTYvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4NDgzMDcxMSwiZXhwIjoxNzg1NDM1NTExfQ.8OnbeT5httrURF3_ZrAmQRo5l7RrlbjAyAt7vw6xxwA" alt="" style="display:block;margin:0 auto" />

<p>The flow is straightforward:</p>
<ul>
<li><p>Creating the order is the first step. Until we create an order, we cannot book inventory in a warehouse. If the order is not created, we cannot start the process.</p>
</li>
<li><p>The order is created, so we should book inventory for it. If, for some reason, this cannot be done, we cannot proceed to the next step.</p>
</li>
<li><p>The inventory is booked, so we can send a confirmation email to the customer.</p>
</li>
<li><p>In the last step, we create the delivery.</p>
</li>
</ul>
<p>This process is quite linear: we send a request, wait for the result, and trigger the next step. In reality, not all processes are like this. It might be that at some stage, we need to run a few processes in parallel, wait until all of them finish, combine the results, and decide what to do next.</p>
<h1>Direct-Call Orchestrator</h1>
<p>This type of orchestrator makes direct calls to known services. The most common way to implement it is using REST or gRPC. Let's first look at the code snippet below:</p>
<pre><code class="language-csharp">public async Task&lt;OrderResult&gt; ProcessOrderAsync(Order order)
{
    try
    {
        var orderResult = await _orderClient.CreateOrderAsync(order);
        var paymentResult = await _paymentClient.ProcessPaymentAsync(order.Payment);
        var emailResult = await _emailClient.SendOrderEmailAsync(order);
        var inventoryResult = await _inventoryClient.ReserveItemsAsync(order.Items);
        
        return new OrderResult { Success = true };
    }
    catch (Exception ex)
    {
        return new OrderResult { Success = false };
    }
}
</code></pre>
<p>This simple method outlines the main idea of a direct-call orchestrator. Here, we have several clients for different services, and we simply call them one after another.</p>
<p><strong>Pros:</strong></p>
<ul>
<li><p>It is the simplest implementation, which is easy to extend.</p>
</li>
<li><p>You have complete control over the process, making it easy to debug and run.</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Tightly coupled design. The orchestrator can only work when all dependencies are healthy. Imagine a situation where one service is down, and the entire process goes down as well.</p>
</li>
<li><p>There is no built-in retry mechanism, so all clients likely need to be adjusted to use retry or circuit breaker libraries.</p>
</li>
</ul>
<h1>Event-Driven Orchestrator</h1>
<p>This type of orchestrator relies on events rather than direct calls to services. Let's look at a possible implementation of this approach using a background service and Azure Service Bus:</p>
<pre><code class="language-csharp">public class OrderOrchestratorService : BackgroundService
{
    private readonly ServiceBusProcessor _eventProcessor;
    private readonly ServiceBusSender _commandSender;
    private readonly ILogger&lt;OrderOrchestratorService&gt; _logger;
    private readonly ConcurrentDictionary&lt;Guid, TaskCompletionSource&lt;object&gt;&gt; _pendingSteps = new();

    public OrderOrchestratorService(
        ServiceBusClient serviceBusClient,
        ILogger&lt;OrderOrchestratorService&gt; logger)
    {
        _eventProcessor = serviceBusClient.CreateProcessor("orchestrator-events", "orchestrator-sub");
        _commandSender = serviceBusClient.CreateSender("orchestrator-commands");
        _logger = logger;

        _eventProcessor.ProcessMessageAsync += OnEventReceived;
        _eventProcessor.ProcessErrorAsync += OnError;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await _eventProcessor.StartProcessingAsync(stoppingToken);
        _logger.LogInformation("OrderOrchestrator started");

        try
        {
            await Task.Delay(Timeout.Infinite, stoppingToken);
        }
        catch (OperationCanceledException)
        {
        }

        await _eventProcessor.StopProcessingAsync();
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        await _commandSender.DisposeAsync();
        await _eventProcessor.DisposeAsync();
        await base.StopAsync(cancellationToken);
    }
    
    // Remaining code
}
</code></pre>
<p>Events are the fuel of this orchestrator. With the start of the background process, we create an event processor that listens to the <code>orchestrator-events</code> topic. This topic receives all status events about the process. When it receives a message, the event handler <code>OnEventReceived</code> is called.</p>
<p>Additionally, we create an Azure Service Bus sender for the <code>orchestrator-commands</code> topic. Services subscribe to this topic to receive commands to perform their part of the process.</p>
<p>Let's look at how the <code>OnEventReceived</code> method works:</p>
<pre><code class="language-csharp">private async Task OnEventReceived(ProcessMessageEventArgs args)
{
    var message = args.Message;
    var correlationId = Guid.Parse(message.CorrelationId);

    if (message.Subject == "OrderPlaced")
    {
        var orderPlaced = JsonSerializer.Deserialize&lt;OrderPlaced&gt;(message.Body.ToStream())!;

        _ = ProcessOrderAsync(orderPlaced, args.CancellationToken);
    }
    else
    {
        if (_pendingSteps.TryRemove(correlationId, out var tcs))
            tcs.TrySetResult(DeserializeResult(message));
    }

    await args.CompleteMessageAsync(message);
}
</code></pre>
<p>The orchestrator starts with an <code>OrderPlaced</code> event, which calls the <code>ProcessOrderAsync</code> method. All other messages are steps of the orchestration process, registered in <code>_pendingSteps</code>. When the result of a step is received, it is removed from the pending list.</p>
<p>Let's look at the <code>ProcessOrderAsync</code> method:</p>
<pre><code class="language-csharp">private async Task ProcessOrderAsync(OrderPlaced order, CancellationToken ct)
{
    try
    {
        var bookResult = await SendAndWaitAsync&lt;BookInventoryResult&gt;(
            new BookInventoryCommand
            {
                CorrelationId = order.CorrelationId,
                OrderId = order.OrderId,
                Product = order.Product,
                Amount = order.Amount
            },
            "BookInventory",
            order.CorrelationId);

        if (!bookResult.Success)
        {
            return;
        }

        await SendAndWaitAsync&lt;SendEmailResult&gt;(
            new SendEmailCommand
            {
                CorrelationId = order.CorrelationId,
                OrderId = order.OrderId,
                CustomerEmail = order.CustomerEmail
            },
            "SendEmail",
            order.CorrelationId);

        await SendAndWaitAsync&lt;CreateDeliveryResult&gt;(
            new CreateDeliveryCommand
            {
                CorrelationId = order.CorrelationId,
                OrderId = order.OrderId
            },
            "CreateDelivery",
            order.CorrelationId); 
    }
    catch (Exception ex)
    {
        _logger.LogError(ex,
            "[{CorrelationId}] Orchestrator: Order orchestration failed",
            order.CorrelationId);
    }
}
</code></pre>
<p>The main idea of this code is to send an event for a step and wait until we have a result. This is implemented in the <code>SendAndWaitAsync</code> method. The orchestrator stops processing if the inventory cannot be booked. At the same time, we do not check the results for <code>SendEmail</code> and <code>CreateDelivery</code>.</p>
<pre><code class="language-csharp">private async Task&lt;T&gt; SendAndWaitAsync&lt;T&gt;(object command, string commandType, Guid correlationId)
{
    var tcs = new TaskCompletionSource&lt;object&gt;(TaskCreationOptions.RunContinuationsAsynchronously);
    _pendingSteps[correlationId] = tcs;

    var message = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(command))
    {
        Subject = commandType,
        CorrelationId = correlationId.ToString()
    };
    await _commandSender.SendMessageAsync(message);

    var result = await tcs.Task;
    return (T)result;
}
</code></pre>
<p>The <code>SendAndWaitAsync</code> method uses the <code>TaskCompletionSource</code> class to wait for the command to complete. This code looks like common async/await, but in reality, its execution relies on <code>OnEventReceived</code>, which is executed each time a new message is published.</p>
<p>The complete source code can be found on <a href="https://github.com/MasDenBy/blog-samples/tree/main/orchestrator-example">GitHub</a>.</p>
<p><strong>Pros:</strong></p>
<ul>
<li>The design is more decentralized compared to the direct-call orchestrator. It does not rely on specific services—only on messages. It does not matter who or how processes commands, as long as they do their job and respond in the correct format.</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>Difficult to implement, as we need to use a wait mechanism for steps. Additionally, we need to store data for the orchestrator somewhere. In my example, I store it in memory, but memory has its limits. If we need to update the orchestrator's code and restart it, the data in memory will be lost. Thus persistence mechanism is necessary.</li>
</ul>
<h1>Problems and Considerations</h1>
<h2>Single Point of Failure</h2>
<p>The orchestrator becomes a single point of failure for the entire workflow. If it fails, the entire business process can stall. Thus, it requires high availability and fault tolerance.</p>
<h2>Possible Scalability Bottleneck</h2>
<p>For high-load applications that require processing a huge number of events, the orchestrator might become a bottleneck. It is important to consider possible scaling solutions.</p>
<h2>Additional complexity</h2>
<p>The orchestrator introduces additional complexity into the business workflow. It needs to manage events, combine responses, and handle retries for direct calls. Additionally, it requires infrastructure to store state.</p>
<h2>How to Implement</h2>
<p>We have already seen two possible implementations of this pattern and quickly outlined their pros and cons. In reality, the way you implement it mostly aligns with your business needs and the infrastructure you use. In some situations, simple direct calls may be better than a complicated event-driven approach, or you may need to combine both.</p>
<p>Consider whether you are going to implement the infrastructure yourself or use ready-to-use solutions. If you do not have time to fix the infrastructure layer of your orchestrator and just want to focus on business logic, I recommend looking at existing implementations.</p>
<h3>Azure Durable Functions</h3>
<p>Azure Durable Functions is an extension of Azure Functions that enables stateful, long-running workflows in a serverless environment. With it, developers can write orchestration logic to coordinate multiple steps, handle retries, manage state, and recover from failures without managing the infrastructure.</p>
<p>Since Durable Functions is an extension of Azure Functions, you have all the features, such as seamless integration with Azure services and scalability out of the box. If you use Azure and Azure Functions, it might be the first choice.</p>
<h3>MassTransit</h3>
<p><a href="https://masstransit.massient.com/">MassTransit</a> is a distributed application framework for building message-based systems that are reliable under load, testable during development, and observable in production. It supports different persistence mechanisms, from SQL databases to cloud storage like Amazon S3 or Azure Storage.</p>
<p>The documentation is full of examples on how to configure state, monitoring, or create a job. It might not be the easiest library to use, but the number of examples and the framework's popularity can help. MassTransit does not have a ready-to-use implementation of an orchestrator, but with its help, it can be created as a separate service or a saga. Thus, you can use it with any cloud provider or on-premise.</p>
<h3><strong>Elsa Workflows</strong></h3>
<p><a href="https://docs.elsaworkflows.io/">Elsa Workflows</a> another interesting, lightweight open-source project which allows running workflows in .NET. It supports both code-first and designer-first approaches, allowing workflows to be defined in C# or using a visual designer (Elsa Studio).</p>
<p>Elsa Workflows is an orchestrator by design. So, you do not need to think about how to define orchestrator logic - you just define orchestrator steps. It supports many persistence providers, event-driven flows, retries, and event handling out of the box. It might be a good choice if you are looking for a ready-to-use orchestrator.</p>
<h1>When to Use</h1>
<h2>Complex or Long Workflows</h2>
<p>The orchestrator is ideal when you have complex workflows or long-running processes that might take hours or days. Think about processes where you need to execute steps in a specific order or with additional conditional logic.</p>
<h2>Strong Consistency</h2>
<p>You need to enforce strong consistency for business rules, such as:</p>
<ul>
<li><p>"The payment must succeed before shipping."</p>
</li>
<li><p>"The user should be created before assigning a subscription."</p>
</li>
</ul>
<p>Using an orchestrator helps mitigate issues when some processes do not finish while others have already started.</p>
<h1>When Not to Use</h1>
<h2>Simple, Short-Lived Workflows</h2>
<p>If your workflow is trivial and consists of only a few steps, you likely do not need an orchestrator. Consider using <a href="https://iharmaiseyeu.net/choreography-pattern-in-microservices">Choreography</a> instead.</p>
<h2>Non-Critical Processes</h2>
<p>If the workflow can tolerate failures without requiring compensation or retries, you do not need an orchestrator. Additionally, retries can sometimes be achieved without an orchestrator by using message brokers.</p>
<h2>Performance-Critical Workflows</h2>
<p>The orchestrator adds latency overhead due to orchestration and persistence logic. For performance-critical applications, this might outweigh the benefits of orchestration. In such cases, consider other approaches like <a href="https://iharmaiseyeu.net/choreography-pattern-in-microservices">Choreography</a> or direct calls.</p>
<h1>Summary</h1>
<p>The Orchestration pattern is a useful tool when your workflows need ordering and guidance. However, it adds additional latency and state persistence overhead. It is always good to examine your process from different angles and understand whether you need strong consistency and if you are comfortable with the single point of failure that comes with implementing this pattern.</p>
<h1>Links</h1>
<p><a href="https://learn.microsoft.com/en-us/azure/durable-task/common/durable-task-orchestrations"><strong>Durable Orchestrations Overview - Azure | Microsoft Learn</strong></a></p>
<p><a href="https://github.com/MassTransit/MassTransit">MassTransit</a></p>
<p><a href="https://docs.elsaworkflows.io/">Elsa Workflows</a></p>
<p><a href="https://github.com/MasDenBy/blog-samples/tree/main/orchestrator-example">The Source Code on GitHub</a></p>
<p>Cover image by <a href="https://pixabay.com/users/scratsmacker-16310259/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5468470">Uwe Conrad</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5468470">Pixabay</a></p>
]]></content:encoded></item><item><title><![CDATA[Choreography Pattern in Microservices]]></title><description><![CDATA[There are patterns that you use without realizing you are actually using a pattern—patterns with defined pros, cons, and recommendations for when to use…]]></description><link>https://iharmaiseyeu.net/choreography-pattern-in-microservices</link><guid isPermaLink="true">https://iharmaiseyeu.net/choreography-pattern-in-microservices</guid><category><![CDATA[C#]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[patterns]]></category><category><![CDATA[Choreography]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Mon, 13 Jul 2026 07:32:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/b56f5030-460b-4372-bb0b-2a28c36522de.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>There are patterns that you use without realizing you are actually using a pattern—patterns with defined pros, cons, and recommendations for when to use them. Choreography is one such pattern for me. For many years, I used it simply as part of my day-to-day development activities, never realizing it was a pattern. So, let's dig deeper into choreography.</p>
<h1>What Is the Choreography Pattern?</h1>
<p>A common analogy for this pattern is dancers: all of them move in the correct rhythm, following each other's movements. This seems to be the main idea behind the name. Let's translate this simple analogy into the world of microservices. If we replace dancers with services, we get the following: all services must do their work independently, following each other without a central coordinator.</p>
<p>Let's look at this with a small example. Suppose we have a web shop where customers buy goods. When someone places an order, we should:</p>
<ul>
<li><p>Create an order</p>
</li>
<li><p>Send a notification to the buyer that the order was successfully created</p>
</li>
<li><p>Book inventory in the warehouse</p>
</li>
<li><p>Create a delivery</p>
</li>
<li><p>And so on</p>
</li>
</ul>
<p>This part of the flow is enough to represent the idea behind the choreography pattern.</p>
<p>At first, let's imagine how we can design this system using a monolithic approach.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/788893f5-ca27-4420-bf4a-b2449b161acd.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi9mMzU2YmQxNy03MzkzLTQ2YmEtYmRkYy1mNGMzMTgwZDI0Y2IvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4MzA4NjEwMSwiZXhwIjoxNzgzNjkwOTAxfQ.qUJtrel_SS7hhrw0T_y8o6XZCwj72aA0koCb6444p6M" alt="" style="display:block;margin:0 auto" />

<p>The diagram above is straightforward. The user makes a request to create an order, and a set of services are called one after another:</p>
<ul>
<li><p><code>OrderService</code> creates the order.</p>
</li>
<li><p><code>InventoryService</code> books the inventory in the warehouse.</p>
</li>
<li><p><code>EmailService</code> sends the buyer an email confirming the order was created.</p>
</li>
<li><p><code>DeliveryService</code> creates the delivery so the delivery flow can start.</p>
</li>
</ul>
<p>The crucial part of this diagram is the order in which we call each service. We cannot book inventory in the warehouse or send an email notification before the order is created, so we wait until <strong>the order is created</strong>. The delivery cannot be created if we do not have the right quantity of products in the warehouse, so we need to know that <strong>the inventory was booked</strong>. <code>OrderController</code> acts as an orchestrator for this flow, knowing when and which services should be called. If an exception occurs for some reason, the next service won't be called. This implementation is synchronous and tightly coupled—we know about every step and follow them.</p>
<p>Let's translate this design to a microservices architecture. It is clear that almost every service from the diagram can be represented as a separate microservice, and <code>OrderController</code> will be merged into <code>OrderService</code>. The design of the system might look like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/e20a3eaa-91d6-40cf-be7f-45116bccd87c.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi82NzZiZjY4MC1jM2M0LTQ2NmUtYWEwZi05Nzk0ODJjMmYzYzcvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4MzA4NjEwMSwiZXhwIjoxNzgzNjkwOTAxfQ.3PiqkY9xGgCgpZZxKuYr64d9pJUa9gceZcfy0wutC6E" alt="" style="display:block;margin:0 auto" />

<p>What catches the eye at first glance is the dependencies. The <code>OrderService</code> not only knows about other services but also completely depends on them. So, we have a tightly coupled, fragile design. What we need to do is remove direct communication between our microservices, and events can help with this.</p>
<p>I have already hinted at some possible events when we considered the monolithic implementation of the workflow. Let's define the full list:</p>
<ul>
<li><p><code>OrderCreated</code> is published when the order is created.</p>
</li>
<li><p><code>InventoryBooked</code> is published when the inventory is booked in the warehouse.</p>
</li>
<li><p><code>DeliveryCreated</code> is published when the delivery is created for the order.</p>
</li>
</ul>
<p>Now we can redesign our system using event-driven microservices.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/c42b52cb-d251-4759-bf48-79fcdea35944.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi83ZjdjOTk3MS0yYzdkLTQ4ZmMtYTVkMi00ZDVhYjczOTI1NjQvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4MzA4NjEwMSwiZXhwIjoxNzgzNjkwOTAxfQ.VgMHysXV_8uceMUv5O8GXLSwlmCDy8V3WWLHkyCrhOk" alt="" style="display:block;margin:0 auto" />

<p>There is no direct connection between services in the new diagram. The message broker (I use Azure Service Bus) receives and delivers all messages. Let's cover how the entire flow works now:</p>
<ul>
<li><p>The user makes a request to create an order through <code>OrderService</code>.</p>
</li>
<li><p><code>OrderService</code> publishes the <code>OrderCreated</code> event. At this step, the service has completed its part of the flow and simply waits for new requests.</p>
</li>
<li><p>The <code>Service Bus</code> delivers the <code>OrderCreated</code> event to <code>InventoryService</code> and <code>EmailService</code>. Both services can start processing this event simultaneously because their work results do not depend on each other.</p>
</li>
<li><p>When <code>InventoryService</code> finishes booking the inventory for the order, it publishes the <code>InventoryBooked</code> event.</p>
</li>
<li><p>The <code>Service Bus</code> delivers the <code>InventoryBooked</code> event to <code>DeliveryService</code>.</p>
</li>
<li><p>When <code>DeliveryService</code> finishes, it publishes the <code>DeliveryCreated</code> event.</p>
</li>
<li><p>And so on.</p>
</li>
</ul>
<p>We can continue adding many different services to this flow, but I assume the main idea is clear. Our services are independent participants that perform their own tasks in the overall operation. This is an example of the Choreography pattern.</p>
<h1>Problems and Considerations</h1>
<h2>Simplicity of Extension</h2>
<p>The Choreography pattern looks very simple and useful: one service publishes events, and other services subscribe to and process these events. For example, in the design above, we can simply add a few services and a few additional events:</p>
<ul>
<li><p><code>EmailService</code> can subscribe to <code>DeliveryCreated</code> event and send an email with delivery information.</p>
</li>
<li><p>An additional <code>InvoiceService</code> can subscribe to the <code>OrderCreated</code> event to generate an invoice.</p>
</li>
<li><p>And so on.</p>
</li>
</ul>
<p>Choreography shines when we have a small number of services and everything works as expected. However, as the workflow grows, we can experience painful issues with finding and fixing defects.</p>
<h2>Event Ordering</h2>
<p>Choreography does not define an explicit order of events. We can manage this only by introducing new events and changing the flow to work with them. This requires many changes and coordination between teams if new events must be processed by services outside your area of responsibility. Just imagine that you need to book inventory only when the order has already been paid.</p>
<p>We already have the <code>OrderCreated</code> event, so we add a new subscription for the <code>PaymentService</code> to process the payment. Otherwise, <code>InventoryService</code> will not account for this new rule. To do this, we need to introduce a new <code>OrderPaid</code> event and change the implementation of inventory booking.</p>
<p>What if many services need to wait until the order is paid? This pattern does not guarantee the order of events. It is still possible to create pseudo-ordering, but if you need to do this, perhaps you need another pattern, such as Orchestration or Saga.</p>
<h2>Eventual Consistency</h2>
<p>Choreography leads to eventual consistency by design. We do not know how quickly the same order will be processed by different systems. For example, a user might receive an email that a delivery was created before the delivery tracking system has processed that information. So, when the user opens the link, they receive an HTTP 404 instead of delivery information.</p>
<h2>Debugging Difficulty</h2>
<p>Let's imagine that a delivery was not created for an order. We need to check if there are issues with the <code>DeliveryService</code>. If it looks fine, we need to check if the order was initially created and whether the inventory was booked. This does not seem so bad, right?</p>
<p>What about a slightly changed flow of events:</p>
<p><code>OrderCreated → OrderPaid → InvoiceGenerated → InventoryBooked → InventoryPacked → DeliveryCreated</code></p>
<p>A support ticket stating that a delivery was not created would take much more time to investigate. We need to check that all five additional events were processed properly.</p>
<p>This is why it is crucial for such systems to have good log analytics software. The necessary logs should be collected and stored. Each event should have a special identifier for the flow, usually called a <code>CorrelationId</code>, which is generated with the first event. Without this identifier, it is nearly impossible to follow all events in a distributed system.</p>
<h2>Processing Dead Letters</h2>
<p>Another important consideration is the notification system. When an event cannot be processed properly by a service, it is moved to a Dead-Letter Queue (<strong>DLQ</strong>) by the message broker. With a proper notification mechanism, this might be the first indicator that the system is experiencing issues. This allows the development team to quickly recover the system and reprocess all events from the <strong>DLQ</strong>.</p>
<h2>Use Outbox for Reliable Event Publishing</h2>
<p>The core of Choreography is event handling. Microservices publish and listen to events. Therefore, we need to ensure that events are published reliably. For this, the Outbox pattern can be used. I have already published an article, "<a href="https://iharmaiseyeu.net/outbox-pattern-in-microservices-reliable-event-publishing-in-csharp"><strong>Outbox Pattern in Microservices: Reliable Event Publishing in C#</strong></a>," about it.</p>
<h2>Event Schema and Versioning</h2>
<p>As the system evolves, event schemas change. It is important to ensure that you support different versions.</p>
<p>It is also important to have a schema registry where members of each team can look up events and their supported versions. You cannot simply deprecate an event version without notifying all teams in advance, because as long as at least one consumer uses it, you must support that version.</p>
<h2>Idempotency</h2>
<p>The same event can be sent multiple times due to network issues or retries, and consumers should be ready for this. There are different options for handling duplicate events, but the main idea is simple: the consumer should either apply the same changes multiple times or skip processing the duplicated event.</p>
<h2>Performance</h2>
<p>Choreography can lead to a high volume of messages. In high-load systems, the message broker might become a bottleneck and increase the cost of the system.</p>
<h2>Testing</h2>
<p>Testing such a system, where many events arrive at many services and might be processed almost simultaneously, is really challenging. You need to:</p>
<ul>
<li><p>Create many different events.</p>
</li>
<li><p>Simulate event failures to check how the system behaves.</p>
</li>
<li><p>Verify that if an event is processed out of order, the system does not enter an incorrect state.</p>
</li>
<li><p>Check the handling of events in the DLQ.</p>
</li>
<li><p>And so on.</p>
</li>
</ul>
<h1>When to Use</h1>
<p>Given the problems we have already outlined, the Choreography pattern is a useful tool in the right hands. Let's look at the cases where it is best to use it.</p>
<h2>Small Number of Events</h2>
<p>As we have already seen, a system with a few events can easily use this pattern. With proper log analytics and retry mechanisms, even big issues should not be a huge problem.</p>
<h2>Consumers from Other Sub-Domains</h2>
<p>It is a common situation when an event needs to be consumed outside your sub-domain. In such cases, the system that needs to process the event is likely developed and maintained by another team.</p>
<p>Look at our list of services, and you can see the possible sub-domains or teams responsible for each service:</p>
<ul>
<li><p>Ordering: <code>OrderService</code></p>
</li>
<li><p>Warehouse: <code>InventoryService</code></p>
</li>
<li><p>Platform: <code>EmailService</code></p>
</li>
<li><p>Delivery: <code>DeliveryService</code></p>
</li>
</ul>
<h1>When Not to Use</h1>
<p>I initially wanted to say, "Do not use in all other situations," but I decided it is better to highlight some specific cases where Choreography seems like the right choice but is not.</p>
<h2>Complex Workflows</h2>
<p>With many steps in your workflow, choreography is really hard to manage. Just imagine a situation where, after a payment failure, you need to issue a refund, or a product is no longer available in the warehouse and you need to cancel all orders, issue refunds, and send emails to buyers with explanations. This might be a good case for Orchestration, not Choreography.</p>
<h2>Strong Consistency Requirements</h2>
<p>I have already noted that Choreography is all about eventual consistency. We send events, and we do not know when they will be processed by consumers. If the system you are working on requires strong consistency, do not use Choreography.</p>
<p>Imagine a situation where User1 sends money to User2. At some point, we might have a situation where User2 has already received the money, but it has not yet been withdrawn from User1. So, User1 can still spend it even after transferring it to another user.</p>
<h1>Implementation</h1>
<p>I will use Azure Functions and Azure Service Bus for the examples. As a base for the implementation, I will use the same flow we have already discussed. After some changes, it should look like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/97a3f06b-ae6f-4c8b-ae38-674a920bf878.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi9kZTZiMDFhMS0yZjExLTRiMjktYTFiNS02MjFkMzBjOTQyNmIvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4MzA4NjEwMSwiZXhwIjoxNzgzNjkwOTAxfQ.YOLQYq3E-T-rXiWOUjcjxNjtpHYvt5yoJJ4UBcvCHBE" alt="" style="display:block;margin:0 auto" />

<blockquote>
<p>The code snippets below do not represent production-quality code. Some fake services are used just to outline the main idea behind the Choreography pattern.</p>
</blockquote>
<p>Let's start with the <code>CreateOrder</code> function. Its source code is in the snippet below:</p>
<pre><code class="language-csharp">public class CreateOrder(
    ServiceBusClient serviceBusClient,
    FakeOrderStore orderStore,
    ILogger&lt;CreateOrder&gt; logger)
{
    private static readonly string[] Products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"];
    private static readonly string[] Emails = ["alice@example.com", "bob@example.com", "carol@example.com"];

    [Function(nameof(CreateOrder))]
    public async Task&lt;HttpResponseData&gt; Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req)
    {
        var correlationId = Guid.NewGuid();
        var orderId = Guid.NewGuid();
        var product = Products[Random.Shared.Next(Products.Length)];
        var email = Emails[Random.Shared.Next(Emails.Length)];
        var amount = Random.Shared.Next(1, 4);

        var orderEvent = new OrderCreated
        {
            CorrelationId = correlationId,
            OrderId = orderId,
            CustomerEmail = email,
            Product = product,
            Amount = amount
        };

        orderStore.Add(orderEvent);

        var sender = serviceBusClient.CreateSender("order-events");
        var message = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(orderEvent))
        {
            Subject = "OrderCreated"
        };
        message.ApplicationProperties.Add("CorrelationId", correlationId.ToString());
        await sender.SendMessageAsync(message);

        logger.LogInformation(
                "[{CorrelationId}] OrderCreated event published: OrderId={OrderId}",
                orderEvent.CorrelationId,
                orderEvent.OrderId);

        var response = req.CreateResponse(System.Net.HttpStatusCode.OK);
        await response.WriteAsJsonAsync(orderEvent);
        return response;
    }
}
</code></pre>
<p>The code is straightforward and includes a mock implementation for creating a fake order. The most interesting part is in lines, where we create a sender <code>serviceBusClient.CreateSender</code> for the topic named <code>order-events</code>, create a <code>ServiceBusMessage</code>, and set the <code>CorrelationId</code>. After sending the event, the entire flow starts.</p>
<p>The <code>BookInventory</code> function works at the warehouse level and books the necessary inventory for the order. If there are not enough products in stock, the function does not send the <code>OrderInventoryBooked</code> event.</p>
<pre><code class="language-csharp">public class BookInventory(
    ServiceBusClient serviceBusClient,
    FakeInventoryStore inventoryStore,
    ILogger&lt;BookInventory&gt; logger)
{
    [Function(nameof(BookInventory))]
    public async Task Run(
        [ServiceBusTrigger("order-events", "order-created-inventory-sub", Connection = "ServiceBusConnection")]
        ServiceBusReceivedMessage message)
    {
        var orderEvent = JsonSerializer.Deserialize&lt;OrderCreated&gt;(message.Body.ToStream())!;

        if (inventoryStore.TryBook(orderEvent.Product, orderEvent.Amount))
        {
            logger.LogInformation(
                "[{CorrelationId}] BookInventory: Inventory booked for order {OrderId} (product: {Product}, qty: {Amount})",
                orderEvent.CorrelationId,
                orderEvent.OrderId,
                orderEvent.Product,
                orderEvent.Amount);

            var bookedEvent = new OrderInventoryBooked
            {
                CorrelationId = orderEvent.CorrelationId,
                OrderId = orderEvent.OrderId,
                CustomerEmail = orderEvent.CustomerEmail,
                Product = orderEvent.Product,
                Amount = orderEvent.Amount
            };

            var sender = serviceBusClient.CreateSender("order-events");
            var bookedMessage = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(bookedEvent))
            {
                Subject = "OrderInventoryBooked"
            };
            bookedMessage.ApplicationProperties.Add("CorrelationId", orderEvent.CorrelationId.ToString());
            await sender.SendMessageAsync(bookedMessage);

            logger.LogInformation(
                "[{CorrelationId}] OrderInventoryBooked published: OrderId={OrderId}",
                orderEvent.CorrelationId,
                orderEvent.OrderId);
        }
        else
        {
            logger.LogWarning(
                "[{CorrelationId}] BookInventory: Failed to book inventory for order {OrderId} (product: {Product}, qty: {Amount}) - insufficient stock",
                orderEvent.CorrelationId,
                orderEvent.OrderId,
                orderEvent.Product,
                orderEvent.Amount);
        }
    }
}
</code></pre>
<p>The function has a <code>ServiceBusTrigger</code> with a subscription for the <code>order-events</code> topic. The topic receives many different order events, not only those related to creation. Therefore, the subscription uses the expression <code>sys.Label = 'OrderCreated'</code> to filter out only the necessary ones.</p>
<p>You can see that we first try to book the inventory <code>inventoryStore.TryBook</code>, and if we succeed, a new <code>OrderInventoryBooked</code> event is published to the same <code>order-events</code> topic.</p>
<p>In parallel with <code>BookInventory</code>, the <code>SendEmail</code> function notifies the buyer with an order confirmation.</p>
<pre><code class="language-csharp">public class SendEmail(ILogger&lt;SendEmail&gt; logger)
{
    [Function(nameof(SendEmail))]
    public void Run(
        [ServiceBusTrigger("order-events", "order-created-email-sub", Connection = "ServiceBusConnection")]
        ServiceBusReceivedMessage message)
    {
        var orderEvent = JsonSerializer.Deserialize&lt;OrderCreated&gt;(message.Body.ToStream())!;

        logger.LogInformation(
            "[{CorrelationId}] SendEmail: Email sent to {Email} for order {OrderId}",
            orderEvent.CorrelationId,
            orderEvent.CustomerEmail,
            orderEvent.OrderId);
    }
}
</code></pre>
<p>The last function in our workflow is <code>CreateDelivery</code>.</p>
<pre><code class="language-csharp">public class CreateDelivery(
    ServiceBusClient serviceBusClient,
    FakeDeliveryStore deliveryStore,
    ILogger&lt;CreateDelivery&gt; logger)
{
    [Function(nameof(CreateDelivery))]
    public async Task Run(
        [ServiceBusTrigger("order-events", "inventory-booked-delivery-sub", Connection = "ServiceBusConnection")]
        ServiceBusReceivedMessage message)
    {
        var bookedEvent = JsonSerializer.Deserialize&lt;OrderInventoryBooked&gt;(message.Body.ToStream())!;

        var deliveryId = Guid.NewGuid();
        var deliveryEvent = new DeliveryCreated
        {
            CorrelationId = bookedEvent.CorrelationId,
            OrderId = bookedEvent.OrderId,
            DeliveryId = deliveryId
        };

        deliveryStore.Add(deliveryEvent);

        var sender = serviceBusClient.CreateSender("delivery-events");
        var deliveryMessage = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(deliveryEvent))
        {
            Subject = "DeliveryCreated"
        };
        deliveryMessage.ApplicationProperties.Add("CorrelationId", bookedEvent.CorrelationId.ToString());
        await sender.SendMessageAsync(deliveryMessage);

        logger.LogInformation(
            "[{CorrelationId}] CreateDelivery: Delivery created for order {OrderId}, DeliveryId={DeliveryId}",
            bookedEvent.CorrelationId,
            bookedEvent.OrderId,
            deliveryId);

        logger.LogInformation(
            "[{CorrelationId}] DeliveryCreated published to delivery-events: OrderId={OrderId}",
            bookedEvent.CorrelationId,
            bookedEvent.OrderId);
    }
}
</code></pre>
<p>Here we see the same behavior as in the previous functions: first, we process the event, and in response, we publish another event indicating a successful result.</p>
<p>The full source code can be found on <a href="https://github.com/MasDenBy/blog-samples/tree/main/choreography-example">GitHub</a>.</p>
<h1>Summary</h1>
<p>The Choreography pattern is usually the first step into event-driven architecture. What could be simpler than publishing an event, executing code upon receipt, and publishing another event as a response? Simplicity and flexibility are key, but with these come many considerations and problems that need to be addressed, such as DLQ maintenance, notifications, eventual consistency, debugging, and testing.</p>
<h1>Links</h1>
<p><a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/choreography"><strong>Choreography Pattern - Azure Architecture Center</strong></a></p>
<p><a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-trigger">Azure Service Bus trigger for Azure Functions</a></p>
<p>Cover Image by <a href="https://pixabay.com/users/romanen-2521638/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1376250">Evgen Rom</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1376250">Pixabay</a></p>
]]></content:encoded></item><item><title><![CDATA[Outbox Pattern in Microservices: Reliable Event Publishing in C#]]></title><description><![CDATA[In a microservices architecture, we often publish events. Thousands or even hundreds of thousands of events are published to notify other services about…]]></description><link>https://iharmaiseyeu.net/outbox-pattern-in-microservices-reliable-event-publishing-in-csharp</link><guid isPermaLink="true">https://iharmaiseyeu.net/outbox-pattern-in-microservices-reliable-event-publishing-in-csharp</guid><category><![CDATA[outbox pattern]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[Databases]]></category><category><![CDATA[MSSQL]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[Azure]]></category><category><![CDATA[CosmosDB]]></category><category><![CDATA[serverless]]></category><category><![CDATA[events]]></category><category><![CDATA[message broker]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Wed, 24 Jun 2026 05:34:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/4ebeb20e-a037-4eea-876d-55bf98232616.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>In a microservices architecture, we often publish events. Thousands or even hundreds of thousands of events are published to notify other services about changes: a user created a profile, an order was paid, a courier took an order for delivery, and so on. All of these are examples of events: <code>UserProfileCreated</code>, <code>OrderPaid</code>, <code>OrderInDelivery</code>. Events are important, and we need to ensure they are published no matter what.</p>
<p>This is exactly what the <strong>Outbox</strong> pattern does. It ensures that events are reliably published from a microservice, even if the service itself or the message broker crashes, or something else goes wrong.</p>
<h1>Outbox pattern</h1>
<p>The main idea of the <strong>Outbox</strong> pattern is to create an additional table and populate it in the same transaction as the business data manipulation. This table is usually called <strong>Outbox</strong>, but this is not a requirement—you can name it whatever suits your project. After new data is added to the table, a separate process (e.g., a background worker) processes it and publishes the events to the broker.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/4a984753-2610-4b9f-b606-e544530e3d3f.svg" alt="" style="display:block;margin:0 auto" />

<p>The diagram above outlines the process, which we can split into 3 steps:</p>
<ol>
<li><p>The <strong>UserService</strong> creates a transaction in the database, where it creates a new user by populating the <strong>UserTable</strong> and inserting new data into the <strong>OutboxTable</strong>.</p>
</li>
<li><p>The background process detects that there is a new event in the <strong>OutboxTable</strong>.</p>
</li>
<li><p>The background process publishes the event to the message broker.</p>
</li>
</ol>
<p>I will show different ways to implement this pattern, but the part of the application we are working with will remain the same. Let's imagine we have a service that creates users, and we must deliver the event that a user was created.</p>
<h1>Relational database</h1>
<p>Let's have a look how we can implement this approach using the relation database.</p>
<p>The <strong>OutboxTable</strong> might look like the following:</p>
<pre><code class="language-sql">CREATE TABLE Outbox (
    Id BIGINT IDENTITY(1,1) PRIMARY KEY,
    Type NVARCHAR(255) NOT NULL,       -- Event type (e.g., 'UserCreated')
    Payload NVARCHAR(MAX) NOT NULL,    -- JSON-serialized event data
    Published BIT DEFAULT 0,           -- Whether the event has been published
    CreatedAt DATETIME2 DEFAULT GETDATE(),
    PublishedAt DATETIME2 NULL,
    Attempts INT DEFAULT 0             -- Number of publishing attempts
);
</code></pre>
<p>This table implementation allows support for different types of events.</p>
<pre><code class="language-csharp">public class UserService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IOutboxRepository _outboxRepository;
    private readonly IUserRepository _userRepository;

    public UserService(
        IUnitOfWork unitOfWork,
        IOutboxRepository outboxRepository,
        IUserRepository userRepository)
    {
        _unitOfWork = unitOfWork;
        _outboxRepository = outboxRepository;
        _userRepository = userRepository;
    }

    public async Task CreateUserAsync(string name, string email)
    {
        _unitOfWork.BeginTransaction();

        try
        {
            // Create a user
            var user = await _userRepository.AddAsync(name, email);

            var @event = new UserCreatedEvent(user.Id, user.Name, user.Email);

            // Save event to outbox table
            var outboxMessage = new OutboxMessage(
                "UserCreated",
                JsonSerializer.Serialize(@event),
                false, // Not published
                DateTime.UtcNow,
                null,  // No date of publish
                0      // 0 attempts to publish the message
            );
            await _outboxRepository.AddAsync(outboxMessage);

            await _unitOfWork.SaveChangesAsync();

            _unitOfWork.Commit();
        }
        catch
        {
            _unitOfWork.Rollback();
            throw;
        }
    }
}
</code></pre>
<p>This code snippet shows how the <code>UserService</code> with the <strong>Outbox</strong> pattern can be implemented. As you might notice we added the message to the Outbox table right after saving the user data.</p>
<p>The same logic can be implemented directly in SQL:</p>
<pre><code class="language-sql">BEGIN TRANSACTION

INSERT INTO User(..)
INSERT INTO Outbox(..)

COMMIT TRANSACTION
</code></pre>
<p>What seems to me like a small code smell in this implementation is that the business logic is close to the code responsible for events. This is not a major issue, and in many cases, it might be the easiest and most practical approach.</p>
<p>To address this, triggers can be used in databases that support them. This might be slightly harder to implement compared to adding another repository in the code, but it separates business logic from event handling.</p>
<pre><code class="language-sql">CREATE TRIGGER trg_Users_AfterInsert
ON Users
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Outbox (Type, Payload, Published, CreatedAt, PublishedAt, Attempts)
    SELECT
        'UserCreated' AS Type,
        (
            SELECT
                u.Id,
                u.Name,
                u.Email,
                GETDATE() AS EventTimestamp
            FROM inserted u
            FOR JSON PATH
        ) AS Payload,
        0 AS Published, -- Not published yet
        GETDATE() AS CreatedAt,
        NULL AS PublishedAt,
        0 AS Attempts
    FROM inserted;
END;
</code></pre>
<p>The database trigger and <code>INSERT</code> are atomic operations: if one fails, the other is rolled back. This works for most relational databases, but it's best to verify if your database supports it.</p>
<p>So far, we've introduced the event storage mechanism, but what about sending the event to a message broker? Common implementations include a background process or a serverless application like <strong>Azure Function</strong> or <strong>AWS Lambda</strong>.</p>
<p>The most important part here is how to retrieve the event data. You need to consider how often to query events and how large the batch should be. This is one of the weakest points of the <strong>Outbox</strong> pattern. For high-load applications that generate a huge number of events, working with the <strong>Outbox</strong> table might become a bottleneck.</p>
<p>In high-load systems, the <strong>Outbox</strong> table can grow very quickly, which may negatively impact performance. So, it's crucial to decide how long events should be stored in the database. Should it be a month or more? How often do you need to reprocess all events from the previous month?</p>
<pre><code class="language-csharp">public class OutboxWorker : BackgroundService
{
    private readonly IOutboxRepository _outboxRepository;
    private readonly IEventPublisher _eventPublisher;
    private readonly ILogger&lt;OutboxWorker&gt; _logger;
    private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(5);

    public OutboxWorker(
        IOutboxRepository outboxRepository,
        IEventPublisher eventPublisher,
        ILogger&lt;OutboxWorker&gt; logger)
    {
        _outboxRepository = outboxRepository;
        _eventPublisher = eventPublisher;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Outbox Worker started.");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                var messages = await _outboxRepository.GetUnpublishedAsync();
                foreach (var message in messages)
                {
                    try
                    {
                        await _eventPublisher.PublishAsync(message.Type, message.Payload);
                        await _outboxRepository.MarkAsPublishedAsync(message.Id);
                        _logger.LogInformation("Published event {EventType} (ID: {Id})", message.Type, message.Id);
                    }
                    catch (Exception ex)
                    {
                        await _outboxRepository.IncrementAttemptsAsync(message.Id);
                        _logger.LogError(ex, "Failed to publish event {EventType} (ID: {Id}). Attempt {Attempts}", 
                            message.Type, message.Id, message.Attempts + 1);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing outbox messages.");
            }

            await Task.Delay(_pollingInterval, stoppingToken);
        }

        _logger.LogInformation("Outbox Worker stopped.");
    }
}
</code></pre>
<p>The code snippet above shows how to poll events from the <strong>Outbox</strong> table using background tasks in .NET. Let's look at some implementation details:</p>
<ul>
<li><strong>Line 26</strong>: Uses <code>IOutboxRepository</code> to query the list of unpublished events. This can be a simple SQL query or use an ORM.</li>
</ul>
<pre><code class="language-sql">SELECT * FROM OutboxMessages WHERE Published = 0 AND Attempts &lt; 5 ORDER BY CreatedAt
</code></pre>
<p>In this example, I query all unpublished events, but you might want to limit the batch size if there are many. At the same time, if an event fails 5 times, it might be best to stop further attempts. In such cases, it's better to have a notification that an event cannot be published, so the development team can quickly investigate and fix the issue.</p>
<p>We must ensure all events are published in the correct order, so we use <code>ORDER BY CreatedAt</code>. This is important because events describe the state of the system over time. The event <code>UserSubscriptionAssigned</code> cannot be fired before <code>UserCreated</code>, because you cannot assign a subscription to a user that hasn't been created yet.</p>
<ul>
<li><p><strong>Line 31</strong>: <code>IEventPublisher</code> is used to publish an event to the broker.</p>
</li>
<li><p><strong>Line 32</strong>: The event is marked as <strong>Published</strong>. After this point, we are no longer interested in this event because it has been published.</p>
</li>
</ul>
<p>What if an exception occurs at this point? The event might have been published, and consumers may have already processed it, but the background process failed to mark the event as published. On the next polling cycle, this event will be published again. Consumers should be prepared for the possibility that the same event may be published multiple times and should be able to process it or skip it.</p>
<h2>Thoughts and Considerations</h2>
<p>The implementation of the <strong>Outbox</strong> pattern might seem trivial, but there are some important considerations to keep in mind. Some of these have already been touched on, but I want to summarize them here.</p>
<h3><strong>Polling Mechanism</strong></h3>
<p>It is important to ensure that the background process is <strong>idempotent</strong> and marks a message as published <strong>only after</strong> it has actually been sent.</p>
<p>Another important consideration is the <strong>batch size</strong> and how often to poll for events. If your system generates 100 events per second but processes only 10 per second, the outbox can become a bottleneck for the entire system because it cannot deliver events in time.</p>
<h3><strong>Error Handling</strong></h3>
<p>How many times should the system retry sending a message? How should it notify the development team about messages that cannot be delivered? If, for some reason, a message cannot be delivered (e.g., the event broker is down, the topic or queue does not exist), the notification should be received as quickly as possible. The earlier the team knows about the issue, the faster they can resolve it and eliminate serious implications.</p>
<h3><strong>Cleaning</strong></h3>
<p>The <strong>Outbox</strong> table must be cleaned; otherwise, it might grow to an unmanageable size. There are many possible approaches to handle this. Let's consider some of them:</p>
<ul>
<li><p><strong>Cleaning Strategy</strong>: First, decide whether to delete rows older than a week or a month. Alternatively, you might want to clean up old records when the number of records in the table hits a threshold (e.g., 10k, 100k). Or, should you delete the event immediately after sending it? These are questions you need to answer before implementing the cleaning mechanism.</p>
</li>
<li><p><strong>Cleaning Execution</strong>: Who or what will clean the table? This could be a database-level cleanup using a database scheduler (if supported by your database). If the database does not support jobs, or if this approach is not suitable for your needs, you can write a cleanup service as a background process or a serverless application.</p>
</li>
</ul>
<h1>NoSQL</h1>
<p>So far, we've discussed relational databases, which natively support transactions. However, there are many cases where relational data isn't used, and we have to use NoSQL databases like <strong>Azure Cosmos DB</strong>, <strong>MongoDB</strong>, or <strong>Amazon DynamoDB</strong>. Can we use the same approach with NoSQL? The answer is: yes and no. Let's look at a few examples.</p>
<h1>Azure Cosmos DB</h1>
<p>Azure Cosmos DB does not have tables in the same way as relational databases like MS SQL or PostgreSQL. Instead, it has containers, and the data in containers is divided by logical partitions. There is a special key, <strong>PartitionKey</strong>, which defines these partitions. When you insert data into the database, all documents in a container with the same <strong>PartitionKey</strong> are considered to be in the same logical partition.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/56c970e2-3c96-4b45-87e0-f049a763711d.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi80YTBmZDAyNC1mMTBkLTQ4YjAtOGQwOS1iOGZjMjJlNWJlNjgvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4MjIxODYxOCwiZXhwIjoxNzgyODIzNDE4fQ.O3rqUalxC1-TEfHWVAYVLiq_ZgbMYCDDv-W18TrMCFU" alt="" style="display:block;margin:0 auto" />

<p>If you look at the diagram above, you can see a container called <strong>data</strong> with documents inside it. Documents with the same <strong>PartitionKey</strong> are in the same logical partition.</p>
<p>Why is this important? Transactions in <strong>Azure Cosmos DB</strong> are called "transactional batches," and they operate on <strong>a single logical partition</strong>, guaranteeing ACID properties. This means that our business data and events must have the same <strong>PartitionKey</strong> and be in the same container.</p>
<p>Let's look how it works. Here's the base class for a document:</p>
<pre><code class="language-csharp">public class DocumentBase&lt;T&gt; where T : class
{
    private DocumentBase() { }

    public DocumentBase(string? partitionKey, string type, T data, string? id = null)
    {
        Data = data;
        Type = type;
        PartitionKey = partitionKey;
        Id = id ?? Guid.NewGuid().ToString();
    }

    public string Id { get; set; }
    public string? PartitionKey { get; init; }
    public string Type { get; init; } = null!;
    public T Data { get; init; } = null!;
    public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
</code></pre>
<p>The code snippet below shows how to use a transactional batch to create a user and an event:</p>
<pre><code class="language-csharp">var userId = Guid.NewGuid().ToString();

var user = new DocumentBase&lt;User&gt;(
    partitionKey: userId,
    type: "user",
    data: new User
    {
        Name = "John Doe",
        Email = "john.doe@example.com",
    },
    id: userId);

var userCreatedEvent = new DocumentBase&lt;UserCreatedEvent&gt;(
    partitionKey: userId,
    type: "event",
    data: new UserCreatedEvent 
    { 
        Data = new UserCreatedEventData(userId, user.Data.Name, user.Data.Email)
    });


var partitionKey = new PartitionKey(userId);
var transactionalBatch = container.CreateTransactionalBatch(partitionKey);

transactionalBatch.CreateItem(user);
transactionalBatch.CreateItem(userCreatedEvent);

// Execute the transactional batch
var batchResponse = await transactionalBatch.ExecuteAsync();

if (!batchResponse.IsSuccessStatusCode)
{
    throw new InvaidOperationException("Transactional batch failed.");
}
</code></pre>
<p>Let's break down the code:</p>
<ul>
<li><p><strong>Lines 3–19</strong>: Create the <code>User</code> entity and the <code>UserCreatedEvent</code>. Note that we use the same <strong>PartitionKey</strong> and set the <code>Type</code> property to easily distinguish between user data and events.</p>
</li>
<li><p><strong>Lines 22–29</strong>: Create a <strong>Transactional Batch</strong> using the previously defined <code>PartitionKey</code>. Both entities are added to the batch, which is then executed to save the data into <strong>Azure Cosmos DB</strong>.</p>
</li>
<li><p><strong>Lines 31–34</strong>: Check the result of the batch execution. In a real-world application, you might want to add logging or other actions, but here I simply throw an exception.</p>
</li>
</ul>
<p>After the code executes, you'll find two documents with the same <strong>PartitionKey</strong> but different IDs.</p>
<p>The user document looks like this:</p>
<pre><code class="language-json">{
    "id": "0aa14bfb-f5f7-45e3-8112-45b14bec48b3",
    "partitionKey": "0aa14bfb-f5f7-45e3-8112-45b14bec48b3",
    "type": "user",
    "data": {
        "name": "John Doe",
        "email": "john.doe@example.com"
    },
    "createdAt": "2026-06-20T12:57:06.834242+00:00",
    "_rid": "EC4xAOFJBqMNAAAAAAAAAA==",
    "_self": "dbs/EC4xAA==/colls/EC4xAOFJBqM=/docs/EC4xAOFJBqMNAAAAAAAAAA==/",
    "_etag": "\"00000000-0000-0000-00b4-4d98780501dd\"",
    "_attachments": "attachments/",
    "_ts": 1781960228
}
</code></pre>
<p>The event looks like this:</p>
<pre><code class="language-json">{
    "id": "e645943f-208c-4dba-a149-1bcb53388302",
    "partitionKey": "0aa14bfb-f5f7-45e3-8112-45b14bec48b3",
    "type": "event",
    "data": {
        "eventType": "UserCreatedEvent",
        "data": {
            "userId": "0aa14bfb-f5f7-45e3-8112-45b14bec48b3",
            "name": "John Doe",
            "email": "john.doe@example.com"
        }
    },
    "createdAt": "2026-06-20T12:57:07.45013+00:00",
    "_rid": "EC4xAOFJBqMOAAAAAAAAAA==",
    "_self": "dbs/EC4xAA==/colls/EC4xAOFJBqM=/docs/EC4xAOFJBqMOAAAAAAAAAA==/",
    "_etag": "\"00000000-0000-0000-00b4-4d98800501dd\"",
    "_attachments": "attachments/",
    "_ts": 1781960228
}
</code></pre>
<p>The next step in implementing a proper <strong>Outbox</strong> mechanism is reading the event data from <strong>Azure Cosmos DB</strong>. For this, the database provides a <strong>change feed</strong>, which is a persistent storage of all changes in all containers. To read the change feed, we can use a background processor or an <strong>Azure Function</strong>.</p>
<p>I prefer the second approach because if you're using <strong>Azure Cosmos DB</strong>, your application is likely already in Azure. Creating and deploying a function would be the easiest way.</p>
<pre><code class="language-csharp">public class OutboxFunction
{
    private const string TopicName = "user-events";
    
    private readonly ServiceBusClient _serviceBusClient;

    public OutboxFunction(
        IAzureClientFactory&lt;ServiceBusClient&gt; factory)
    {
        _serviceBusClient = factory.CreateClient("Default");
    }

    [Function("OutboxFunction")]
    public async Task Run([CosmosDBTrigger(
        databaseName: "%COSMOS_DATABASE_NAME%",
        containerName: "%COSMOS_CONTAINER_NAME%",
        Connection = "COSMOS_CONNECTION",
        LeaseContainerName = "leases",
        CreateLeaseContainerIfNotExists = true)] IReadOnlyList&lt;DocumentBase&lt;dynamic&gt;&gt; documents)
    {
        var sender = _serviceBusClient.CreateSender(TopicName);

        foreach (var doc in documents.Where(x =&gt; x.Type == "event"))
        {
            var message = new ServiceBusMessage(BinaryData.FromObjectAsJson(doc.Data))
            {
                ContentType = "application/json",
                MessageId = Guid.NewGuid().ToString()
            };

            await sender.SendMessageAsync(message);
        }

        await sender.DisposeAsync();
    }
}
</code></pre>
<p>Let's review the code:</p>
<p><strong>Lines 14-19</strong>: shows how to use <code>CosmosDBTrigger</code> to receive the changed documents. I use <code>DocumentBase&lt;dynamic&gt;</code> because not only events will be returned and easiest way is to use <code>dynamic</code>.</p>
<p><strong>Line 21</strong>: create the sender for a topic <code>user-events</code>.</p>
<p><strong>Line 23</strong>: change feed detects all changes in a container, so besides the events there will be the real documents which we do not want to send. It is the reason why we filter all documents by the type.</p>
<p><strong>Lines 25-31</strong>: the json-serialization and sending the message to the <strong>Azure Service Bus</strong> topic.</p>
<p><strong>Line 34</strong>: disposing the sender for releasing the resources.</p>
<p>This function is simple and lacks exception handling, which is important in production-ready systems. Imagine a scenario where an exception occurs and <code>DisposeAsync</code> is not called. Resources may not be released, and after some time, a flood of exceptions could fill your logging system. Pay attention to this and use <code>try/catch/finally</code> for this function.</p>
<p>In the previous code snippet, I used <strong>Azure Service Bus</strong>, but this approach will work with any message broker you prefer.</p>
<p>The system diagram for the <strong>Azure Cosmos DB</strong> approach looks like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/64c01f633d0d5beec2f4cb9f/6a7923f9-1314-4c7d-9475-8b27f9b8d3ef.svg" alt="" style="display:block;margin:0 auto" />

<img src="https://docs.2getherme.nl/api/files.get?sig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJ1cGxvYWRzLzQ0NmZkYTIzLTM5MmItNGZmOS1hYjE3LWQ3NjJjOGI3YjI0Zi9kN2Y0NDJkOC1iODJlLTRhYjYtYTQ1Yy05NDcwYjU1YTNiYmIvZGlhZ3JhbS5zdmciLCJ0eXBlIjoiYXR0YWNobWVudCIsImlhdCI6MTc4MjIxODYxOCwiZXhwIjoxNzgyODIzNDE4fQ.I8L74XMbdoxuFwEvGEpBNEfNtgegQK8xTv7NGiG06wA" alt="" style="display:block;margin:0 auto" />

<h2>Thoughts and Considerations</h2>
<p>We don't need to poll for events here because the trigger fires after changes in the container. However, we can still receive duplicate events if an exception occurs after sending the event to <strong>Azure Service Bus</strong> but before the change is processed. This is something to consider.</p>
<p>Another important consideration is the proper cleanup of event data. Without it, the change feed can contain many stale records, which cost money but provide no value. To address this, we can use the <strong>TTL (Time To Live)</strong> feature of <strong>Cosmos DB</strong>. TTL defines, in seconds, how long a document will live in the container. It can be set at the container or item level, or disabled entirely.</p>
<h1>MongoDB</h1>
<p><strong>MongoDB</strong> is a popular choice for those who want to use a NoSQL database. Let's see how we can implement the <strong>Outbox</strong> pattern using <strong>MongoDB</strong> and <strong>Kafka</strong> as a message broker.</p>
<p>For cases where atomicity is required across multiple collections, we can use transactions. The only requirement is that a replica set must be created, which is standard for production systems.</p>
<p>The code for creating a user and saving an event is shown below:</p>
<pre><code class="language-csharp">app.MapPost("/api/users", async (UserDto dto, IMongoDatabase db) =&gt;
{
    using var session = await db.Client.StartSessionAsync();
    User user = null!;
    try
    {
        await session.WithTransactionAsync(async (s, ct) =&gt;
        {
            var usersColl = db.GetCollection&lt;User&gt;("users");
            var outboxColl = db.GetCollection&lt;OutboxEvent&gt;("outbox_events");

            user = new User { Id = ObjectId.GenerateNewId(), Name = dto.Name, Email = dto.Email };
            await usersColl.InsertOneAsync(s, user, null, ct);

            var evt = new OutboxEvent
            {
                Type = "UserCreated",
                Payload = new BsonDocument
                {
                    {"userId", user.Id.ToString()},
                    {"name", user.Name},
                    {"email", user.Email}
                },
                CreatedAt = DateTime.UtcNow,
                Processed = false
            };
            await outboxColl.InsertOneAsync(s, evt, null, ct);
            return true;
        });
        
        return Results.Created($"/users/{user.Id}", user);
    }
    catch (Exception)
    {
        throw;
    }
});
</code></pre>
<p>The general idea remains the same; the only difference is how transactions are used in <strong>MongoDB</strong>. We need to create a new session (<strong>line 3</strong>) and, within this session, create a transaction (<strong>line 7</strong>).</p>
<ul>
<li><p><strong>Lines 12–13</strong>: Create and save the user.</p>
</li>
<li><p><strong>Lines 15–27</strong>: Create and save the event. Note that we set <code>Processed</code> to <code>false</code>, which indicates that the event has not yet been processed.</p>
</li>
</ul>
<p>For the event processor, I chose a simple <code>BackgroundService</code> that starts a <strong>Change Stream</strong> to listen for changes in the <strong>outbox_events</strong> collection.</p>
<pre><code class="language-csharp">public class OutboxProcessor : BackgroundService
{
    private readonly IMongoDatabase _db;
    private readonly IProducer&lt;string, string&gt; _producer;
    public OutboxProcessor(IMongoDatabase db)
    {
        _db      = db;
        var cfg  = new ProducerConfig { BootstrapServers = Environment.GetEnvironmentVariable("KAFKA_BOOTSTRAP") ?? "kafka:9092" };
        _producer = new ProducerBuilder&lt;string, string&gt;(cfg).Build();
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var coll = _db.GetCollection&lt;OutboxEvent&gt;("outbox_events");
        var meta = _db.GetCollection&lt;BsonDocument&gt;("outbox_metadata");

        var pipeline = new BsonDocument[]
        {
            new BsonDocument("$match", new BsonDocument("operationType", "insert"))
        };

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                var resumeDoc = await meta.Find(Builders&lt;BsonDocument&gt;.Filter.Eq("_id", "resume_token"))
                    .FirstOrDefaultAsync(stoppingToken);

                var options = new ChangeStreamOptions();
                if (resumeDoc != null)
                    options.ResumeAfter = resumeDoc["token"].AsBsonDocument;

                using var cursor = await coll.WatchAsync&lt;ChangeStreamDocument&lt;OutboxEvent&gt;&gt;(
                    pipeline, options, stoppingToken);

                await cursor.ForEachAsync(async change =&gt;
                {
                    var evt = change.FullDocument;
                    try
                    {
                        await _producer.ProduceAsync(
                            "user-events",
                            new Message&lt;string, string&gt;
                            {
                                Key   = evt.Id.ToString(),
                                Value = evt.Payload.ToJson()
                            },
                            stoppingToken);

                        var filter = Builders&lt;OutboxEvent&gt;.Filter.Eq(e =&gt; e.Id, evt.Id);
                        var update = Builders&lt;OutboxEvent&gt;.Update.Set(e =&gt; e.Processed, true);
                        await coll.UpdateOneAsync(filter, update, cancellationToken: stoppingToken);

                        await meta.ReplaceOneAsync(
                            Builders&lt;BsonDocument&gt;.Filter.Eq("_id", "resume_token"),
                            new BsonDocument
                            {
                                { "_id", "resume_token" },
                                { "token", change.ResumeToken }
                            },
                            new ReplaceOptions { IsUpsert = true },
                            cancellationToken: stoppingToken);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to process event {evt.Id}: {ex.Message}");
                    }
                }, stoppingToken);
            }
            catch (OperationCanceledException)
            {
                break;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Change Stream error: {ex.Message}. Reconnecting in 5s...");
                await Task.Delay(5000, stoppingToken);
            }
        }
    }
}
</code></pre>
<p>Let's break down the code, as there are some differences from what we've already seen:</p>
<ul>
<li><p><strong>Lines 17–20</strong>: Create the pipeline for the change stream. In simple terms, this is the configuration that specifies when we want to receive notifications about changes in the collection. There are different stages available, and you can use more than one if needed. In our case, we use <code>$match</code> to check that <code>operationType</code> is equal to <code>insert</code>.</p>
</li>
<li><p><strong>Line 26</strong>: Query the resume token from the <strong>outbox_metadata</strong> collection. The resume token tells the change feed where it stopped previously. If the background process was shut down due to planned maintenance or an unexpected issue, when it starts again, it will know from which point in time to resume. This needs to be implemented because, by default, the change feed does not look back and starts waiting for changes only from the time it begins.</p>
</li>
<li><p><strong>Lines 29-31</strong>: Creating the <code>ChangeStreamOptions</code> and if we have a resume token we set <code>ResumeAfter</code> property with the value of token.</p>
</li>
<li><p><strong>Line 33</strong>: Create the change feed cursor.</p>
</li>
<li><p><strong>Line 36</strong>: Provide the function that will be called for each change in the collection.</p>
</li>
<li><p><strong>Lines 41–48</strong>: Send the event to the Kafka topic using <code>IProducer.ProduceAsync</code>.</p>
</li>
<li><p><strong>Lines 50–51</strong>: Update the <code>Processed</code> field to <code>true</code>, indicating that the event has already been sent.</p>
</li>
<li><p><strong>Lines 54–62</strong>: Save the resume token.</p>
</li>
</ul>
<h2>Thoughts and Considerations</h2>
<p>As we've seen, the implementation of <strong>Outbox</strong> for <strong>MongoDB</strong> follows the same pattern. However, it has a similar problem: cleaning up the collection with outbox events. Here are some approaches.</p>
<h3>TTL Index</h3>
<p><a href="https://www.mongodb.com/docs/manual/core/index-ttl/"><strong>TTL Index</strong></a> is a special index that tells MongoDB after how much time a document can be removed from the collection. This might be a good idea because it is an automated approach. However, the downside is the difficulty of finding the correct time interval after which events can be deleted. Setting it too high will cause the collection to grow in size, while setting it too low might result in situations where an event needs to be reprocessed but has already been deleted.</p>
<h3>Capped Collections</h3>
<p><a href="https://www.mongodb.com/docs/manual/core/capped-collections/"><strong>Capped Collections</strong></a> are a special type of collection with a fixed size. When the collection is full and new events arrive, it automatically overwrites the oldest ones. This type of outbox can be helpful when you need predictable storage usage. The downside is that we cannot predict when events will be deleted, as any spike in the number of events could delete many old ones.</p>
<h3>Immediate cleaning</h3>
<p>Another possibility is to delete the event immediately after it is sent. This can be done in the same background process where the change stream sends the events to the message broker. Again, it is unclear what to do if the event needs to be reprocessed.</p>
<p>Each of these approaches has its pros and cons. Perhaps, as developers, we should not focus on a single approach but combine them. For example, in a system where some events are more important than others, less important events could be deleted immediately after being published, while important ones could wait for automatic deletion using the TTL approach.</p>
<h1>Summary</h1>
<p>As we have seen, the components of the <strong>Outbox</strong> pattern remain the same regardless of the database or implementation approach. Whether we use a relational or NoSQL database, the core idea is consistent: we save the event in the database as part of the same transaction that modifies the business data. A background process then retrieves unpublished events and publishes them.</p>
<p>Despite using different databases or approaches for polling events, we still face the same key considerations: how to clean up events, how to avoid duplicates, and how to handle unexpected situations.</p>
<p>The <strong>Outbox</strong> pattern might look very simple at first glance, but appearances can be deceiving.</p>
<h1>Links</h1>
<p><a href="https://microservices.io/patterns/data/transactional-outbox.html">Pattern: Transactional outbox</a></p>
<p><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/change-feed-processor">Change feed processor in Azure Cosmos DB</a></p>
<p><a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2-trigger?tabs=python-v2%2Cisolated-process%2Cextensionv4%2Cnodejs-v4%2Cidentity-based&amp;pivots=programming-language-csharp">Azure Cosmos DB trigger for Azure Functions 2.x and higher</a></p>
<p><a href="https://learn.microsoft.com/en-us/Azure/cosmos-db/how-to-time-to-live?tabs=dotnet-sdk-v3">Configure time to live in Azure Cosmos DB</a></p>
<p><a href="https://www.mongodb.com/docs/manual/core/transactions/">Transactions in MongoDB</a></p>
<p><a href="https://www.mongodb.com/docs/manual/changeStreams/">Change Streams in MongoDB</a></p>
<p><a href="https://www.mongodb.com/docs/manual/core/index-ttl/">TTL Indexes in MongoDB</a></p>
]]></content:encoded></item><item><title><![CDATA[How to replace FluentAssertions library]]></title><description><![CDATA[FluentAssertions is a library that almost everyone in the .NET community has either used or at least heard of. Until version 8, it was a free, open-source…]]></description><link>https://iharmaiseyeu.net/how-to-replace-fluentassertions-library</link><guid isPermaLink="true">https://iharmaiseyeu.net/how-to-replace-fluentassertions-library</guid><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[assertion]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Thu, 20 Feb 2025 07:00:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739981060985/d2418b81-9e0a-41e5-a810-bb60551c3b8f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://fluentassertions.com/">FluentAssertions</a> is a library that almost everyone in the .NET community has either used or at least heard of. Until version 8, it was a free, open-source project. However, starting with version 8, a license is required to use it.</p>
<p>I am not against purchasing software or libraries, but sometimes it is not financially feasible. In such cases, we need to find alternative solutions.</p>
<h2 id="heading-using-fluentassertions-7">Using FluentAssertions 7</h2>
<p>We can continue using <strong>FluentAssertions</strong> by sticking with version 7, which remains free and receives updates. To ensure we do not unintentionally upgrade to version 8, we can specify the exact version in our <code>.csproj</code> file using square brackets. This prevents IDEs from suggesting an update.</p>
<pre><code class="lang-plaintext">&lt;PackageReference Include="FluentAssertions" Version="[7.0.0]" /&gt;
</code></pre>
<p><strong>Advantages</strong>: No changes are required in tests, and we can continue using <strong>FluentAssertions</strong> as before.</p>
<p><strong>Disadvantages</strong>: If someone on the team manually updates the package version, they may unintentionally violate the license agreement. Additionally, because version 7 is no longer the primary focus, its support could end at any time. If that happens and you have thousands of tests relying on an outdated package, you might spend valuable time fixing tests instead of delivering software.</p>
<h2 id="heading-using-an-alternative-like-shouldly">Using an Alternative Like Shouldly</h2>
<p><a target="_blank" href="https://github.com/shouldly/shouldly">Shouldly</a> is a similar assertion library that receives regular updates and is licensed under the <a target="_blank" href="https://github.com/shouldly/shouldly/blob/master/LICENSE.txt">BSD 3-Clause License</a>, allowing its use in proprietary software.</p>
<p>The package has <a target="_blank" href="https://docs.shouldly.org/">well-written documentation</a>, and its syntax is intuitive. For those familiar with <strong>FluentAssertions</strong>, transitioning to <strong>Shouldly</strong> should not be difficult.</p>
<p>To install the package, use the following command:</p>
<pre><code class="lang-bash">dotnet add package Shouldly
</code></pre>
<p>Example assertions:</p>
<pre><code class="lang-csharp">myObject.DoWorkAndReturnInteger().ShouldBe(<span class="hljs-number">12</span>);
myObject.Exists().ShouldBeTrue();
</code></pre>
<p><strong>Advantages</strong>: Open-source, actively maintained, and has good documentation with a clean syntax.</p>
<p><strong>Disadvantages</strong>: Since it is still a third-party project, there is always a risk that its maintainers may decide to change its licensing model in the future. Additionally, while the syntax is similar, it is not identical, meaning the entire test codebase will require modifications.</p>
<h2 id="heading-writing-your-assertion-library">Writing Your Assertion Library</h2>
<p>If you primarily use <strong>FluentAssertions</strong> for its syntax and can accept less polished exception messages, developing your assertion library might be a viable option. Using assertions from your existing test framework simplifies the process.</p>
<p>The following example is based on <a target="_blank" href="https://xunit.net/">xUnit</a>, but the concept applies to other frameworks as well.</p>
<p>Start by creating a C# library project and adding the <code>xunit.assert</code> package:</p>
<pre><code class="lang-bash">dotnet add package xunit.assert
</code></pre>
<p>This package provides all available <strong>xUnit</strong> assertions, allowing us to wrap them in our custom assertions.</p>
<p>Consider the following test that uses <strong>FluentAssertions</strong>:</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">Fact</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">GetSomeString_ShouldReturnString</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-comment">// Arrange</span>
    <span class="hljs-keyword">var</span> expected = <span class="hljs-string">"string we expect"</span>;

    <span class="hljs-comment">// Act</span>
    <span class="hljs-keyword">var</span> actual = _sut.GetSomeString();

    <span class="hljs-comment">// Assert</span>
    actual.Should().Be(expected);
}
</code></pre>
<p>To support similar assertions, let's create a <code>StringAssertions</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">StringAssertions</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> _value;

    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">StringAssertions</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span></span>)</span>
    {
        _value = <span class="hljs-keyword">value</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Be</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> expected</span>)</span> =&gt; Assert.Equal(expected, _value);
}
</code></pre>
<p>This class is a simple wrapper around xUnit assertions. We can use it like this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> actual = <span class="hljs-string">"my string"</span>;
<span class="hljs-keyword">var</span> expected = <span class="hljs-string">"another string"</span>;

<span class="hljs-keyword">new</span> StringAssertions(actual).Be(expected);
</code></pre>
<p>While this works, the syntax is not ideal. We can improve it with an extension method:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AssertionExtensions</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> StringAssertions <span class="hljs-title">Should</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> <span class="hljs-keyword">string</span> actual</span>)</span> =&gt; <span class="hljs-keyword">new</span> StringAssertions(actual);
}
</code></pre>
<p>Now, we can write assertions in the familiar <code>.Should().Be()</code> format.</p>
<p><strong>Advantages</strong>: The assertion code remains under your control and can be modified as needed. If necessary, you can integrate another assertion library in the future.</p>
<p><strong>Disadvantages</strong>: Writing and maintaining assertion methods can be time-consuming. While simple, achieving feature parity with <strong>FluentAssertions</strong> or <strong>Shouldly</strong> would require significant effort.</p>
<h2 id="heading-forking-fluentassertions-7">Forking FluentAssertions 7</h2>
<p>I list this option last because very few developers will likely choose it. There is a <a target="_blank" href="https://github.com/fluentassertions/fluentassertions/tree/support-7.0">support-7.0 branch</a> that contains the <strong>FluentAssertions</strong> source code under the Apache 2.0 license. This means the code can still be used in personal and commercial projects.</p>
<p>If your test suite heavily depends on <strong>FluentAssertions</strong> and migrating to another library is impractical, forking the repository, packaging your version, and using it internally might be a reasonable solution.</p>
<blockquote>
<p>Before proceeding, carefully review the repository's license file to understand the legal implications.</p>
</blockquote>
<p><strong>Advantages</strong>: No test changes are required, and you can continue using <strong>FluentAssertions</strong> as before.</p>
<p><strong>Disadvantages</strong>: You must maintain the fork, apply necessary updates, and fix bugs that are not addressed in the main repository.</p>
<h2 id="heading-summary">Summary</h2>
<p>This article provides an overview of possible alternatives to <strong>FluentAssertions</strong>. None of these options are perfect, and each comes with its own set of advantages and disadvantages. Choosing the best approach depends on various factors, including the size of your test codebase, the feasibility of using alternative packages, and your willingness to invest time in writing additional code.</p>
<h2 id="heading-links">Links</h2>
<p><a target="_blank" href="https://fluentassertions.com/">https://fluentassertions.com/</a></p>
<p><a target="_blank" href="https://github.com/shouldly/shouldly">https://github.com/shouldly/shouldly</a></p>
<p><a target="_blank" href="https://docs.shouldly.org/">https://docs.shouldly.org/</a></p>
<p><a target="_blank" href="https://xunit.net/">Home &gt; xUnit.net</a></p>
]]></content:encoded></item><item><title><![CDATA[Hosting .NET 8 Applications in Azure Kubernetes Service (AKS)]]></title><description><![CDATA[This article is the third in the series "Use Kubernetes to host .NET 8 applications": Containerize and Host .NET 8 applications in Kubernetes Scaling .NET…]]></description><link>https://iharmaiseyeu.net/hosting-net-8-applications-in-azure-kubernetes-service-aks</link><guid isPermaLink="true">https://iharmaiseyeu.net/hosting-net-8-applications-in-azure-kubernetes-service-aks</guid><category><![CDATA[dotnet]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[containers]]></category><category><![CDATA[Azure]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Mon, 02 Dec 2024 08:00:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733050455167/ad2963bb-bbaa-4c58-bff5-b5bdc7984370.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is the third in the series "Use Kubernetes to host .NET 8 applications":</p>
<ul>
<li><p><a target="_blank" href="https://iharmaiseyeu.net/containerize-and-host-net-8-application-in-kubernetes">Containerize and Host .NET 8 applications in Kubernetes</a></p>
</li>
<li><p><a target="_blank" href="https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes">Scaling .NET 8 Applications in Kubernetes</a></p>
</li>
<li><p>Hosting .NET 8 Applications in Azure Kubernetes Service (AKS) (this article)</p>
</li>
</ul>
<p>The <a target="_blank" href="https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes">previous article</a> explored scaling .NET applications in a local Kubernetes environment, including concepts like replicas, deployments, and load balancers.</p>
<p>This article explains how to transition your application from a local Kubernetes cluster to Azure Kubernetes Service (AKS).</p>
<h3 id="heading-setting-up-azure-kubernetes-service-aks">Setting Up Azure Kubernetes Service (AKS)</h3>
<h4 id="heading-create-an-aks-cluster">Create an AKS cluster</h4>
<p>Azure provides multiple ways to create an AKS cluster. You can use the Azure CLI, Azure Portal, or Azure PowerShell. This article uses Azure CLI for simplicity. Alternatively, you can follow the <a target="_blank" href="https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal?tabs=azure-cli">Azure Portal tutorial</a>.</p>
<p>First, ensure you have the <a target="_blank" href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">Azure CLI</a> installed or use the <a target="_blank" href="https://learn.microsoft.com/en-us/azure/cloud-shell/overview">Azure Cloud Shell</a>. If using Azure CLI locally, log in with:</p>
<pre><code class="lang-powershell">az login
</code></pre>
<p>For streamlined setup, initialize variables for resource names and locations:</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$randomId</span> = (<span class="hljs-built_in">New-Guid</span>).ToString().Substring(<span class="hljs-number">0</span>,<span class="hljs-number">8</span>)
<span class="hljs-variable">$location</span> = <span class="hljs-string">"northeurope"</span>
<span class="hljs-variable">$resourceGroup</span> = <span class="hljs-string">"hello-kube<span class="hljs-variable">$randomId</span>"</span>
<span class="hljs-variable">$aksName</span> = <span class="hljs-string">"hktest<span class="hljs-variable">$randomId</span>"</span>
<span class="hljs-variable">$storageName</span> = <span class="hljs-string">"hellokubestorage<span class="hljs-variable">$randomId</span>"</span>
<span class="hljs-variable">$acrName</span> = <span class="hljs-string">"hellokubeacr<span class="hljs-variable">$randomId</span>"</span>
</code></pre>
<p>The <code>$randomId</code> variable ensures unique resource names.</p>
<p>Next, create a resource group to organize the Azure resources:</p>
<pre><code class="lang-powershell">az <span class="hljs-built_in">group</span> create -<span class="hljs-literal">-location</span> <span class="hljs-variable">$location</span> -<span class="hljs-literal">-name</span> <span class="hljs-variable">$resourceGroup</span>
</code></pre>
<p>Create the AKS cluster with the following command:</p>
<pre><code class="lang-powershell">az aks create -<span class="hljs-literal">-resource</span><span class="hljs-literal">-group</span> <span class="hljs-variable">$resourceGroup</span> `
    -<span class="hljs-literal">-name</span> <span class="hljs-variable">$aksName</span> `
    -<span class="hljs-literal">-node</span><span class="hljs-literal">-count</span> <span class="hljs-number">1</span> `
    -<span class="hljs-literal">-enable</span><span class="hljs-literal">-app</span><span class="hljs-literal">-routing</span> `
    -<span class="hljs-literal">-generate</span><span class="hljs-literal">-ssh</span><span class="hljs-literal">-keys</span>
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>--node-count 1</code> creates a single-node cluster.</p>
</li>
<li><p><code>--enable-app-routing</code> simplifies application DNS setup.</p>
</li>
<li><p><code>--generate-ssh-keys</code> creates SSH keys for secure node access.</p>
</li>
</ul>
<h4 id="heading-connect-kubectl-to-aks-cluster"><strong>Connect kubectl to AKS cluster</strong></h4>
<p>To interact with the AKS cluster, use <code>kubectl</code>. If using Azure Cloud Shell, <code>kubectl</code> is pre-installed. For local installations, install it with:</p>
<pre><code class="lang-powershell">az aks <span class="hljs-built_in">install-cli</span>
</code></pre>
<p>To start using <code>kubectl</code> we need to download credentials that were generated during the provisioning our cluster:</p>
<pre><code class="lang-powershell">az aks <span class="hljs-built_in">get-credentials</span> -<span class="hljs-literal">-resource</span><span class="hljs-literal">-group</span> <span class="hljs-variable">$resourceGroup</span> -<span class="hljs-literal">-name</span> <span class="hljs-variable">$aksName</span>
</code></pre>
<p>Verify the connection by checking the nodes:</p>
<pre><code class="lang-powershell">kubectl get nodes
</code></pre>
<p>You should see the cluster's nodes listed with a <strong>Ready</strong> status, similar to this</p>
<pre><code class="lang-plaintext">NAME                                STATUS   ROLES    AGE    VERSION
aks-nodepool1-40348856-vmss000000   Ready    &lt;none&gt;   4d2h   v1.29.9
</code></pre>
<h3 id="heading-configuring-persistent-storage-in-aks">Configuring Persistent Storage in AKS</h3>
<p>In the <a target="_blank" href="https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes">previous article</a>, we used <code>hostPath</code> for storage. However, in AKS, storage needs to be available across all nodes. Azure offers several storage options, including Azure Files, Azure Disks, and Azure Blob Storage.</p>
<p>You can find the comparison table below. More information regarding each service can be found at <a target="_blank" href="https://learn.microsoft.com/en-us/azure/aks/concepts-storage">this link</a>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Storage</td><td>Best for</td><td>Access Mode</td><td>Performance</td><td>Use Case</td></tr>
</thead>
<tbody>
<tr>
<td>Azure Disks</td><td>Block storage for VMs and Kubernetes Pods</td><td>ReadWriteOnce</td><td>High IOPS, low latency (Premium/Ultra SSD)</td><td>Databases, high-performance VMs, Kubernetes</td></tr>
<tr>
<td>Azure Files</td><td>Shared storage, accessible by multiple nodes</td><td>ReadWriteMany</td><td>Standard HDD or Premium SSD</td><td>Shared directories, Kubernetes multi-node</td></tr>
<tr>
<td>Azure NetApp Files</td><td>High-performance enterprise file storage</td><td>ReadWriteMany</td><td>High IOPS, scalable, low-latency (NFS/SMB)</td><td>HPC, large databases, SAP</td></tr>
<tr>
<td>Azure Blob Storage</td><td>Scalable, cloud-native object storage</td><td>API-based access</td><td>Hot, Cool, Archive tiers based on frequency</td><td>Backups, media storage, large datasets</td></tr>
</tbody>
</table>
</div><p>From the table, <strong>Azure Files</strong> and <strong>Azure Blob Storage</strong> stand out as suitable options for our needs. However, supporting Azure Blob Storage requires application-level changes, while Azure Files is already compatible with our requirements. It provides a fully managed file-share service that can be accessed simultaneously by multiple nodes.</p>
<p>Here’s the updated <code>storage.yml</code> configuration file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">PersistentVolume</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">hello-pv</span>
  <span class="hljs-attr">labels:</span>
    <span class="hljs-attr">type:</span> <span class="hljs-string">azure-file</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">storageClassName:</span> <span class="hljs-string">azurefile</span>
  <span class="hljs-attr">capacity:</span>
    <span class="hljs-attr">storage:</span> <span class="hljs-string">1Gi</span>
  <span class="hljs-attr">accessModes:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">ReadWriteMany</span>
  <span class="hljs-attr">azureFile:</span>
    <span class="hljs-attr">secretName:</span> <span class="hljs-string">azure-secret</span>
    <span class="hljs-attr">shareName:</span> <span class="hljs-string">hello-kube-share</span>
    <span class="hljs-attr">readOnly:</span> <span class="hljs-literal">false</span>
<span class="hljs-meta">---</span>
<span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">PersistentVolumeClaim</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">hello-pvc</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">storageClassName:</span> <span class="hljs-string">azurefile</span>
  <span class="hljs-attr">accessModes:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">ReadWriteMany</span>
  <span class="hljs-attr">resources:</span>
    <span class="hljs-attr">requests:</span>
      <span class="hljs-attr">storage:</span> <span class="hljs-string">1Gi</span>
</code></pre>
<p>In this configuration:</p>
<ul>
<li><p><code>storageClassName: azurefile</code> provisions persistent storage using Azure Files, which is preconfigured in AKS.</p>
</li>
<li><p>The <code>azureFile</code> section specifies the Azure File Share configuration, including the share name (<code>shareName: hello-kube-share</code>) and the Kubernetes secret (<code>secretName: azure-secret</code>) for authentication.</p>
</li>
</ul>
<p>This setup enables high scalability and multi-node support by leveraging Azure's distributed file system.</p>
<h3 id="heading-creating-the-azure-storage-account">Creating the Azure Storage Account</h3>
<p>Before applying the storage configuration, we need to create an Azure Storage Account to house the file share. Use the following Azure CLI command:</p>
<pre><code class="lang-powershell">az storage account create `
    -<span class="hljs-literal">-name</span> <span class="hljs-variable">$storageName</span> `
    -<span class="hljs-literal">-resource</span><span class="hljs-literal">-group</span> <span class="hljs-variable">$resourceGroup</span> `
    -<span class="hljs-literal">-location</span> <span class="hljs-variable">$location</span> `
    -<span class="hljs-literal">-sku</span> Standard_LRS `
    -<span class="hljs-literal">-kind</span> StorageV2
</code></pre>
<p>Next, create the file share in the storage account to store configuration files. Begin by retrieving the storage account keys:</p>
<pre><code class="lang-powershell">az storage account keys list `
    -<span class="hljs-literal">-resource</span><span class="hljs-literal">-group</span> <span class="hljs-variable">$resourceGroup</span> `
    -<span class="hljs-literal">-account</span><span class="hljs-literal">-name</span> <span class="hljs-variable">$storageName</span> `
    -<span class="hljs-literal">-query</span> <span class="hljs-string">"[0].value"</span> `
    -<span class="hljs-literal">-output</span> tsv
</code></pre>
<p>Save the output, as you'll need it for the next step. Then, create the file share replacing the first <code>&lt;your-storage-account-key&gt;</code> :</p>
<pre><code class="lang-powershell">az storage share create `
    -<span class="hljs-literal">-name</span> hello<span class="hljs-literal">-kube</span><span class="hljs-literal">-share</span> `
    -<span class="hljs-literal">-account</span><span class="hljs-literal">-name</span> <span class="hljs-variable">$storageName</span> `
    -<span class="hljs-literal">-account</span><span class="hljs-literal">-key</span> &lt;your<span class="hljs-literal">-storage</span><span class="hljs-literal">-account</span><span class="hljs-literal">-key</span>&gt;
</code></pre>
<p>To securely store the Azure Storage Account keys the Kubernetes secret should be created.</p>
<p>Replace <code>&lt;your-storage-account-key&gt;</code> with the saved key and run this command</p>
<pre><code class="lang-powershell">kubectl create secret generic azure<span class="hljs-literal">-secret</span> `
    -<span class="hljs-literal">-from</span><span class="hljs-literal">-literal</span>=azurestorageaccountname=<span class="hljs-variable">$storageName</span> `
    -<span class="hljs-literal">-from</span><span class="hljs-literal">-literal</span>=azurestorageaccountkey=&lt;your<span class="hljs-literal">-storage</span><span class="hljs-literal">-account</span><span class="hljs-literal">-key</span>&gt;
</code></pre>
<p>This command creates a secret named <code>azure-secret</code>, containing:</p>
<ul>
<li><p>The storage account name (<code>azurestorageaccountname</code>).</p>
</li>
<li><p>The storage account key (<code>azurestorageaccountkey</code>).</p>
</li>
</ul>
<p>Finally, apply the storage configuration:</p>
<pre><code class="lang-powershell">kubectl apply <span class="hljs-operator">-f</span> storage.yml
</code></pre>
<p>To verify successful creation, run:</p>
<pre><code class="lang-powershell">kubectl get pv
kubectl get pvc
</code></pre>
<h3 id="heading-azure-container-registry">Azure Container Registry</h3>
<p>Before modifying our application configurations, we need a repository to store our container images. While DockerHub is a popular choice, <strong>Azure Container Registry (ACR)</strong> offers distinct advantages:</p>
<ul>
<li><p><strong>Seamless integration</strong> with Azure Kubernetes Service (AKS), enabling straightforward authentication and access via Azure Active Directory (AAD) and managed identities.</p>
</li>
<li><p><strong>Optimized for Azure</strong> environments, reducing latency when pulling images by hosting the registry in the same region as your AKS cluster.</p>
</li>
<li><p><strong>Enterprise-grade security</strong> features, including private repositories, vulnerability scanning, Azure Private Link, and role-based access control (RBAC) via AAD.</p>
</li>
<li><p><strong>Advanced capabilities</strong> tailored for enterprise use, such as geo-replication, image signing, and full integration with the Azure ecosystem.</p>
</li>
</ul>
<p>Let’s create an ACR instance named <code>hellokubeacr{random}</code> in the same resource group as our AKS cluster. In a production environment, consider placing the ACR in a separate resource group to enable reuse across multiple projects. This approach depends on your specific requirements.</p>
<pre><code class="lang-powershell">az acr create `
    -<span class="hljs-literal">-resource</span><span class="hljs-literal">-group</span> <span class="hljs-variable">$resourceGroup</span> `
    -<span class="hljs-literal">-name</span> <span class="hljs-variable">$acrName</span> `
    -<span class="hljs-literal">-sku</span> Basic `
    -<span class="hljs-literal">-admin</span><span class="hljs-literal">-enabled</span> True
</code></pre>
<p>In this article, we will authenticate with ACR using a login and password, similar to DockerHub. However, multiple authentication methods are available, so I recommend reviewing <a target="_blank" href="https://learn.microsoft.com/en-us/azure/container-registry/container-registry-authentication?tabs=azure-cli">the documentation</a> to choose the best option for your needs.</p>
<p>Log in to Azure Container Registry using the following command:</p>
<pre><code class="lang-powershell">az acr login -<span class="hljs-literal">-name</span> <span class="hljs-variable">$acrName</span>
</code></pre>
<p>If successful, you will see the message <code>Login Succeeded</code>.</p>
<p>To allow AKS pull images from ACR, we need to create a Kubernetes secret. First, retrieve the ACR credentials:</p>
<pre><code class="lang-powershell">az acr credential show -<span class="hljs-literal">-name</span> <span class="hljs-variable">$acrName</span> -<span class="hljs-literal">-resource</span><span class="hljs-literal">-group</span> <span class="hljs-variable">$resourceGroup</span>
</code></pre>
<p>The output will include the username and passwords for your Azure Container Registry. Save this information for use in the next step.</p>
<p>Create the Kubernetes secret for image pulling:</p>
<pre><code class="lang-powershell">kubectl create secret docker<span class="hljs-literal">-registry</span> acr<span class="hljs-literal">-secret</span> `
    -<span class="hljs-literal">-docker</span><span class="hljs-literal">-server</span>=<span class="hljs-string">"<span class="hljs-variable">$acrName</span>.azurecr.io"</span> `
    -<span class="hljs-literal">-docker</span><span class="hljs-literal">-username</span>=&lt;your<span class="hljs-literal">-acr</span><span class="hljs-literal">-username</span>&gt; `
    -<span class="hljs-literal">-docker</span><span class="hljs-literal">-password</span>=&lt;your<span class="hljs-literal">-acr</span><span class="hljs-literal">-password</span>&gt; `
    -<span class="hljs-literal">-docker</span><span class="hljs-literal">-email</span>=&lt;your<span class="hljs-literal">-email</span>&gt;
</code></pre>
<p>At this stage, we have everything we need to push our application images to the cloud.</p>
<h3 id="heading-preparing-container-images">Preparing Container Images</h3>
<h4 id="heading-deploying-the-background-process">Deploying the background process</h4>
<p>Since we already built the application images in <a target="_blank" href="https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes">the previous article</a>, we will reuse them here. To do this, tag the images using the format <code>{container-registry}/{image-name}:{version}</code>.</p>
<ul>
<li><p><code>container-registry</code>: Links the image to the corresponding Azure Container Registry, allowing Kubernetes to locate it during deployment.</p>
</li>
<li><p><code>image-name:version</code>: Identifies the application and its version, aiding in version management within the registry.</p>
</li>
</ul>
<p>For instance, tagging the <code>hello-kube</code> image version <code>1.2</code> for the <code>hellokubeacr{random}</code> registry looks like this:</p>
<pre><code class="lang-powershell">docker tag hello<span class="hljs-literal">-kube</span>:<span class="hljs-number">1.2</span> <span class="hljs-string">"<span class="hljs-variable">$acrName</span>.azurecr.io/hello-kube:1.2"</span>
</code></pre>
<p>Push the image to ACR</p>
<pre><code class="lang-powershell">docker push <span class="hljs-string">"<span class="hljs-variable">$acrName</span>.azurecr.io/hello-kube:1.2"</span>
</code></pre>
<p>Now that the image is stored in ACR and the Kubernetes secret is configured, update your pod’s configuration to pull the image from ACR.</p>
<p>Here is your updated pod configuration file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Pod</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">app-pod</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">volumes:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">data</span>
    <span class="hljs-attr">persistentVolumeClaim:</span>
      <span class="hljs-attr">claimName:</span> <span class="hljs-string">hello-pvc</span>
  <span class="hljs-attr">containers:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">hellokubeacr{random}.azurecr.io/hello-kube:1.2</span> <span class="hljs-comment"># Replace {random} with real value</span>
    <span class="hljs-attr">volumeMounts:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">data</span>
      <span class="hljs-attr">mountPath:</span> <span class="hljs-string">/configuration</span>
  <span class="hljs-attr">imagePullSecrets:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">acr-secret</span>
</code></pre>
<p>The key differences are:</p>
<ul>
<li><p><code>image</code> uses the fully qualified ACR path (<code>hellokubeacr{random}.azurecr.io/hello-kube:1.2</code>) instead of just the image name.</p>
</li>
<li><p><code>imagePullSecrets</code> refers to the <code>acr-secret</code>, enabling Kubernetes to authenticate with ACR.</p>
</li>
</ul>
<p>Apply the configuration:</p>
<pre><code class="lang-powershell">kubectl apply <span class="hljs-operator">-f</span> app<span class="hljs-literal">-pod</span>.yml
</code></pre>
<h4 id="heading-deploying-the-api">Deploying the API</h4>
<p>Deploying the API to AKS follows a similar process. Start with tagging the Docker image and pulling it to ACR.</p>
<pre><code class="lang-powershell"><span class="hljs-comment"># Tag your API image for ACR</span>
docker tag hello<span class="hljs-literal">-kube</span><span class="hljs-literal">-api</span>:<span class="hljs-number">1.0</span> <span class="hljs-string">"<span class="hljs-variable">$acrName</span>.azurecr.io/hello-kube-api:1.0"</span>

<span class="hljs-comment"># Push the image to ACR</span>
docker push <span class="hljs-string">"<span class="hljs-variable">$acrName</span>.azurecr.io/hello-kube-api:1.0"</span>
</code></pre>
<p>The image is available in ACR, update the deployment YAML file to point to the ACR image and configure the appropriate secrets for image pulling.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube-api-deploy</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">2</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">hello-kube-api</span>
  <span class="hljs-attr">strategy:</span>
    <span class="hljs-attr">type:</span> <span class="hljs-string">RollingUpdate</span>
    <span class="hljs-attr">rollingUpdate:</span>
      <span class="hljs-attr">maxUnavailable:</span> <span class="hljs-number">1</span>
      <span class="hljs-attr">maxSurge:</span> <span class="hljs-number">1</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">hello-kube-api</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">data</span>
        <span class="hljs-attr">persistentVolumeClaim:</span>
          <span class="hljs-attr">claimName:</span> <span class="hljs-string">hello-pvc</span>
      <span class="hljs-attr">containers:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube-api</span>
        <span class="hljs-attr">image:</span> <span class="hljs-string">hellokubeacr{random}.azurecr.io/hello-kube-api:1.0</span> <span class="hljs-comment"># Replace {random} with real value</span>
        <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">8080</span>
        <span class="hljs-attr">volumeMounts:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">data</span>
          <span class="hljs-attr">mountPath:</span> <span class="hljs-string">/configuration</span>
      <span class="hljs-attr">imagePullSecrets:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">acr-secret</span>
</code></pre>
<p>Apply the deployment:</p>
<pre><code class="lang-powershell">kubectl apply <span class="hljs-operator">-f</span> api<span class="hljs-literal">-deploy</span>.yml
</code></pre>
<h3 id="heading-setting-up-a-load-balancer">Setting Up a Load Balancer</h3>
<p>To make the API accessible from outside the Kubernetes cluster, we need to expose it via a LoadBalancer. By default, Kubernetes services are internal, meaning they are only accessible within the cluster network. A LoadBalancer allows us to create an external IP address that routes traffic to the appropriate pods inside the cluster. This is crucial for production environments where users or external systems need to interact with the application.</p>
<p>In Azure, the LoadBalancer service type automatically provisions an external IP address through Azure's native load-balancing infrastructure. This simplifies configuration and ensures that your API is publicly reachable with minimal effort.</p>
<p>Here’s the configuration for the LoadBalancer:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Service</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube-lb-svc</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">type:</span> <span class="hljs-string">LoadBalancer</span>
  <span class="hljs-attr">ports:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">port:</span> <span class="hljs-number">8080</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">hello-kube-api</span>
</code></pre>
<p>Apply the service:</p>
<pre><code class="lang-powershell">kubectl apply <span class="hljs-operator">-f</span> api<span class="hljs-literal">-lb</span>.yml
</code></pre>
<h3 id="heading-testing-the-deployment">Testing the Deployment</h3>
<p>With everything in place, retrieve the external IP address of the LoadBalancer service:</p>
<pre><code class="lang-powershell">kubectl get svc
</code></pre>
<p>Look for the <code>hello-kube-lb-svc</code> entry, which will display the external IP address.</p>
<pre><code class="lang-plaintext">NAME                TYPE           CLUSTER-IP    EXTERNAL-IP    PORT(S)          AGE
hello-kube-lb-svc   LoadBalancer   10.0.126.94   72.145.45.65   8080:32551/TCP   61s
kubernetes          ClusterIP      10.0.0.1      &lt;none&gt;         443/TCP          8m43s
</code></pre>
<p>Access the API’s health endpoint <code>/api/health</code> to confirm deployment success.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731511013226/373b907f-8f51-4eea-9d9d-c75d6b73b28b.png" alt class="image--center mx-auto" /></p>
<p>The health endpoint returns the 200 OK with the name of the pod.</p>
<p>The request to <code>/api/state</code> the endpoint gives an increasing number each time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731511043726/ed47e796-9cb4-4315-b48c-f06a5157e4f1.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-summary">Summary</h3>
<p>In this article, we transitioned a .NET 8 application from a local Kubernetes environment to Azure Kubernetes Service (AKS). We set up an AKS cluster, configured Azure Files for persistent storage, integrated Azure Container Registry (ACR), and adjusted configurations for cloud deployment. Finally, we deployed and tested the application, showcasing the power and scalability of Azure for hosting .NET applications.</p>
<h3 id="heading-links">Links</h3>
<p><a target="_blank" href="https://github.com/MasDenBy/blog-samples/tree/main/k8s-net8-part3">Source code | GitHub</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal?tabs=azure-cli">Deploy an Azure Kubernetes Service (AKS) cluster using Azure portal | Microsoft Learn</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">How to install the Azure CLI | Microsoft Learn</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/cloud-shell/overview">What is Azure Cloud Shell? | Microsoft Learn</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/cli/azure/aks#az-aks-create">az aks create | Microsoft Learn</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/aks/concepts-storage">Concepts - Storage in Azure Kubernetes Services (AKS) - Azure Kubernetes Service | Microsoft Learn</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/container-registry/container-registry-authentication?tabs=azure-cli">Azure Container Registry Authentication Options Explained - Azure Container Registry | Microsoft Learn</a></p>
<p>Image credits: <a target="_blank" href="https://www.pexels.com/photo/container-ship-on-sea-23221406/">Container Ship on Sea</a> by <a target="_blank" href="https://www.pexels.com/@marlinclark/">Marlin Clark</a></p>
]]></content:encoded></item><item><title><![CDATA[Scaling .NET 8 Applications in Kubernetes]]></title><description><![CDATA[This article is the second in the series "Use Kubernetes to host .NET 8 applications": Containerize and Host .NET 8 applications in Kubernetes Scaling .NET…]]></description><link>https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes</link><guid isPermaLink="true">https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes</guid><category><![CDATA[.NET]]></category><category><![CDATA[Kubernetes]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Tue, 25 Jun 2024 06:00:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719253623516/ff3c2478-ac7a-4623-9bfe-da43dd4f5ada.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is the second in the series "Use Kubernetes to host .NET 8 applications":</p>
<ul>
<li><p><a target="_blank" href="https://iharmaiseyeu.net/containerize-and-host-net-8-application-in-kubernetes">Containerize and Host .NET 8 applications in Kubernetes</a></p>
</li>
<li><p>Scaling .NET 8 Applications in Kubernetes (this article)</p>
</li>
<li><p>Hosting .NET 8 Applications in Azure Kubernetes Service (AKS)</p>
</li>
</ul>
<p>The <a target="_blank" href="https://iharmaiseyeu.net/containerize-and-host-net-8-application-in-kubernetes">previous article</a> focused on containerizing and hosting a simple .NET 8 console application in Kubernetes. We started by creating a test application and crafting a Dockerfile to build a Docker image of the application. We then explored the basics of Kubernetes, setting up a local Kubernetes cluster using Docker Desktop, and deploying our application container within a Kubernetes pod. Finally, we addressed state persistence challenges by configuring a <code>hostPath</code> volume, ensuring our application's progress is saved across pod restarts.</p>
<p>In this article, I will reveal a few vital components of Kubernetes that help deliver and scale applications.</p>
<h2 id="heading-test-application">Test application</h2>
<p>The test application from the previous article emulates some work and saves the process in a text file. You can follow the process in two ways: observing application logs using <code>kubectl logs</code> or reading the configuration file.</p>
<p>This requires access to Kubernetes and its components. In typical scenarios, users don't have this access. Imagine if, when uploading a video to YouTube, you had to log into the servers to check the status. First, Google wouldn't allow it. Second, it's a poor user experience.</p>
<p>To eliminate this problem we will create an API with an endpoint that shows the current operation state (<a target="_blank" href="https://github.com/MasDenBy/blog-samples/tree/main/k8s-net8-part2">the source code</a>). Here's a snippet of the code.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

<span class="hljs-keyword">var</span> app = builder.Build();

<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> configFileName = <span class="hljs-string">"/configuration/step.config"</span>;

app.MapGet(<span class="hljs-string">"/api/state"</span>, () =&gt;
{
    <span class="hljs-keyword">if</span>(File.Exists(configFileName))
    {
        <span class="hljs-keyword">return</span> Results.Ok(File.ReadAllText(configFileName));
    }

    <span class="hljs-keyword">return</span> Results.BadRequest();
});

app.MapGet(<span class="hljs-string">"/api/health"</span>, () =&gt;
{
    <span class="hljs-keyword">return</span> Results.Ok(Environment.MachineName);
});

app.Run();
</code></pre>
<p>The API has two GET endpoints:</p>
<ul>
<li><p><code>/api/state</code> shows the current operation state, performed by the background process</p>
</li>
<li><p><code>/api/health</code> indicates if the API works as expected and returns the machine name.</p>
</li>
</ul>
<p>The Dockerfile and pod configuration files are similar to the ones used for the background process, so they are not included in this article.</p>
<h2 id="heading-deployment">Deployment</h2>
<p>The way a pod was created in <a target="_blank" href="https://iharmaiseyeu.net/containerize-and-host-net-8-application-in-kubernetes">the previous article</a> has a few drawbacks. The main ones are difficulty in scaling and recreating the pod when it dies.</p>
<p>A Deployment in Kubernetes is like a blueprint for your application. It defines the desired state for your pods and ensures your cluster matches this state. Whether you need to roll out a new version of your app, scale up to handle increased traffic or roll back to a previous version in case of issues, Deployments have you covered.</p>
<p>Deployments make updating your application seamless. You update the Deployment configuration, and Kubernetes takes care of the rest—creating new pods, managing old ones, and ensuring zero downtime. This powerful feature helps you maintain high availability and resilience for your .NET 8 applications.</p>
<p>Next, we will create the deployment for our API service.</p>
<pre><code class="lang-plaintext">apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-kube-api-deploy
spec:
  replicas: 2
  selector:
    matchLabels:
      app: hello-kube-api
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: hello-kube-api
    spec:
      volumes:
      - name: data
        persistentVolumeClaim:
          claimName: hello-pvc
      containers:
      - name: hello-kube-api
        image: hello-kube-api:1.0
        ports:
        - containerPort: 8080
        volumeMounts:
        - name: data
          mountPath: /configuration
</code></pre>
<p>The deployment file looks bulky, but if you look closely, you’ll notice that some parts are similar to pod configuration and only half is new. It's better to start with the new parts. All configuration elements are under the <code>spec</code> element, so I will omit it for clarity.</p>
<ul>
<li><p><code>replicas: 2</code> ensures that two instances (pods) of our application are running at all times, providing redundancy and load balancing.</p>
</li>
<li><p><code>selector</code> with <code>matchLabels</code> tells Kubernetes which pods are managed by this Deployment. Here, it selects pods with the label <code>app: hello-kube-api</code>.</p>
</li>
</ul>
<p>The <code>strategy</code> configuration defines the update strategy: <code>RollingUpdate</code> or <code>Recreate</code>. The <code>RollingUpdate</code> strategy ensures zero downtime by incrementally updating pods and maintaining application availability throughout the process. You can control the update pace with parameters like <code>maxUnavailable</code> and <code>maxSurge</code>, ensuring a seamless user experience. On the other hand, the <code>Recreate</code> strategy shuts down all existing pods before starting new ones, resulting in downtime. This straightforward approach is suitable for non-critical applications or when updates require significant changes incompatible with running pods.</p>
<p>To ensure zero downtime by gradually replacing old pods with new ones, the <code>type: RollingUpdate</code> suits us best.</p>
<ul>
<li><p>The <code>rollingUpdate</code> element allows adjusting the strategy more thoroughly.</p>
<ul>
<li><p><code>maxUnavailable: 1</code> allows only one pod to be unavailable during the update process.</p>
</li>
<li><p><code>maxSurge: 1</code> specifies that one additional pod can be created during the update, ensuring there’s always an extra pod available during the rollout.</p>
</li>
</ul>
</li>
</ul>
<p>The <code>template</code> describes the pod that will be created with this deployment. It specifies the container and the volume. This configuration is similar to the one used for creating the pod, with the only difference being that we use the API image and instead of mounting <code>hostPath</code>, we use <code>persistentVolumeClaim</code>.</p>
<blockquote>
<p>Note that <code>template.metadata</code> sets app label as <code>hello-kube-api</code> which matches the <code>matchLabels</code> selector.</p>
</blockquote>
<p>In Kubernetes, PersistentVolume (PV) and PersistentVolumeClaim (PVC) are essential for managing storage. A PersistentVolume is a piece of storage provisioned by an administrator or dynamically created using Storage Classes. It's independent of any individual pod, ensuring your data persists beyond the lifecycle of pods. On the other hand, a PersistentVolumeClaim is a request for storage by a user. When you create a PVC, Kubernetes finds a PV that matches the claim’s requirements, binding them together. This separation allows for dynamic and flexible storage management, ensuring your applications have the persistent storage they need.</p>
<p>The configurations for PV and PVC needed for our applications are below.</p>
<pre><code class="lang-plaintext">apiVersion: v1
kind: PersistentVolume
metadata:
  name: hello-pv
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: hello-pvc
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi
</code></pre>
<p>By defining these PV and PVC we create a persistent storage solution that all our Kubernetes pods can use, ensuring data is retained even if the pods are terminated or rescheduled.</p>
<p>We can apply deployment and storage configuration in any order, but we have to understand that our deployment cannot be created until the storage is provided. Thus I recommend provisioning the storage first and only after that apply deployment configuration.</p>
<pre><code class="lang-bash">kubectl apply -f storage.yml
kubectl apply -f api-deploy.yml
</code></pre>
<p>As usual, we can use <code>kubectl get</code> to check the status of our deployment.</p>
<pre><code class="lang-plaintext">&gt; kubectl get deploy

NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
hello-kube-api-deploy   2/2     2            2           10m
</code></pre>
<p>The interesting part is that we asked to create two replicas of our pods instead of one pod as it was with our background process. We can see more details using the <code>describe</code> command. If you use it, you can receive a more detailed response about the deployment, pod, volume, and events.</p>
<pre><code class="lang-plaintext">&gt; kubectl describe deployments hello-kube-api-deploy

Name:                   hello-kube-api-deploy
Namespace:              default
CreationTimestamp:      Sun, 23 Jun 2024 11:44:58 +0200
Labels:                 &lt;none&gt;
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=hello-kube-api
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Pod Template:
  Labels:  app=hello-kube-api
  Containers:
   hello-kube-api:
    Image:        hello-kube-api:1.0
    Port:         8080/TCP
    Host Port:    0/TCP
    Environment:  &lt;none&gt;
    Mounts:
      /configuration from data (rw)
  Volumes:
   data:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  hello-pvc
    ReadOnly:   false
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  &lt;none&gt;
NewReplicaSet:   hello-kube-api-deploy-b6686ccc6 (2/2 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  34s   deployment-controller  Scaled up replica set hello-kube-api-deploy-b6686ccc6 to 2
</code></pre>
<p>Right now we have two applications running in Kubernetes: the background process and the API.</p>
<pre><code class="lang-plaintext">NAME                                    READY   STATUS    RESTARTS      AGE
app-pod                                 1/1     Running   2 (62m ago)   33d
hello-kube-api-deploy-b6686ccc6-kxc9j   1/1     Running   0             59m
hello-kube-api-deploy-b6686ccc6-sc7lj   1/1     Running   0             59m
</code></pre>
<p>Because we created the replica set with two pods in it K8S needs to assign unique names for each pod. For that, it uses the following format:</p>
<p><code>[the name of deployment]-[unique identifier of deployment]-[unique identifier of pod]</code></p>
<h2 id="heading-load-balancing-and-service-configuration">Load Balancing and Service Configuration</h2>
<p>Our application works in Kubernetes, but we still haven't seen the results. Creating a frontend with a UI is outside the scope of this article, so we will try to call our API to see the result.</p>
<p>Kubernetes assigns a private cluster IP for each pod in a cluster so that pods can communicate. This private IP is not accessible from the outside world. Each pod has a unique name and IP, which we can use to communicate with them. However, relying on pod names and IPs is impractical because pods can be deleted and recreated with different names and IP addresses at any time. To solve this issue, Kubernetes uses an abstraction called Services.</p>
<p>Services are essential for enabling communication between different components of an application. A Service defines a logical set of pods and a policy to access them. Kubernetes offers different types of services:</p>
<ul>
<li><p>ClusterIP for internal communication within the cluster.</p>
</li>
<li><p>NodePort for exposing services on each node's IP at a static port.</p>
</li>
<li><p>LoadBalancer for exposing services externally using a cloud provider's load balancer.</p>
</li>
</ul>
<p>We want to access our pods from the external world, so we will use a LoadBalancer service.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Service</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube-lb-svc</span>
  <span class="hljs-attr">labels:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">hello-kube-api</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">type:</span> <span class="hljs-string">LoadBalancer</span>
  <span class="hljs-attr">ports:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">port:</span> <span class="hljs-number">8080</span>
    <span class="hljs-attr">protocol:</span> <span class="hljs-string">TCP</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">hello-kube-api</span>
</code></pre>
<p>This configuration creates a <strong>LoadBalancer</strong> service named <code>hello-kube-lb-svc</code> that listens on port <code>8080</code> and directs traffic to our API pods labeled <code>app: hello-kube-api</code>.</p>
<p>Apply the configuration with:</p>
<pre><code class="lang-bash">kubectl apply -f api-lb.yml
</code></pre>
<p>Check the status of the service:</p>
<pre><code class="lang-bash">kubectl get svc
</code></pre>
<p>And use <code>describe</code> to see more details</p>
<pre><code class="lang-bash">kubectl describe svc hello-kube-lb-svc
</code></pre>
<h2 id="heading-testing-the-applications">Testing the applications</h2>
<p>We are finally ready to test our applications. Start by checking the health endpoint by navigating to <code>http://localhost:8080/api/health</code> in your browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719141864378/164c0525-09ad-4ade-8f63-6b451e30bb24.png" alt class="image--center mx-auto" /></p>
<p>You should see a <code>200 OK</code> response with the text <code>hello-kube-api-deploy-[unique identifier]</code>, which matches the pod name. Refresh the page a few times, and you will notice different responses as the load balancer directs traffic to different pods.</p>
<p>If you delete a pod:</p>
<pre><code class="lang-bash">kubectl delete pod [pod-name]
</code></pre>
<p>Refresh the page again, you should still get a <code>200 OK</code> response, but from a different pod, indicating that Kubernetes has recreated the deleted pod and the service is working as expected.</p>
<p>Let's scale our application to have five replicas of the API. Modify the <code>spec.replicas</code> parameter in the deployment configuration and apply the changes:</p>
<pre><code class="lang-bash">kubectl apply -f api-deploy.yml
</code></pre>
<p>Verify the number of running pods:</p>
<pre><code class="lang-bash">kubectl get pods
</code></pre>
<p>You should see five pods running:</p>
<pre><code class="lang-plaintext">NAME                                    READY   STATUS    RESTARTS       AGE
app-pod                                 1/1     Running   0              33d
hello-kube-api-deploy-b6686ccc6-8kkql   1/1     Running   0              19s
hello-kube-api-deploy-b6686ccc6-8vmzs   1/1     Running   0              9m16s
hello-kube-api-deploy-b6686ccc6-hh9hd   1/1     Running   0              19s
hello-kube-api-deploy-b6686ccc6-kxc9j   1/1     Running   0              126m
hello-kube-api-deploy-b6686ccc6-prbmc   1/1     Running   0              19s
</code></pre>
<p>Finally, let's inspect the state endpoint to check the status of the background operation. This endpoint shows the result of the work done by two different pods, with the result persisting in the volume.</p>
<p>Navigate to <code>http://localhost:8080/api/state</code> in your browser. You should see a response like <code>1293</code>. Recheck it after a few minutes, and the number should increment, indicating the background process is working correctly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719142192804/e960749a-8031-4e80-a8f2-44157cd2afd5.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we build on our previous work containerizing a .NET 8 application by focusing on scaling and managing the application within Kubernetes. We introduce a new API service for monitoring the application's state and health, and we create a Kubernetes Deployment to ensure the application runs smoothly with zero downtime. Persistent storage is managed using PersistentVolumes (PV) and PersistentVolumeClaims (PVC), ensuring data persistence across pod restarts. Finally, we configure a LoadBalancer service to expose the API to external traffic, enabling us to test and verify the application's scalability and resilience.</p>
<h2 id="heading-links">Links</h2>
<p><a target="_blank" href="https://github.com/MasDenBy/blog-samples/tree/main/k8s-net8-part2">The source code</a></p>
<p><a target="_blank" href="http://localhost:8080/api/health">Deployments | Kub</a><a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">ernetes</a></p>
<p><a target="_blank" href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Persistent Volumes | Kubernetes</a></p>
<p><a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/">ReplicaSet | Kubernetes</a></p>
<p><a target="_blank" href="https://kubernetes.io/docs/concepts/services-networking/service/">Service | Kubernetes</a></p>
<p>Image credits: <a target="_blank" href="https://www.pexels.com/photo/cargo-container-lot-906494/">Cargo Container Lot</a> by <a target="_blank" href="https://www.pexels.com/@chanaka-318741/">Chanaka</a></p>
]]></content:encoded></item><item><title><![CDATA[Containerize and host .NET 8 application in Kubernetes]]></title><description><![CDATA[This article is a part of the series "Use Kubernetes to host .NET 8 applications": Containerize and Host .NET 8 applications in Kubernetes (this article)…]]></description><link>https://iharmaiseyeu.net/containerize-and-host-net-8-application-in-kubernetes</link><guid isPermaLink="true">https://iharmaiseyeu.net/containerize-and-host-net-8-application-in-kubernetes</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Docker]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Mon, 26 Feb 2024 08:00:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708897281448/5f014a76-2a99-477b-9d7d-ccbe5c76a99d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is a part of the series "Use Kubernetes to host .NET 8 applications":</p>
<ul>
<li><p>Containerize and Host .NET 8 applications in Kubernetes (this article)</p>
</li>
<li><p><a target="_blank" href="https://iharmaiseyeu.net/scaling-net-8-applications-in-kubernetes">Scaling .NET 8 Applications in Kubernetes</a></p>
</li>
<li><p>Hosting .NET 8 Applications in Azure Kubernetes Service (AKS)</p>
</li>
</ul>
<p>Have you ever felt the struggle of managing the ever-growing complexity of your applications? As our projects become increasingly interconnected, deploying and orchestrating them becomes a serious task.</p>
<p>That's where Kubernetes steps in. Think of it as your ultimate helper in the world of container orchestration. It takes care of deploying, scaling, and managing your applications.</p>
<p>As a .NET developer, I want to dive into using Kubernetes with .NET 8 in this series of articles, but in reality, it can be used with everything.</p>
<h2 id="heading-test-application">Test application</h2>
<p>Let's get started with our test application (<a target="_blank" href="https://github.com/MasDenBy/blog-samples/tree/main/k8s-net8-part1">the source code</a>). I want to make it simple but at the same time, it should be a good starting point to learn how to work with Kubernetes. For that purpose, I have created a console application that represents a simple background process. The source code of it below.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Hello, Kube!"</span>);
Console.WriteLine(<span class="hljs-string">"Starting background process"</span>);
Console.WriteLine(<span class="hljs-string">"Looking for a configuration in local file"</span>);

<span class="hljs-keyword">var</span> stepToRun = <span class="hljs-number">0</span>;

<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> configFileName = <span class="hljs-string">"step.config"</span>;

<span class="hljs-keyword">if</span>(File.Exists(configFileName))
{
    stepToRun = <span class="hljs-keyword">int</span>.Parse(File.ReadAllText(configFileName));
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{stepToRun}</span> steps were completed. Continue process."</span>);
    stepToRun++;
}
<span class="hljs-keyword">else</span>
{
    Console.WriteLine(<span class="hljs-string">"Configuration does not exists. Starting from 0 step"</span>);
}

<span class="hljs-keyword">while</span>(<span class="hljs-literal">true</span>)
{
    Console.WriteLine(<span class="hljs-string">$"Processing step: <span class="hljs-subst">{stepToRun}</span>"</span>);

    <span class="hljs-comment">// Do some work</span>
    Thread.Sleep(<span class="hljs-number">5000</span>);
    File.WriteAllText(configFileName, stepToRun.ToString());

    stepToRun++;
}
</code></pre>
<p>In a nutshell, this background process simulates processing and saves the progress in the local configuration file. If you run it for the first time, it starts processing from step 0.</p>
<pre><code class="lang-plaintext">Hello, Kube!
Starting background process
Looking for a configuration in local file
Configuration does not exists. Starting from 0 step
Processing step: 0
Processing step: 1
Processing step: 2
Processing step: 3
</code></pre>
<p>Rerunning the application will give a slightly different result.</p>
<pre><code class="lang-plaintext">Hello, Kube!
Starting background process
Looking for a configuration in local file
4 steps were completed. Continue process.
Processing step: 5
Processing step: 6
Processing step: 7
</code></pre>
<p>I know this is a somewhat silly application, but it will help us learn some important concepts in the future.</p>
<h2 id="heading-containerization-of-test-application">Containerization of test application</h2>
<p>We need to create a container image for our application. Docker is the de facto standard for working with containers, so I will use it for this purpose.</p>
<p>Please find below the content of the Dockerfile for the sample application.</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">FROM</span> mcr.microsoft.com/dotnet/runtime:<span class="hljs-number">8.0</span> AS base
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-keyword">FROM</span> mcr.microsoft.com/dotnet/sdk:<span class="hljs-number">8.0</span> AS build
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /src</span>
<span class="hljs-keyword">COPY</span><span class="bash"> *.csproj ./</span>
<span class="hljs-keyword">RUN</span><span class="bash"> dotnet restore</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>

<span class="hljs-keyword">FROM</span> build AS publish
<span class="hljs-keyword">RUN</span><span class="bash"> dotnet publish -c Release -o /app/publish</span>

<span class="hljs-keyword">FROM</span> base AS final
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=publish /app/publish .</span>
<span class="hljs-keyword">ENTRYPOINT</span><span class="bash"> [<span class="hljs-string">"dotnet"</span>, <span class="hljs-string">"HelloKube.dll"</span>]</span>
</code></pre>
<p>This Dockerfile builds a multi-stage Docker image for a .NET 8 application, optimizing for a smaller final image size by separating the build and runtime dependencies.</p>
<p>It starts with the official runtime image for .NET 8.0 <code>mcr.microsoft.com/dotnet/runtime:8.0</code>.</p>
<p>We use the SDK image <code>mcr.microsoft.com/dotnet/sdk:8.0</code> to restore Nuget packages and build and publish the application in the release configuration.</p>
<p>In the final stage, we only need to copy the published files of the application from the previous stage and set the entry point.</p>
<p>To build the image from our Dockerfile we need to use the following command.</p>
<pre><code class="lang-bash">docker build -t hello-kube:1.0 .
</code></pre>
<p>After completing the Docker build command, you should have the image <code>hello-kube</code> on your machine. It's time to move on to the Kubernetes part.</p>
<h2 id="heading-kubernetes-in-a-few-words">Kubernetes in a few words</h2>
<p>Before installing Kubernetes let's stop for a minute and talk about how it works with containers.</p>
<p>Kubernetes contains many different components, each with its own responsibility. For running our background process, we need to use the following:</p>
<ul>
<li><p>Pod</p>
</li>
<li><p>Nodes (Worker and Control Plane)</p>
</li>
<li><p>Cluster</p>
</li>
</ul>
<blockquote>
<p>In reality, there are many more of them, but this article does not intend to replace the official documentation or grow to the size of a book. Thus, I will briefly cover only the most important parts necessary for understanding the content of the article.</p>
</blockquote>
<p>A Pod is a place where your container or containers are running. You can think of it as an abstraction that helps Kubernetes to work with different types of applications. A Pod can run not only containers, but also virtual machines, WASM applications, and serverless functions. So, using such an abstraction allows Kubernetes not to care about the type of application it runs because it does not matter.</p>
<p>A worker node is a place where pods are run. It has a special runtime for that purpose. Besides that, the worker node load balances tasks and monitors pod status.</p>
<p>The Control Plane (in some resources you can see the name Master node as well) is a set of different services that rule worker nodes, and manage scaling, and deployment.</p>
<p>A cluster is a collection of nodes (machines) that work together to run containerized applications. It needs at least one control plane node for proper functioning.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708701913372/34c6357b-0f94-46e2-8094-5db6df22518c.jpeg" alt class="image--center mx-auto" /></p>
<p>This simple diagram shows how these components are tied together. As you can see, our cluster has 3 nodes: the control plane, worker node 1, and worker node 2. At the same time, worker nodes have running pods.</p>
<h2 id="heading-create-a-cluster-in-the-local-environment">Create a cluster in the local environment</h2>
<p>In this article, I'm going to use locally installed Kubernetes. Since I don't want to deal with a complex installation process, I will use Docker Desktop which is already installed on my machine.</p>
<ul>
<li><p>Download and install the latest version of <a target="_blank" href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> (if you don't have it).</p>
</li>
<li><p>After installing Docker Desktop, open it.</p>
</li>
<li><p>Navigate to "Settings" by clicking on the Docker icon in the system tray (taskbar on Windows, menu bar on macOS).</p>
</li>
<li><p>Go to the "Kubernetes" tab and check the box next to "Enable Kubernetes."</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708704687073/7d57ef7b-ecb7-4257-a119-16fbf5086c94.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Click the "Apply &amp; Restart" button to save the changes and restart the Docker Desktop.</p>
</li>
<li><p>After Docker Desktop is restarted, open a terminal or a command prompt and enter the following command to check if Kubernetes is running.</p>
</li>
</ul>
<pre><code class="lang-bash">kubectl version
</code></pre>
<p>You should have a response similar to this</p>
<pre><code class="lang-plaintext">Client Version: v1.29.1
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.28.2
</code></pre>
<p>By default, Docker Desktop creates a single node cluster with the name <code>docker-desktop</code>. It should be enough for our local development. Run the following command to verify that your cluster is running.</p>
<pre><code class="lang-bash">kubectl get nodes
</code></pre>
<pre><code class="lang-plaintext">NAME             STATUS   ROLES           AGE   VERSION
docker-desktop   Ready    control-plane   28d   v1.28.2
</code></pre>
<p>As you can see, I have a <code>control-plane</code> node with the name <code>docker-desktop</code> and it has the <code>ready</code> status, which means that we can start to work with our local cluster.</p>
<h2 id="heading-running-application-container-in-kubernetes">Running application container in Kubernetes</h2>
<p>As we already know, we need the pod to run our container. We can create it in different ways: through CLI or using YAML configuration files. It is beneficial to use the second approach due to its readability, and you can store such files in the repository with the application code.</p>
<p>Create a configuration file with the name <code>app-pod.yml</code> to create a pod. The content of the file is below.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Pod</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">app-pod</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">containers:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">hello-kube:1.0</span>
</code></pre>
<p>Let's go through it.</p>
<p><code>apiVersion</code> is the version of the Kubernetes API we would like to use.</p>
<p><code>kind</code> indicates the type of Kubernetes resource we would like to provision.</p>
<p><code>metadata.name</code> sets the name for our pod.</p>
<p><code>spec.containers</code> describes which container to use.</p>
<p>To run a pod, we need to execute the following command.</p>
<pre><code class="lang-bash">kubectl apply -f app-pod.yml
</code></pre>
<p>The message <code>pod/app-pod created</code> should appear if the operation is successful.</p>
<p>Before going further, let's check which status our nodes have.</p>
<pre><code class="lang-bash">kubectl get pods
</code></pre>
<p>You can see the pod with the name <code>app-pod</code> in the list.</p>
<pre><code class="lang-plaintext">NAME      READY   STATUS    RESTARTS         AGE
app-pod   1/1     Running   10 (2m35s ago)   8d
</code></pre>
<p>It is time to check if our background process works. To do so, run the following command.</p>
<pre><code class="lang-bash">kubectl logs app-pod
</code></pre>
<p>On my machine, I have the following response.</p>
<pre><code class="lang-plaintext">Hello, Kube!
Starting background process
Looking for a configuration in local file
Configuration does not exists. Starting from 0 step
Processing step: 0
Processing step: 1
Processing step: 2
Processing step: 3
Processing step: 4
Processing step: 5
</code></pre>
<p>If you have the same, then congratulations, you have run your .NET 8 application in Kubernetes!</p>
<p>Let's pretend that we need to fix some important bug in our application or add a new functionality. We change the codebase and move the new version of the application into production.</p>
<p>I changed the first line in our application to the following to simulate some changes.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Hello, Kube! v.1.1"</span>);
</code></pre>
<p>We need to build a new version.</p>
<pre><code class="lang-bash">docker build -t hello-kube:1.1 .
</code></pre>
<p>Don't forget to change the version of the image in <code>app-pod.yml</code> file from <code>hello-kube:1.0</code> to <code>hello-kube:1.1</code>.</p>
<p>We need to redeploy our pod.</p>
<pre><code class="lang-bash">kubectl apply -f app-pod.yml
</code></pre>
<p>Checking the logs, we see.</p>
<pre><code class="lang-plaintext">Hello, Kube! v.1.1
Starting background process
Looking for a configuration in local file
Configuration does not exists. Starting from 0 step
Processing step: 0
Processing step: 1
Processing step: 2
</code></pre>
<p>The new version of our application runs (you can see it in the first line), but it looks like we started the process from the beginning. It does not sound correct because as you remember we save the progress in the configuration file.</p>
<p>We have such behavior because a pod is an unchanged object in its nature. So, when we update the pod, we don't perform an update but delete the current pod and create a new one. So, when we released the new version of our application, the old configuration file with the progress was deleted with the old pod.</p>
<h2 id="heading-working-with-storages">Working with storages</h2>
<p>Right now with our background process, we have an issue that the progress of work is not saved when our application is updated. So we need to find out the most appropriate way to save the progress. Due to we run it on one host, we can use <a target="_blank" href="https://kubernetes.io/docs/concepts/storage/volumes/#hostpath">hostPath</a> volume for our purpose.</p>
<p>In simple words, <code>hostPath</code> mounts a file or a directory from the host filesystem to the pod. So that when we use this directory or file from our pod it is persisted on our host.</p>
<p>To add the support of a volume, we need to make changes to our <code>app-pod.yml</code>. Please review the new lines added.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Pod</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">app-pod</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">containers:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">hello-kube</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">hello-kube:1.2</span>
    <span class="hljs-attr">volumeMounts:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">mountPath:</span> <span class="hljs-string">/configuration</span>
      <span class="hljs-attr">name:</span> <span class="hljs-string">configuration-volume</span>
  <span class="hljs-attr">volumes:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">configuration-volume</span>
    <span class="hljs-attr">hostPath:</span>
      <span class="hljs-attr">path:</span> <span class="hljs-string">/run/desktop/mnt/host/hello-kube-vol</span>
      <span class="hljs-attr">type:</span> <span class="hljs-string">DirectoryOrCreate</span>
</code></pre>
<p>We start reviewing the changes in the file from the bottom. The new element <code>spec.volumes</code> describes which volumes can be used in the pod.</p>
<p>Our <code>hostPath</code> volume has the name <code>configuration-volume</code> with the path <code>/run/desktop/mnt/host/hello-kube-vol</code>.</p>
<p>After defining the volume, we need to mount this volume into the container. For that purpose, we use the element <code>spec.containers.volumeMounts</code> and as parameters, we specify the name of the volume (should match with the name in <a target="_blank" href="http://volumes.name"><code>volumes.name</code></a>) and the path within the container where the volume should be mounted. In this case, it's <code>/configuration</code>.</p>
<p>It is time to change our application code to store the configuration file in the folder <code>/configuration</code>.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Hello, Kube! v.1.2"</span>);

<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> configFileName = <span class="hljs-string">"/configuration/step.config"</span>;

<span class="hljs-comment">// Others lines are unchanged</span>
</code></pre>
<p>Don't forget to build a new container and deploy a new pod file.</p>
<pre><code class="lang-plaintext">Hello, Kube! v.1.2
Starting background process
Looking for a configuration in local file
Configuration does not exists. Starting from 0 step
Processing step: 0
Processing step: 1
Processing step: 2
</code></pre>
<p>As expected the application started with a 0 step.</p>
<p>I won't release the new version of the application to check if our configuration file is stored in a volume. For that purpose, I delete the pod and recreate it again.</p>
<pre><code class="lang-bash">kubectl delete pod app-pod
kubectl apply -f app-pod.yml
kubectl logs app-pod
</code></pre>
<p>The response that I have is the following</p>
<pre><code class="lang-plaintext">Hello, Kube! v.1.2
Starting background process
Looking for a configuration in local file
12 steps were completed. Continue process.
Processing step: 13
</code></pre>
<p>Our background process finally saves the progress. So, we can not be afraid to restart or recreate our pod.</p>
<p>Kubernetes has a big list of supported <a target="_blank" href="https://kubernetes.io/docs/concepts/storage/">storages</a>. I don't think you will need all of them for your applications, but checking which support is useful.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we explored using Kubernetes to host .NET 8 applications. We containerized a simple console application, introduced key Kubernetes components, and set up a local cluster using Docker Desktop. By deploying our application in a Kubernetes pod and addressing state persistence challenges with volumes, we gained practical insights into Kubernetes usage.</p>
<p>In the next article, we are going to learn how to deploy and scale applications.</p>
<h2 id="heading-links">Links</h2>
<p><a target="_blank" href="https://github.com/MasDenBy/blog-samples/tree/main/k8s-net8-part1">The source code</a></p>
<p><a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/pods/">Pods | Kubernetes</a></p>
<p><a target="_blank" href="https://kubernetes.io/docs/concepts/storage/volumes/">Volumes | Kubernetes</a></p>
<p><a target="_blank" href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a></p>
<p>Image credits: <a target="_blank" href="https://www.pexels.com/photo/blue-white-orange-and-brown-container-van-163726/">Blue White Orange and Brown Container Van</a> by <a target="_blank" href="https://www.pexels.com/@pixabay/">Pixabay</a></p>
]]></content:encoded></item><item><title><![CDATA[Host Azure Function on Linux consumption plan]]></title><description><![CDATA[The dynamic consumption plan allows you to pay only for the resources you use when your function is running. Thus, if there are no incoming requests and a…]]></description><link>https://iharmaiseyeu.net/host-azure-function-on-linux-consumption-plan</link><guid isPermaLink="true">https://iharmaiseyeu.net/host-azure-function-on-linux-consumption-plan</guid><category><![CDATA[Azure Functions]]></category><category><![CDATA[Bicep]]></category><category><![CDATA[azure-storage]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Mon, 04 Dec 2023 08:00:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701616362530/67bd03dc-4923-4d3c-a618-986679af7f0a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The dynamic consumption plan allows you to pay only for the resources you use when your function is running. Thus, if there are no incoming requests and a function does nothing, you don't pay for it.</p>
<p>I will use Bicep to provision all necessary resources, but it is also possible to work with the Azure portal for that purpose.</p>
<p>What we need to start with is to create the storage account. Azure Function requires to have one to store configuration files and we are going to utilize it to store the code of our function.</p>
<p>The following code creates a storage account and the <code>release</code> container.</p>
<pre><code class="lang-plaintext">param appName string
param location string

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: '${appName}storage'
  location: location
  kind: 'StorageV2'
  sku: {
    name: 'Standard_ZRS'
  }
  properties: {
    accessTier: 'Hot'
    minimumTlsVersion: 'TLS1_2'
  }
}

resource blobServices 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {
  name: 'default'
  parent: storageAccount
}

resource releasesContainer 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {
  name: 'releases'
  parent: blobServices
  properties: {
    publicAccess: 'None'
  }
}
</code></pre>
<p>Microsoft suggests using managed identity over connection strings. Therefore, our function will not have any shared keys to access the storage account. Instead, we create a user-assigned managed identity and grant it Blob Data Owner permissions. An identity with such a role has full access to the storage blob container and data required for the normal operation of a function.</p>
<pre><code class="lang-plaintext">var storageBlobDataOwnerRoleId = 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b'

resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2021-09-30-preview' = {
  name: appName
  location: location
}

resource functionAppStorageBlodDataOwnerUserAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(storageAccount.id, storageBlobDataOwnerRoleId, identity.id)
  scope: storageAccount
  properties: {
    roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', storageBlobDataOwnerRoleId)
    principalId: identity.properties.principalId
    principalType: 'ServicePrincipal'
  }
}
</code></pre>
<p>The last resource we must provision before creating the function is a server farm with a dynamic plan.</p>
<pre><code class="lang-plaintext">resource hostingPlan 'Microsoft.Web/serverfarms@2022-09-01' = {
  name: appName
  location: location
  sku: {
    name: 'Y1' 
    tier: 'Dynamic'
  }
  properties:{
    reserved: true
  }
}
</code></pre>
<p>At this point, all our preparations are done, and we can proceed to create our function.</p>
<pre><code class="lang-plaintext">param packageName string

resource functionApp 'Microsoft.Web/sites@2022-09-01' = {
  name: '${appName}-func'
  location: location
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${identity.id}' : { }
    }
  }
  kind: 'functionapp,linux'
  properties: {
    reserved: true
    enabled: true
    serverFarmId: hostingPlan.id
    siteConfig: {
      appSettings: [
        {
          name: 'FUNCTIONS_EXTENSION_VERSION'
          value: '~4'
        }
        {
          name: 'FUNCTIONS_WORKER_RUNTIME'
          value: 'dotnet'
        }
        {
          name: 'WEBSITE_RUN_FROM_PACKAGE'
          value: '${storageAccount.properties.primaryEndpoints.blob}releases/${packageName}'
        }
        {
          name: 'WEBSITE_RUN_FROM_PACKAGE_BLOB_MI_RESOURCE_ID'
          value: identity.id
        }
        {
          name: 'AzureWebJobsStorage__accountName'
          value: storageAccount.name
        }
        {
          name: 'AzureWebJobsStorage__credential'
          value: 'managedIdentity'
        }
        {
          name: 'AzureWebJobsStorage__clientId'
          value: identity.properties.clientId
        }
      ]
    }
  }
}
</code></pre>
<p>The <code>functionApp</code> resource is provisioning the function with the user-assigned managed identity we created earlier. The <code>kind</code> element is set to <code>functionapp,linux</code>, indicating that we would like to use the Linux function.</p>
<p>The most interesting part here is the <code>appSettings</code> block. Let's delve into it.</p>
<p><code>FUNCTIONS_EXTENSION_VERSION</code> and <code>FUNCTIONS_WORKER_RUNTIME</code> are settings that define the function's version and runtime. I'm using the 4th version of the Azure function, which, at the time of writing, is the latest and recommended version. Regarding the runtime, it can be not only <code>dotnet</code> but also <code>node</code>, <code>java</code>, etc.</p>
<p><code>WEBSITE_RUN_FROM_PACKAGE</code> specifies the path to the zip file containing the release of a function. As you can see, it points to the storage account and the container we created earlier. The parameter <code>packageName</code> determines the name of the zip file.</p>
<p><code>WEBSITE_RUN_FROM_PACKAGE_BLOB_MI_RESOURCE_ID</code> needs to be set if we use a managed identity for accessing the storage account. Otherwise, it can be omitted.</p>
<p>The <code>AzureWebJobsStorage</code> settings specify the function storage account and identity required to access it.</p>
<p>The complete <a target="_blank" href="https://github.com/MasDenBy/blog-samples/blob/main/az-function-linux-consumption/deploy.bicep">Bicep file</a> can be found on GitHub.</p>
<h2 id="heading-links">Links</h2>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/azure-functions/consumption-plan">Azure Functions Consumption plan hosting</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#storage-blob-data-owner">Storage Blob Data Owner role</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/azure-functions/storage-considerations?tabs=azure-cli">Storage considerations for Azure Functions</a></p>
<p>Image credits: <a target="_blank" href="https://www.instagram.com/jane__ml/">Jane__ml</a></p>
]]></content:encoded></item><item><title><![CDATA[How to prevent multiple simultaneous deployments in Azure DevOps]]></title><description><![CDATA[CI/CD has completely transformed the way we work today. Instead of releasing the software once a month or somewhere in the future, we now release it…]]></description><link>https://iharmaiseyeu.net/how-to-prevent-multiple-simultaneous-deployments-in-azure-devops</link><guid isPermaLink="true">https://iharmaiseyeu.net/how-to-prevent-multiple-simultaneous-deployments-in-azure-devops</guid><category><![CDATA[#AzureDevOps]]></category><category><![CDATA[ci-cd]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Mon, 30 Oct 2023 09:14:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698656779699/a022e788-152e-4f97-b3b8-7bf4d2b7ad1b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>CI/CD has completely transformed the way we work today. Instead of releasing the software once a month or somewhere in the future, we now release it multiple times a day. In our environment, each merge to the main branch triggers a deployment to production. Consequently, if we approve and merge several PRs simultaneously, we may encounter a race condition when two or more deployments attempt to deploy to the same environment.</p>
<p>The solution to this problem is an <a target="_blank" href="https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals?view=azure-devops&amp;preserve-view=true&amp;tabs=check-pass#exclusive-lock">Exclusive lock</a>, which allows only one pipeline to proceed at a time. When multiple runs attempt to deploy, they may either wait (using a <code>sequential</code> lock) or be canceled, with only the latest one acquiring a lock (using a <code>runLatest</code>).</p>
<p>Now, let's examine the code snippet below:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">trigger:</span>
  <span class="hljs-attr">branches:</span>
    <span class="hljs-attr">include:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>

<span class="hljs-attr">pool:</span>
  <span class="hljs-attr">vmImage:</span> <span class="hljs-string">ubuntu-latest</span>

<span class="hljs-attr">lockBehavior:</span> <span class="hljs-string">runLatest</span>

<span class="hljs-attr">stages:</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">stage:</span> <span class="hljs-string">'deployment'</span>
  <span class="hljs-attr">jobs:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">deployment:</span> <span class="hljs-string">'deployment'</span>
    <span class="hljs-attr">environment:</span> <span class="hljs-string">production</span>
    <span class="hljs-attr">strategy:</span>
      <span class="hljs-attr">runOnce:</span>
        <span class="hljs-attr">deploy:</span>
          <span class="hljs-attr">steps:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-attr">script:</span> <span class="hljs-string">sleep</span> <span class="hljs-number">30</span>
</code></pre>
<p>The setting <code>lockBehavior: runLatest</code> indicates that we want to run only the latest deployment, canceling any other concurrent deployments. <code>sequential</code> is another possible lock behavior that allows all runs to deploy in a line.</p>
<p><code>environment: production</code> specifies the environment to which we intend to deploy. It is crucial to define this parameter, as environments are considered protected resources in Azure DevOps, and we can apply an <code>Exclusive Lock</code> to them.</p>
<p>If you run the pipeline created from this YAML file multiple times, you probably won't notice any difference, as all deployments will run concurrently. To rectify this, we need to set an exclusive lock on our production environment. To do so:</p>
<ul>
<li><p>Navigate to <code>Environments</code>-&gt;<code>production</code>-&gt;<code>'Approvals and checks'</code> tab</p>
</li>
<li><p>Click <code>Add check(+)</code> button</p>
</li>
<li><p>Select <code>Exclusive lock</code></p>
</li>
<li><p>Click <code>Next</code> button</p>
</li>
<li><p>Click <code>Create</code> button</p>
</li>
</ul>
<p>Now the lock will take effect, and after running the pipeline multiple times, you will most likely observe that only the latest deployment is executed. If you need to deploy all runs concurrently, simply change <code>lockBehavior</code> to <code>sequential</code>.</p>
<p>Image credits: "<a target="_blank" href="https://www.pexels.com/photo/photo-of-train-on-train-tracks-3617450/">Photo of Train on Train Tracks</a>" by <a target="_blank" href="https://www.pexels.com/@benjaminjsuter/"><strong>Benjamin Suter</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Use Testcontainers for running Azurite in Azure DevOps pipeline]]></title><description><![CDATA[In our solutions, we use storage accounts quite often. They are easy and inexpensive, and for many situations, they are sufficient, eliminating the need to…]]></description><link>https://iharmaiseyeu.net/use-testcontainers-for-running-azurite-in-azure-devops-pipeline</link><guid isPermaLink="true">https://iharmaiseyeu.net/use-testcontainers-for-running-azurite-in-azure-devops-pipeline</guid><category><![CDATA[Docker]]></category><category><![CDATA[Azure]]></category><category><![CDATA[#AzureDevOps]]></category><category><![CDATA[azurite]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Wed, 04 Oct 2023 06:55:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696259835273/ed58c928-660b-4d6d-970f-694708396e49.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In our solutions, we use storage accounts quite often. They are easy and inexpensive, and for many situations, they are sufficient, eliminating the need to pay for expensive alternatives.</p>
<p>Azurite is a storage emulator of storage accounts for local development, allowing you to work with blobs, queues, and tables on your machine without incurring any costs. When necessary, you can simply switch to using an Azure Storage account in the cloud. It's as easy as a piece of cake, right?</p>
<p>For local development, it certainly is. But what if we need to write integration tests that require communication with a storage account? I see a few possible solutions to achieve that.</p>
<h3 id="heading-use-real-instances-of-azure-storage-account"><strong>Use real instances of Azure storage account</strong></h3>
<p>At first glance, this seems like a good idea. After all, we are already using an Azure storage account, so why not leverage it for testing purposes? Indeed, we can, but if multiple developers share a single instance, they may inadvertently interfere with each other. Therefore, each developer should utilize their dedicated storage account. However, this approach is not without its drawbacks.</p>
<p>Firstly, we require a minimum of two storage accounts—one for development and another for testing.</p>
<p>Secondly, it's essential to ensure that the storage account is empty before executing tests, necessitating regular cleanup.</p>
<p>Thirdly, if you happen to be working in an environment with an unreliable internet connection, running tests can become problematic.</p>
<p>Fourthly, in the context of a CI pipeline, providing access to multiple storage accounts may not be feasible. While it's possible to create a single account for testing, it still requires cleanup after tests and careful coordination to ensure that only one pipeline runs at a time. This can be cumbersome for larger teams where multiple developers need to run tests frequently.</p>
<h3 id="heading-utilizing-the-locally-installed-version-of-azurite"><strong>Utilizing the Locally Installed Version of Azurite</strong></h3>
<p>Azurite is an emulator of a storage account that can be installed on a local environment. While this approach addresses some issues related to an unstable internet connection, it is not without its challenges.</p>
<p>Azurite is well-suited for local development, and I strongly encourage its use for that purpose. However, when it comes to running tests, we encounter the same challenge of needing a separate, clean testing environment.</p>
<h3 id="heading-leveraging-testcontainers"><strong>Leveraging Testcontainers</strong></h3>
<p><a target="_blank" href="https://testcontainers.com/">Testcontainers</a> a powerful and versatile library that simplifies the process of containerized testing. It allows you to spin up Docker containers for databases, message brokers, and other dependencies your application relies on. It offers a set of packages designed to streamline the provisioning of resources for testing.</p>
<p>In simple terms, it operates as follows: when we require a service, an instance of it is provisioned within a Docker container. We can then interact with it just like a regular instance. Once the work is complete (i.e., all tests have been executed), the container is automatically destroyed.</p>
<p>With Testcontainers, each container instance is created as a pristine environment, eliminating the need for manual cleanup. Since it operates on a local machine, each developer can be confident that their tests run in a completely isolated environment.</p>
<p>Internet connectivity is only necessary during the initial setup when Docker may need to download images if they are not already present in the local environment.</p>
<p>As the name suggests, Testcontainers is primarily intended for use in testing. Of course, no one can stop you from using them for development tasks as well.</p>
<h2 id="heading-sample-application">Sample application</h2>
<p>To present how to use Testcontainers I have written a minimal API with one endpoint that downloads a file from an Azure blob and displays it to the user. The source code is below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Azure.Storage.Blobs;

<span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton(x =&gt;
{
    <span class="hljs-keyword">var</span> connectionString = <span class="hljs-string">"&lt;your-connection-string&gt;"</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> BlobServiceClient(connectionString);
});

<span class="hljs-keyword">var</span> app = builder.Build();

app.MapGet(<span class="hljs-string">"/api/file"</span>, <span class="hljs-keyword">async</span> (BlobServiceClient blobServiceClient) =&gt;
{
    <span class="hljs-keyword">var</span> containerClient = blobServiceClient.GetBlobContainerClient(<span class="hljs-string">"data"</span>);
    <span class="hljs-keyword">var</span> blobClient = containerClient.GetBlobClient(<span class="hljs-string">"file.txt"</span>);

    <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> blobClient.DownloadContentAsync();
    <span class="hljs-keyword">return</span> Results.Text(response.Value.Content);
});

app.Run();
</code></pre>
<p>Since I don't have Azurite installed on my machine, I use a Docker image with the following command:</p>
<pre><code class="lang-bash">docker run -p 10000:10000 mcr.microsoft.com/azure-storage/azurite azurite-blob --blobHost 0.0.0.0
</code></pre>
<p>Once the emulator is completely initialized, I create the container with the name <code>data</code> and upload a file named <code>file.txt</code> with the content <code>Content of the file</code>.</p>
<p>Running the API and executing the endpoint should return the text <code>Content of the file</code>. We can run it locally to verify that everything is working, and indeed, it does. However, we would like to have a more reliable and faster mechanism to validate this functionality. Therefore, let's add an integration test for it.</p>
<h2 id="heading-adding-integration-tests">Adding integration tests</h2>
<p>Well-written tests should be as isolated as possible. For our endpoint, we cannot use the same storage account as for development or production environments. Thus, we can highlight that our test should be able to:</p>
<ul>
<li><p>Create a storage account and a container.</p>
</li>
<li><p>Upload a file into the container.</p>
</li>
<li><p>Delete the storage account.</p>
</li>
</ul>
<p>To address the first and last points, we will use Testcontainers.</p>
<p>What we need first is to add the <code>Testcontainers.Azurite</code> package to our test project. Many packages are available for different services, and the full list can be observed through <a target="_blank" href="https://testcontainers.com/modules/"><strong>this link</strong></a>.</p>
<pre><code class="lang-bash">dotnet add package Testcontainers.Azurite
</code></pre>
<p>In our test we upload the file with some text content, call the endpoint to return the content of the uploaded file, and validate that it is the same.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ProgramTests</span> : <span class="hljs-title">IClassFixture</span>&lt;<span class="hljs-title">ApiWebApplicationFactory</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> HttpClient httpClient;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> BlobHelper blobHelper;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ProgramTests</span>(<span class="hljs-params">ApiWebApplicationFactory factory</span>)</span>
    {
        <span class="hljs-keyword">this</span>.httpClient = factory.CreateClient();
        <span class="hljs-keyword">this</span>.blobHelper = <span class="hljs-keyword">new</span> BlobHelper(factory.Services);
    }

    [<span class="hljs-meta">Fact</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Get_ShouldResponseWithTextFileContent</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">// Arrange</span>
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> content = <span class="hljs-string">"The content of the file for test"</span>;
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">this</span>.blobHelper.UploadTextFileAsync(<span class="hljs-string">"file.txt"</span>, content);

        <span class="hljs-comment">// Act</span>
        <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> <span class="hljs-keyword">this</span>.httpClient.GetAsync(<span class="hljs-string">"/api/file"</span>);
        response.EnsureSuccessStatusCode();

        <span class="hljs-keyword">var</span> actualContent = <span class="hljs-keyword">await</span> response.Content.ReadAsStringAsync();

        <span class="hljs-comment">// Assert</span>
        Assert.Equal(content, actualContent);
    }
}
</code></pre>
<p><code>BlobHelper</code> is a helper class for uploading the file. The content of it is available in the source code.</p>
<p><code>ApiWebApplicationFactory</code> is our custom implementation of <code>WebApplicationFactory</code> to configure our integration tests.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ApiWebApplicationFactory</span> : <span class="hljs-title">WebApplicationFactory</span>&lt;<span class="hljs-title">Program</span>&gt;, <span class="hljs-title">IAsyncLifetime</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> AzuriteTestContainer azuriteTestContainer;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ApiWebApplicationFactory</span>(<span class="hljs-params"></span>)</span>
    {
         <span class="hljs-keyword">this</span>.azuriteTestContainer = <span class="hljs-keyword">new</span> AzuriteTestContainer();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">InitializeAsync</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">this</span>.azuriteTestContainer.StartAsync();
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ConfigureWebHost</span>(<span class="hljs-params">IWebHostBuilder builder</span>)</span>
    {
        builder.ConfigureServices(services =&gt;
        {
            services.AddSingleton(<span class="hljs-keyword">new</span> BlobServiceClient(azuriteTestContainer.ConnectionString));
        });
    }

    <span class="hljs-keyword">async</span> Task IAsyncLifetime.DisposeAsync()
    {
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">this</span>.azuriteTestContainer.DisposeAsync();
    }
}
</code></pre>
<p>Here, we create <code>AzuriteTestContainer</code> (see the source code of this object below) and perform the essential parts: start the container and dispose of it.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Testcontainers.Azurite;

<span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AzuriteTestContainer</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> AzuriteContainer container;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AzuriteTestContainer</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">this</span>.container = <span class="hljs-keyword">new</span> AzuriteBuilder()
            .WithImage(<span class="hljs-string">"mcr.microsoft.com/azure-storage/azurite:latest"</span>)
            .Build();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ConnectionString =&gt; <span class="hljs-keyword">this</span>.container.GetConnectionString();

    <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">StartAsync</span>(<span class="hljs-params"></span>)</span> =&gt; <span class="hljs-keyword">this</span>.container.StartAsync();
    <span class="hljs-function"><span class="hljs-keyword">public</span> ValueTask <span class="hljs-title">DisposeAsync</span>(<span class="hljs-params"></span>)</span> =&gt; <span class="hljs-keyword">this</span>.container.DisposeAsync();
}
</code></pre>
<p>The <code>AzuriteTestContainer</code> class serves as a wrapper around <code>AzuriteContainer</code> and <code>AzuriteBuilder</code> from the <code>Testcontainers.Azurite</code> package. This object is responsible for creating a Docker container with the specified image and disposing of it.</p>
<p>Running our test will automatically provision Azurite in a Docker container.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695928450643/dc8035ef-bc0f-49f0-8268-cfcc8bc66ca6.png" alt class="image--center mx-auto" /></p>
<p>In addition to the container, we expect to see another one named <code>testcontainers/ryuk</code>, which serves as a helper for cleaning all resources (containers, networks, volumes) created during the test run.</p>
<p>The <code>mcr.microsoft.com/azure-storage/azurite</code> image represents the Azurite container. It's important to note that the ports may differ, so if you run some tests in parallel and several Azurite containers are created, each will have its ports. Therefore, you don't need to write any lines of code for that.</p>
<p>In our Azure DevOps pipeline, we can add a task to run tests like that.</p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">DotNetCoreCLI@2</span>
  <span class="hljs-attr">displayName:</span> <span class="hljs-string">test</span>
  <span class="hljs-attr">inputs:</span>
    <span class="hljs-attr">command:</span> <span class="hljs-string">test</span>
    <span class="hljs-attr">projects:</span> <span class="hljs-string">$(solution)</span>
    <span class="hljs-attr">arguments:</span> <span class="hljs-string">--configuration</span> <span class="hljs-string">Release</span> <span class="hljs-string">--logger</span> <span class="hljs-string">trx</span> <span class="hljs-string">--collect:"XPlat</span> <span class="hljs-string">Code</span> <span class="hljs-string">Coverage"</span>
</code></pre>
<p>At this point, our integration test will pass in the pipeline. Examining the console input, we can see that the Docker container was automatically provisioned and de-provisioned automatically. Cool, isn't it?</p>
<pre><code class="lang-plaintext">...
[testcontainers.org 00:00:01.64] Docker image testcontainers/ryuk:0.5.1 created
[testcontainers.org 00:00:01.71] Docker container 0d6de9a94a02 created
[testcontainers.org 00:00:01.77] Start Docker container 0d6de9a94a02
[testcontainers.org 00:00:03.13] Wait for Docker container 0d6de9a94a02 to complete readiness checks
[testcontainers.org 00:00:03.13] Docker container 0d6de9a94a02 ready
[testcontainers.org 00:00:03.15] Docker registry credential mcr.microsoft.com not found
[testcontainers.org 00:00:08.30] Docker image mcr.microsoft.com/azure-storage/azurite:latest created
[testcontainers.org 00:00:08.33] Docker container 21715eda45f1 created
[testcontainers.org 00:00:08.33] Start Docker container 21715eda45f1
[testcontainers.org 00:00:08.66] Wait for Docker container 21715eda45f1 to complete readiness checks
[testcontainers.org 00:00:08.66] Docker container 21715eda45f1 ready
[testcontainers.org 00:00:15.35] Delete Docker container 21715eda45f1
Results File: /home/vsts/work/_temp/_fv-az429-553_2023-10-01_10_54_49.trx

Passed!  - Failed:     0, Passed:     1, Skipped:     0, Total:     1, Duration: &lt; 1 ms - AzuriteTestContainers.IntegrationTests.dll (net7.0)
...
</code></pre>
<h2 id="heading-move-to-managed-identity">Move to managed identity</h2>
<p>Currently, we are using a connection string to establish a connection with the Azure storage account. However, this is not the best approach, and Microsoft recommends using Managed Identity instead. Let's update our code to align with this approach.</p>
<p>We need to remove the connection string and use blob URI and <code>DefaultAzureCredential</code> instead. Thus instantiation of <code>BlobServiceClient</code> should look like this.</p>
<pre><code class="lang-csharp">builder.Services.AddSingleton(x =&gt;
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> BlobServiceClient(<span class="hljs-keyword">new</span> Uri(<span class="hljs-string">"http://127.0.0.1:10000/devstoreaccount1"</span>), <span class="hljs-keyword">new</span> DefaultAzureCredential());
});
</code></pre>
<p>When running the application, you might encounter the following error: <code>System.ArgumentException: Cannot use TokenCredential without HTTPS</code>.</p>
<p>Managed identity cannot be used when the service is accessible via HTTP as Azurite runs by default, so we need to address this issue. The <a target="_blank" href="https://github.com/Azure/Azurite#https-setup"><strong>Azurite GitHub page</strong></a> provides information on how to enable HTTPS by providing a certificate.</p>
<p>To generate the certificate, we'll use the utility <a target="_blank" href="https://github.com/FiloSottile/mkcert"><strong>mkcert</strong></a>, which allows us to quickly create development certificates with just a few commands:</p>
<pre><code class="lang-bash">mkcert -install
mkcert 127.0.0.1
</code></pre>
<p>The first command creates a local Certificate Authority (CA) and installs it in the system's trust store. The second command generates our development certificate for the local system.</p>
<p>Now, we can run our Docker container using the following command:</p>
<pre><code class="lang-bash">docker run -p 10000:10000 -v c:/certs/:/workspace  mcr.microsoft.com/azure-storage/azurite azurite --blobHost 0.0.0.0 --cert /workspace/127.0.0.1.pem --key /workspace/127.0.0.1-key.pem --oauth basic
</code></pre>
<p>A crucial step here is to map (<code>-v c:/certs/:/workspace</code>) the folder containing the certificates to Docker.</p>
<p>With this setup, we are ready to change the blob URL from <code>http://127.0.0.1:10000/devstoreaccount1</code> to <code>https://127.0.0.1:10000/devstoreaccount1</code>.</p>
<p>After migrating our app to use managed identity, we should do the same with our tests. While it's possible to keep tests running with a connection string, it's not ideal for ensuring 100% confidence in our unit tests. To achieve this, we need to be as closely aligned with our application code as possible.</p>
<p>To enable Azurite to run over HTTPS, we need to use certificates. Since we've already generated development certificates, we just need to make them accessible for tests. To do this, create a folder named <code>certs</code> in the test project and copy the certificate files into it.</p>
<p>Next, modify the <code>AzuriteTestContainer</code> class to work with certificates and return the correct URLs of services instead of the connection string. Below is the source code for this class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AzuriteTestContainer</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> Regex BlobUriRegex = <span class="hljs-keyword">new</span>(<span class="hljs-string">@"BlobEndpoint=([A-Za-z0-9:\\.\/]*)"</span>, RegexOptions.Compiled);

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> AzuriteContainer container;
    <span class="hljs-keyword">private</span> Uri blobUri = <span class="hljs-literal">null</span>!;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AzuriteTestContainer</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">this</span>.container = <span class="hljs-keyword">new</span> AzuriteBuilder()
            .WithImage(<span class="hljs-string">"mcr.microsoft.com/azure-storage/azurite:latest"</span>)
            .WithResourceMapping(<span class="hljs-keyword">new</span> DirectoryInfo(<span class="hljs-string">"./certs"</span>), <span class="hljs-string">"/workspace/"</span>)
            .WithCommand(<span class="hljs-string">"--cert"</span>, <span class="hljs-string">"/workspace/127.0.0.1.pem"</span>, <span class="hljs-string">"--key"</span>, <span class="hljs-string">"/workspace/127.0.0.1-key.pem"</span>, <span class="hljs-string">"--oauth"</span>, <span class="hljs-string">"basic"</span>)
            .Build();
    }

    <span class="hljs-keyword">public</span> Uri BlobUri =&gt; <span class="hljs-keyword">this</span>.blobUri ??= <span class="hljs-keyword">this</span>.GetServiceUri(BlobUriRegex);

    <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">StartAsync</span>(<span class="hljs-params"></span>)</span> =&gt; <span class="hljs-keyword">this</span>.container.StartAsync();
    <span class="hljs-function"><span class="hljs-keyword">public</span> ValueTask <span class="hljs-title">DisposeAsync</span>(<span class="hljs-params"></span>)</span> =&gt; <span class="hljs-keyword">this</span>.container.DisposeAsync();

    <span class="hljs-function"><span class="hljs-keyword">private</span> Uri <span class="hljs-title">GetServiceUri</span>(<span class="hljs-params">Regex regex</span>)</span>
    {
        <span class="hljs-keyword">var</span> connectionString = <span class="hljs-keyword">this</span>.container.GetConnectionString();

        <span class="hljs-keyword">var</span> matchResult = regex.Match(connectionString);

        <span class="hljs-keyword">var</span> uri = matchResult.Success 
            ? <span class="hljs-keyword">new</span> Uri(matchResult.Groups[<span class="hljs-number">1</span>].Value)
            : <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"Cannot retrieve uri from connection string"</span>);

        <span class="hljs-keyword">var</span> uriBuilder = <span class="hljs-keyword">new</span> UriBuilder(uri)
        {
            Scheme = Uri.UriSchemeHttps
        };

        <span class="hljs-keyword">return</span> uriBuilder.Uri;
    }
}
</code></pre>
<p>Let's review these changes:</p>
<ul>
<li><p><code>WithResourceMapping</code> maps the directory from our local system to the directory in the container, making our certificates available to Azurite inside the container instance.</p>
</li>
<li><p><code>WithCommand</code> allows us to run a command inside the container during startup. We use the same command that we used to run the Docker container on the local system.</p>
</li>
</ul>
<p>Since we no longer use a connection string, we need the real addresses of the services (in our example, we use only the blob service, but it's easy to extend for tables and queues). Unfortunately, <code>AzuriteContainer</code> does not return such data by default, but we can easily retrieve it from a connection string. We use <code>GetServiceUri</code> and <code>BlobUriRegex</code> for that.</p>
<p>There is a small change in <code>ApiWebApplicationFactory</code> to use the blob URI instead of the connection string:</p>
<pre><code class="lang-csharp">services.AddSingleton(<span class="hljs-keyword">new</span> BlobServiceClient(azuriteTestContainer.BlobUri, <span class="hljs-keyword">new</span> DefaultAzureCredential()));
</code></pre>
<p>After these changes, our application and tests should work as before in the local environment. However, if you run them on CI, they might fail due to missing certificates. To address this issue, make a few small changes in your pipeline:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">variables:</span>
  <span class="hljs-attr">solution:</span> <span class="hljs-string">'azurite-testcontainers/AzuriteTestContainers.sln'</span>
  <span class="hljs-attr">azureSubscription:</span> <span class="hljs-string">'My Test Subscription'</span>

<span class="hljs-comment"># Others tasks omitted</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">CmdLine@2</span>
  <span class="hljs-attr">displayName:</span> <span class="hljs-string">install</span> <span class="hljs-string">certificate</span>
  <span class="hljs-attr">inputs:</span>
    <span class="hljs-attr">workingDirectory:</span> <span class="hljs-string">$(Build.SourcesDirectory)</span>
    <span class="hljs-attr">script:</span> <span class="hljs-string">|
      sudo apt install libnss3-tools -y
      curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"
      chmod +x mkcert-v*-linux-amd64
      sudo cp mkcert-v*-linux-amd64 /usr/local/bin/mkcert
      mkcert -install
      mkcert -cert-file ./azurite-testcontainers/AzuriteTestContainers.IntegrationTests/certs/127.0.0.1.pem -key-file ./azurite-testcontainers/AzuriteTestContainers.IntegrationTests/certs/127.0.0.1-key.pem 127.0.0.1
</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">task:</span> <span class="hljs-string">AzureCLI@2</span>
  <span class="hljs-attr">displayName:</span> <span class="hljs-string">test</span>
  <span class="hljs-attr">inputs:</span>
    <span class="hljs-attr">azureSubscription:</span> <span class="hljs-string">$(azureSubscription)</span>
    <span class="hljs-attr">scriptType:</span> <span class="hljs-string">pscore</span>
    <span class="hljs-attr">scriptLocation:</span> <span class="hljs-string">inlineScript</span>
    <span class="hljs-attr">inlineScript:</span> <span class="hljs-string">|
      dotnet test $(solution) /p:CollectCoverage=true /p:CoverletOutputFormat=opencover --collect "Code coverage" --logger trx
</span>
<span class="hljs-comment"># Others tasks omitted</span>
</code></pre>
<p>A new step, <code>install certificate</code>, has been added. If you're using a Windows machine, you can find information about the installation process on the GitHub page of the utility.</p>
<p>We can no longer use the <code>DotNetCoreCLI@2</code> task to run tests because we now use managed identity in our tests, which require running them with an identity. If you deploy your application to Azure, you use a subscription for that purpose, and you can use the same subscription to run tests. To do so, use the <code>AzureCLI@2</code> task and specify the subscription to use.</p>
<h2 id="heading-summary">Summary</h2>
<p>Testing is an integral part of our daily routine, and libraries like Testcontainers make it easier. We have demonstrated how simple it is to use Azurite in a container, and our minor changes in the testing infrastructure further validate this approach.</p>
<h2 id="heading-links">Links</h2>
<p><a target="_blank" href="https://github.com/MasDenBy/blog-samples/tree/main/azurite-testcontainers">Source Code on GitHub</a></p>
<p><a target="_blank" href="https://hub.docker.com/_/microsoft-azure-storage-azurite">Azurite image on Docker Hub</a></p>
<p><a target="_blank" href="https://github.com/Azure/Azurite">Azurite on GitHub</a></p>
<p><a target="_blank" href="https://testcontainers.com/">Testcontainers</a></p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview">What are managed identities for Azure resources?</a></p>
<p><a target="_blank" href="https://github.com/FiloSottile/mkcert">mkcert</a></p>
<p>Image credits: <a target="_blank" href="https://www.instagram.com/jane__ml/">Jane__ml</a></p>
]]></content:encoded></item><item><title><![CDATA[How to use Azure AI Translator service for text translation]]></title><description><![CDATA[Azure AI Translator is a potent cloud-based tool provided by Microsoft that automates language translation and localization in applications.]]></description><link>https://iharmaiseyeu.net/how-to-use-azure-ai-translator-service-for-text-translation</link><guid isPermaLink="true">https://iharmaiseyeu.net/how-to-use-azure-ai-translator-service-for-text-translation</guid><category><![CDATA[Azure]]></category><category><![CDATA[C#]]></category><category><![CDATA[Azure Key Vault]]></category><category><![CDATA[Bicep]]></category><category><![CDATA[azure ai services]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Fri, 01 Sep 2023 06:00:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693419589726/a3db7a9c-d71c-4503-a611-cf646ab5e012.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Azure AI Translator is a potent cloud-based tool provided by Microsoft that automates language translation and localization in applications, websites, and services. If you require translation capabilities in an application, Azure AI Translator can provide the solution.</p>
<h2 id="heading-provisioning-resource">Provisioning resource</h2>
<p>To begin, we'll utilize the Azure CLI to deploy the necessary resources. Follow these steps:</p>
<ol>
<li><p>Create a resource group named <code>translator-rg</code> in the <code>westeurope</code> region:</p>
<pre><code class="lang-bash"> az group create --location westeurope --name translator-rg
</code></pre>
</li>
<li><p>Create a Text Translator service named <code>mytranslator</code> within the <code>translator-rg</code> resource group:</p>
<pre><code class="lang-bash"> az cognitiveservices account create \
     --kind TextTranslation \ <span class="hljs-comment"># We need TextTranslator</span>
     --location WestEurope \
     --name mytranslator \
     --resource-group translator-rg \
     --sku S1 \
     --subscription 00000000-0000-0000-0000-000000000000 <span class="hljs-comment"># Your subscription</span>
     --yes
</code></pre>
</li>
</ol>
<p>With these steps, you've established a resource group and created a Text Translator service.</p>
<p>To communicate with Translator API we need to have the endpoint of the service and keys. For text translation, we need to use the global endpoint <code>https://api.cognitive.microsofttranslator.com/</code>.</p>
<p>To retrieve the keys we need to execute the following command</p>
<pre><code class="lang-bash">az cognitiveservices account keys list --name mytranslator -g translator-rg
</code></pre>
<p>Copy and paste one key to the notepad.</p>
<blockquote>
<p>For the production environment use Azure Key Vault to store keys. See "Use Azure Key Vault to store key" below in the article.</p>
</blockquote>
<p>Now we have everything to make some translations using Azure AI Translator.</p>
<h2 id="heading-working-with-api">Working with API</h2>
<h3 id="heading-basic-approach">Basic approach</h3>
<p>We need to have some objects for request and response. Let's use records to create them.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">internal</span> record <span class="hljs-title">TranslationRequest</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> Text</span>)</span> { }
<span class="hljs-function"><span class="hljs-keyword">internal</span> record <span class="hljs-title">TranslationResponse</span>(<span class="hljs-params">Translation[] Translations</span>)</span> { }
<span class="hljs-function"><span class="hljs-keyword">internal</span> record <span class="hljs-title">Translation</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> Text, <span class="hljs-keyword">string</span> To</span>)</span> { }
</code></pre>
<p>Now we are ready to call the API.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Net.Http.Json;

<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TranslatorKey = <span class="hljs-string">"[api-key]"</span>;
<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TranslatorEndpoint = <span class="hljs-string">"https://api.cognitive.microsofttranslator.com"</span>;
<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> Location = <span class="hljs-string">"[location-of-resource]"</span>;

<span class="hljs-keyword">var</span> text = <span class="hljs-string">"Let's translate some text"</span>;

<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> request = <span class="hljs-keyword">new</span> HttpRequestMessage(HttpMethod.Post, 
    <span class="hljs-string">$"<span class="hljs-subst">{TranslatorEndpoint}</span>/translate?api-version=3.0&amp;from=en&amp;to=es&amp;to=cs&amp;to=nl"</span>);
request.Headers.Add(<span class="hljs-string">"Ocp-Apim-Subscription-Key"</span>, TranslatorKey);
request.Headers.Add(<span class="hljs-string">"Ocp-Apim-Subscription-Region"</span>, Location);
request.Content = JsonContent.Create(<span class="hljs-keyword">new</span> [] { <span class="hljs-keyword">new</span> TranslationRequest(text) });

<span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> HttpClient().SendAsync(request);
response.EnsureSuccessStatusCode();

<span class="hljs-keyword">var</span> responseContent = <span class="hljs-keyword">await</span> response.Content.ReadFromJsonAsync&lt;TranslationResponse[]&gt;();
<span class="hljs-keyword">var</span> translations = responseContent?.First()?.Translations;

<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> translation <span class="hljs-keyword">in</span> translations)
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{translation.To}</span>: <span class="hljs-subst">{translation.Text}</span>"</span>);
</code></pre>
<p>Make sure to replace <code>[api-key]</code> with the key obtained from the translator account and <code>[location-of-resource]</code> with the location where your translation resource was created.</p>
<p>Pay attention to the requested URL <code>$"{TranslatorEndpoint}/translate?api-version=3.0&amp;from=en&amp;to=es&amp;to=fr&amp;to=de"</code> . Let's have a look into it more closely.</p>
<ul>
<li><p><code>version=3.0</code> is the API version we want to use</p>
</li>
<li><p><code>from=en</code> indicating that we would like to have a translation from English. This parameter is optional so if it is missing translator will try to detect the language.</p>
</li>
<li><p><code>&amp;to=es&amp;to=cs&amp;to=nl</code> the list of languages to translate text to. This is a required parameter. To get the list of all supported languages follow this <a target="_blank" href="https://api.cognitive.microsofttranslator.com/languages?api-version=3.0">link</a>.</p>
</li>
</ul>
<p>The result of running this code</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692976189932/9463aa55-7a8d-4e4b-be0d-786fcc5961d7.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-use-azure-key-vault-to-store-key">Use Azure Key Vault to store key</h3>
<p>The problem with the code is that we need to copy-paste and store the key with the application. From a security perspective, it is a breach because everyone can access it, and if for the testing environment, it is not a big problem it is better not to leak production keys.</p>
<p>To solve this problem we can use Azure Key Vault to store our key. Our application will know only about the key name and how to access it. Let's have a look at how to implement such an approach.</p>
<ol>
<li><p>Create a Key Vault with the name <code>translatorappvault</code> in the resource group <code>translator-rg</code> using Azure CLI.</p>
<pre><code class="lang-bash"> az keyvault create --location WestEurope \
    --name translatorappvault \
    --resource-group translator-rg
</code></pre>
</li>
<li><p>Set key from Azure AI Translator.</p>
<p> Note: Replace <code>[api-key]</code> with the actual key from the Translator resource.</p>
<pre><code class="lang-bash"> az keyvault secret <span class="hljs-built_in">set</span> --vault-name translatorappvault \
    --name <span class="hljs-string">"TranslatorKey"</span> \
    --value <span class="hljs-string">"[api-key]"</span>
</code></pre>
</li>
<li><p>Add the following packages to the solution:</p>
<pre><code class="lang-bash"> dotnet add package Azure.Security.KeyVault.Secrets
 dotnet add package Azure.Identity
</code></pre>
<p> <code>Azure.Security.KeyVault.Secrets</code> provides the implementation of the API necessary to access Key Vault. <code>Azure.Identity</code> provides the authentication possibility.</p>
</li>
<li><p>Accessing Key Vault and retrieving the key</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TranslatorKey = <span class="hljs-string">"TranslatorKey"</span>;
 <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> KeyVaultEndpoint = <span class="hljs-string">"https://translatorappvault.vault.azure.net/"</span>;

 <span class="hljs-keyword">var</span> client = <span class="hljs-keyword">new</span> SecretClient(<span class="hljs-keyword">new</span> Uri(KeyVaultEndpoint), <span class="hljs-keyword">new</span> DefaultAzureCredential());
 <span class="hljs-keyword">var</span> secretResponse = <span class="hljs-keyword">await</span> client.GetSecretAsync(TranslatorKey);
</code></pre>
<p> Notice that we use <code>DefaultAzureCredential</code> during the instantiation of <code>SecretClient</code>. This type of credential allows us to use passwordless authentication and the most important part is that this code will work similarly in every environment either development, testing, or production.</p>
</li>
<li><p>In the last part, we need to change the header <code>Ocp-Apim-Subscription-Key</code> to use the key retrieved from Azure Key Vault.</p>
<pre><code class="lang-csharp"> request.Headers.Add(<span class="hljs-string">"Ocp-Apim-Subscription-Key"</span>, secretResponse.Value.Value);
</code></pre>
</li>
</ol>
<p>Running this code will give the same translations as before with the only difference that we don't provide any key.</p>
<p>We still have room for improvement. As you remember we set the key to Key Vault manually and if for some reason we need to change it (leaks or key rotation) we need to perform the same steps. Not only is it error-prone but also a potential place for leaking credentials.</p>
<h3 id="heading-small-deployment-improvement">Small deployment improvement</h3>
<p>To improve our solution we can use Bicep. The domain-specific language developed by Microsoft to describe and deploy Azure resources.</p>
<p>The following script describes our resources.</p>
<pre><code class="lang-bash">param principalId string
param location string = resourceGroup().location

var tenant = subscription().tenantId
var secretsUserRoleId = <span class="hljs-string">'4633458b-17de-408a-b874-0445c86b69e6'</span>

resource translator <span class="hljs-string">'Microsoft.CognitiveServices/accounts@2023-05-01'</span> = {
  name: <span class="hljs-string">'mytranslator'</span>
  location: location
  sku: {
    name: <span class="hljs-string">'S1'</span>
    tier: <span class="hljs-string">'Standard'</span>
  }
  kind: <span class="hljs-string">'TextTranslation'</span>
  identity: {
    <span class="hljs-built_in">type</span>: <span class="hljs-string">'SystemAssigned'</span>
  }
  properties: {  
  }
}

resource keyvault <span class="hljs-string">'Microsoft.KeyVault/vaults@2023-02-01'</span> = {
  name: <span class="hljs-string">'translatorappvault'</span>
  location: location
  properties: {
    tenantId: tenant
    sku: {
      family: <span class="hljs-string">'A'</span>
      name: <span class="hljs-string">'standard'</span>
    }
    enableRbacAuthorization: <span class="hljs-literal">true</span>
    accessPolicies: []
  }
}

resource translatorKeySecret <span class="hljs-string">'Microsoft.KeyVault/vaults/secrets@2023-02-01'</span> = {
  name: <span class="hljs-string">'translatorKey'</span>
  parent: keyvault
  properties: {
    value: translator.listKeys().key1
  }
}

resource secretsUserAssignment <span class="hljs-string">'Microsoft.Authorization/roleAssignments@2022-04-01'</span> = {
  name: guid(keyvault.id, secretsUserRoleId, principalId)
  scope: keyvault
  properties: {
    roleDefinitionId: resourceId(<span class="hljs-string">'Microsoft.Authorization/roleDefinitions'</span>, secretsUserRoleId)  
    principalId: principalId
    principalType: <span class="hljs-string">'User'</span>
  }
}
</code></pre>
<p>We have four different resources here <code>translator</code>, <code>keyvault</code>, <code>translatorKeySecret</code> and <code>secretsUserAssignment</code> let's have a look at them.</p>
<p><code>translator</code> and <code>keyvault</code> are the resources we previously created with Azure CLI, but why do we need two others?</p>
<p>Previously we created <code>translatorKeySecret</code> as well as with the command <code>az keyvault secret set</code>. This resource holds the key to the translator API. The interesting part of this code is the following:</p>
<pre><code class="lang-bash">value: translator.listKeys().key1
</code></pre>
<p>In such a declarative way we say that the value for <code>TranslatorKey</code> is the <code>key1</code> of <code>translator</code>. So that every time we deploy our resources this value would be set, thus the key would be up-to-date.</p>
<p>The latest resource is <code>secretsUserAssignment</code> with the type <code>Microsoft.Authorization/roleAssignments</code> permits the user to read secrets. Because right now we run our app on behalf of the user account we give such permission to the user. If our application were running in the cloud we would permit it instead of a user.</p>
<p>To execute the deployment script we need to obtain the principal ID of the user who runs the application. Execute the following command in the Azure CLI replacing <code>[email-address-of-the-user]</code> with your email address.</p>
<pre><code class="lang-bash">az ad user show --id <span class="hljs-string">"[email-address-of-the-user]"</span> --query id --output tsv
</code></pre>
<p>Now we are ready to deploy our resources.</p>
<pre><code class="lang-bash">az deployment group create --resource-group translator-rg \
    --template-file resources.bicep \
    --parameters principalId=<span class="hljs-string">"[guid-from-previous-step]"</span>
</code></pre>
<p><code>resources.bicep</code> is the file name of the deployment script. If you name it differently don't forget to change it in the command.</p>
<p>Running the application after the script has been finished should give identical translations.</p>
<p>Let's check that new keys are applied automatically. For that, we manually regenerate the key1 using this command.</p>
<pre><code class="lang-bash">az cognitiveservices account keys regenerate --name mytranslator \
    -g translator-rg \
    --key-name key1
</code></pre>
<p>Run the application and it should fail with 401 Unauthorized response.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693241727290/842aa9b2-7648-4429-859d-aacdb90c6f7a.jpeg" alt class="image--center mx-auto" /></p>
<p>It is expected because we changed the keys but did not redeploy our resources thus Key Vault still has the old key. Run the deployment command. When it is finished run the application to check that everything works as expected.</p>
<h2 id="heading-summary">Summary</h2>
<p>Azure AI Translator offers robust text translation capabilities that are fast and provide high-quality translations. At the same time, the use of keys instead of managed identity might be considered as a downside. We can use Azure Key Vault to eliminate this problem.</p>
<p>For more detailed information on available methods and features, refer to <a target="_blank" href="https://learn.microsoft.com/en-us/azure/ai-services/translator/reference/rest-api-guide">the official documentation</a>.</p>
<p>Image credits: "<a target="_blank" href="https://www.pexels.com/photo/books-768125/">Books</a>" by <a target="_blank" href="https://www.pexels.com/@emily-252615/">Emily</a></p>
]]></content:encoded></item><item><title><![CDATA[Renewing Azure certificate]]></title><description><![CDATA[Renewing an Azure certificate involves extending the validity period of an existing certificate. By default, the certificate's validity is set to two years…]]></description><link>https://iharmaiseyeu.net/renewing-azure-certificate</link><guid isPermaLink="true">https://iharmaiseyeu.net/renewing-azure-certificate</guid><category><![CDATA[Azure]]></category><category><![CDATA[Certification]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Fri, 25 Aug 2023 07:49:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1692949573081/adea983b-7742-4c23-8adf-b240b992dad9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Renewing an Azure certificate involves extending the validity period of an existing certificate. By default, the certificate's validity is set to two years from the date of issuance. To achieve this, specific criteria must be met:</p>
<ul>
<li><p>The certification must currently be active. Occasionally, Microsoft may retire specific exams, making it impossible to obtain or extend certifications associated with those exams.</p>
</li>
<li><p>Renewing should be done 180 days before the end date and before the certificate's expiration. Therefore, if your certification is valid until December 20, 2023, it's crucial to complete the renewal before that date.</p>
</li>
</ul>
<h3 id="heading-preparation">Preparation</h3>
<p>Around 180 days before the certificate's expiration, Microsoft sends an email to the address used for certification, with the subject "Action required - Your Microsoft Certification will expire in 180 days!" This email contains essential information about the process that I strongly recommend reading, along with a link to Microsoft Learn, which provides detailed information.</p>
<blockquote>
<p>It's also possible to check your certificate status without waiting for emails. Simply sign in to your <a target="_blank" href="https://learn.microsoft.com/en-us/">Microsoft Learn</a> profile and in the left, menu click "Certifications".</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692902395345/8da00f36-752e-48a8-8427-819b7577ca16.png" alt class="image--center mx-auto" /></p>
<p>Clicking the Renew button, either in the email or on the "Certifications" page, opens a detailed information page about the assessment, terms, measured skills, and more.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692902441207/f1a3f7f6-a02f-4769-be2b-58fc00671dd6.png" alt class="image--center mx-auto" /></p>
<p>One significant section on this page (in my opinion) is "Prepare for the renewal assessment." Here, you can find modules that aid in preparing for the renewal assessment.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692902558643/d4fb780b-827f-420f-8284-55f0d2aa154c.png" alt class="image--center mx-auto" /></p>
<p>While these modules might not encompass all the information needed to pass the assessment successfully, they serve as an excellent starting point. For additional information, referring to the official Microsoft documentation is advisable to delve deeper into specific topics that might arise.</p>
<h3 id="heading-assessment">Assessment</h3>
<p>The assessment consists of 25 questions, including both single-choice and multi-choice questions. To pass, you need to achieve a minimum score of 60%.</p>
<p>The first two attempts can be made consecutively, but after the second failure, a 24-hour waiting period is imposed. Thus, it's better not to postpone the exam until the last day or week, as you'll have only one attempt per day after the second try.</p>
<p>"Should I attempt the assessment without preparation?" This is a subjective question. There's a possibility that you're already familiar with the material, and refreshing your knowledge might not be necessary. Alternatively, you might want to use the questions to identify areas for further learning. In any case, choose what suits you best. I prefer going through the modules first and then attempting the exam.</p>
<p>When you feel ready, don't hesitate to take the exam. Even in the event of failure, the assessment provides valuable insights into the topics you need to focus on. Take your time to review these areas and try again.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692902650158/de5e21fa-0353-40d1-a049-c261b5487d43.png" alt class="image--center mx-auto" /></p>
<p>Congratulations on successfully passing the assessment and extending your certificate's validity!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692902736782/00775b79-d157-4cb7-9cde-4697752f174e.png" alt class="image--center mx-auto" /></p>
<p>Image credits: "<a target="_blank" href="https://www.pexels.com/photo/selective-focus-photography-of-leaves-with-water-drop-531428/"><strong>Selective Focus Photography of Leaves With Water Drop</strong></a>" by <a target="_blank" href="https://www.pexels.com/@pixabay/">Pixabay</a></p>
]]></content:encoded></item><item><title><![CDATA[How to apply Content-Security-Policy (CSP) headers using Azure Front Door]]></title><description><![CDATA[Content-Security-Policy (CSP) is a security standard that helps prevent cross-site scripting (XSS) and other code injection attacks by allowing website…]]></description><link>https://iharmaiseyeu.net/how-to-apply-content-security-policy-csp-headers-using-azure-front-door</link><guid isPermaLink="true">https://iharmaiseyeu.net/how-to-apply-content-security-policy-csp-headers-using-azure-front-door</guid><category><![CDATA[Azure]]></category><category><![CDATA[.NET]]></category><category><![CDATA[Bicep]]></category><dc:creator><![CDATA[Ihar Maiseyeu]]></dc:creator><pubDate>Tue, 01 Aug 2023 06:00:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690838631927/dbea4aba-9cbf-41e0-9406-7050601fa284.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">Content-Security-Policy</a> (CSP) is a security standard that helps prevent cross-site scripting (XSS) and other code injection attacks by allowing website owners to specify which content sources can be trusted and loaded by their web pages. The CSP policy is defined in an HTTP header sent from the server to the client's web browser, and it can include directives that restrict the types of content allowed, such as images, scripts, stylesheets, and fonts.</p>
<p>Let's have a look at the most basic implementation using ASP.NET middleware.</p>
<pre><code class="lang-csharp">app.Use(<span class="hljs-keyword">async</span> (context, next) =&gt; {
    context.Response.Headers.Add(<span class="hljs-string">"Content-Security-Policy"</span>,
        <span class="hljs-string">"script-src 'self' cdn.jsdelivr.net;"</span> +
        <span class="hljs-string">"style-src 'self' fonts.googleapis.com cdn.jsdelivr.net;"</span> +
        <span class="hljs-string">"font-src 'self' fonts.gstatic.com;"</span>
    );

    <span class="hljs-keyword">await</span> next();
});
</code></pre>
<p>This implementation is simple, but it might be difficult to read and maintain when the amount of elements is increased.</p>
<p>To solve this problem we can use <a target="_blank" href="https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders">NetEscapades.AspNetCore.SecurityHeaders</a> package. The package is quite useful and can help to work with different security headers, not only with CSP. The code above can be transformed.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> policyCollection = <span class="hljs-keyword">new</span> HeaderPolicyCollection()
    .AddContentSecurityPolicy(builder =&gt;
    {
        builder.AddScriptSrc()
            .Self()
            .From(<span class="hljs-string">"cdn.jsdelivr.net"</span>);

        builder.AddStyleSrc()
            .Self()
            .From(<span class="hljs-string">"fonts.googleapis.com"</span>)
            .From(<span class="hljs-string">"cdn.jsdelivr.net"</span>);

        builder.AddFontSrc()
            .Self()
            .From(<span class="hljs-string">"fonts.gstatic.com"</span>);
    });

app.UseSecurityHeaders(policyCollection);
</code></pre>
<p>This code is better to read and most likely it is what you need in 99% of cases. The only problem here is we need to change the application code every time we need to modify headers. What goes with running the deployment pipeline and provisioning new updates just because of changes in a configuration. Usually, it is not a problem due to we don't need to perform such kinds of changes every week or month.</p>
<p>If in some cases you don't want to work with headers in the application code they can be applied through Web Application Firewall (WAF). There are both individual and part of cloud providers' services. I will show how to use WAF which is a part of Azure Front Door.</p>
<p>We have an assumption that Front Door is provisioned and all necessary configuration has been applied. If not please find more information on how to do it <a target="_blank" href="https://learn.microsoft.com/en-us/azure/frontdoor/create-front-door-portal">here</a>.</p>
<p>Open the Front Door profile and go to the menu <code>"Settings" -&gt; "Rule sets"</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690824583932/1afc4429-c848-4194-8aac-b0b4bdf8dc55.jpeg" alt class="image--center mx-auto" /></p>
<p>On <strong>Rule sets</strong> page, click <code>Add</code> button to add new rule sets.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690824781547/558b63ee-0143-45e7-a45c-f2e9bd47f01f.jpeg" alt class="image--center mx-auto" /></p>
<p>The rule sets configuration page allows to add of various rules to customize HTTP requests. Let's add our rules for Content Security Policy. For that, we need to click <code>Add Rule</code> button.</p>
<p>Enter the descriptive name something like <code>cspRule</code>.</p>
<p>We skip adding conditions because we would like to apply CSP headers for each request.</p>
<p>The next step is to add an action to modify the response header. Click <code>Add an action</code> button and choose <code>Modify response header</code> from the menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690825342442/628b66a1-89dd-413d-947f-98d4c0a59022.jpeg" alt class="image--center mx-auto" /></p>
<p>Because we would like to set up CSP headers only through Frontdoor, it is better to take precautionary steps and clear all possible headers which might be set on the backend side. To do so we need to choose the <code>Delete</code> operator and as a header name enter <code>'Content-Security-Policy'</code>.</p>
<p>After that add 3 other <code>Append</code> actions with header name <code>'Content-Security-Policy'</code> and the following header values:</p>
<p><code>script-src 'self' cdn.jsdelivr.net;</code></p>
<p><code>style-src 'self' fonts.googleapis.com cdn.jsdelivr.net;</code></p>
<p><code>font-src 'self' fonts.gstatic.com;</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690826588237/2af0d7ac-530e-4110-b401-d496a1d196da.jpeg" alt class="image--center mx-auto" /></p>
<p>Click <code>Save</code> button.</p>
<p>Right now we have the ruleset with the rule to modify CSP headers what we need to do is to apply this ruleset to the route. To do so open <code>Front Door manager</code> and choose the route.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690826854052/9c41905c-0de0-4141-8ffb-447f070e25f9.jpeg" alt class="image--center mx-auto" /></p>
<p>There is a section "Rules" at the bottom of the page. Choose the earlier created ruleset and click <code>Update</code> button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690827041193/9956503c-512c-4ed4-aa5e-bfd08c714c23.jpeg" alt class="image--center mx-auto" /></p>
<p>After all these steps Front Door will take care of applying the necessary Content Security Policy headers.</p>
<p>If you prefer to use IaC instead of working with UI there is the Bicep script for these rules.</p>
<pre><code class="lang-plaintext">resource frontdoor 'Microsoft.Cdn/profiles@2022-11-01-preview' = {
  name: 'sitefrontdoor'
  // The rest of configuration omitted
}

resource siteEndpoint 'Microsoft.Cdn/profiles/afdEndpoints@2021-06-01' = {
  parent: frontdoor
  name: 'siteEndpoint'
  // The rest of configuration omitted
}

resource cspRuleset 'Microsoft.Cdn/profiles/ruleSets@2022-11-01-preview' = {
  name: 'cspRuleset'
  parent: frontdoor
}

resource cspRule 'Microsoft.Cdn/profiles/ruleSets/rules@2022-11-01-preview' = {
  name: 'cspRule'
  parent: cspRuleset
  properties: {
    order: 1
    // We would like to apply this rule to all requests thus there are no conditions
    conditions: []
    actions: [
      // As a first action delete all CSP headers that might have set on backend site.
      // It is mostly precautions to make sure that we set headers only through Frontdoor.
      {
        name: 'ModifyResponseHeader'
        parameters: {
          headerAction: 'Delete'
          headerName: 'Content-Security-Policy'
          typeName: 'DeliveryRuleHeaderActionParameters'
        }
      }
      {
        name: 'ModifyResponseHeader'
        parameters: {
          headerAction: 'Append'
          headerName: 'Content-Security-Policy'
          typeName: 'DeliveryRuleHeaderActionParameters'
          value: 'script-src \'self\' cdn.jsdelivr.net;'
        }
      }
      {
        name: 'ModifyResponseHeader'
        parameters: {
          headerAction: 'Append'
          headerName: 'Content-Security-Policy'
          typeName: 'DeliveryRuleHeaderActionParameters'
          value: 'style-src \'self\' fonts.googleapis.com cdn.jsdelivr.net;'
        }
      }
      {
        name: 'ModifyResponseHeader'
        parameters: {
          headerAction: 'Append'
          headerName: 'Content-Security-Policy'
          typeName: 'DeliveryRuleHeaderActionParameters'
          value: 'font-src \'self\' fonts.gstatic.com;'
        }
      }
    ]
  }
}

resource siteRoute 'Microsoft.Cdn/profiles/afdendpoints/routes@2021-06-01' = {
  parent: siteEndpoint
  name: 'siteRoute'
  properties: {
    ruleSets: [
      {
        id: cspRuleset.id
      }
    ]
    // The rest of configuration omitted
  }
}
</code></pre>
<p>Image credits: "<a target="_blank" href="https://unsplash.com/photos/MAgPyHRO0AA">right arrow sign on wall</a>" by <a target="_blank" href="https://unsplash.com/@helloimnik">Nik</a></p>
]]></content:encoded></item></channel></rss>