Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Aug 8

Exploring microservices Saga and Compensation patterns with C# example

Exploring microservices Saga and Compensation patterns with C# example
Автор:
Источник:
Просмотров:
763

Introduction

Microservices, like a team of superheroes, are small, independent services that work together to create powerful applications. Sometimes, these services need to talk to each other in a specific order, and that’s where the microservices saga and compensation pattern come into play.

In this article, I will delve into the intricacies of using the Saga and Compensation patterns to design your microservice using C#.NET examples.

The microservices Saga

Imagine a story unfolding with multiple chapters, each chapter telling a part of the tale. Similarly, in microservices, a saga is a sequence of steps that must be performed in a specific order to achieve a goal.

C# example:

Let's say we have an online shopping system with two microservices: one for inventory and another for payments. When a user buys a product, the saga might involve checking if the item is in stock, reserving it, and then processing the payment.

public class OrderSaga
{
    private readonly InventoryService _inventoryService;
    private readonly PaymentService _paymentService;

    public OrderSaga(InventoryService inventoryService, PaymentService paymentService)
    {
        _inventoryService = inventoryService;
        _paymentService = paymentService;
    }

    public async Task PlaceOrderAsync(OrderDetails order)
    {
        try
        {
            // Step 1: Check inventory
            await _inventoryService.CheckInventoryAsync(order.ProductId, order.Quantity);
            // Step 2: Reserve inventory
            await _inventoryService.ReserveInventoryAsync(order.ProductId, order.Quantity);
            // Step 3: Process payment
            await _paymentService.ProcessPaymentAsync(order.Amount);
        }
        catch (Exception ex)
        {
            // Handle errors or compensate for failed steps
            Console.WriteLine($"Order processing failed: {ex.Message}");
            // Compensate by releasing reserved inventory
            await _inventoryService.ReleaseInventoryAsync(order.ProductId, order.Quantity);
        }
    }
}

In this example, the PlaceOrderAsync method represents our saga. It checks inventory, reserves the item, and processes payment. If any step fails, it catches the error and compensates by releasing the reserved inventory.

Compensation Pattern

Imagine you accidentally knock over a tower of blocks you were building. The compensation pattern is like rebuilding that tower step by step to fix what went wrong.

C# example:

Let's modify our previous example to include explicit compensation steps for each action.

public class OrderSagaWithCompensation
{
    private readonly InventoryService _inventoryService;
    private readonly PaymentService _paymentService;    

    public OrderSagaWithCompensation(InventoryService inventoryService, PaymentService paymentService)
    {
        _inventoryService = inventoryService;
        _paymentService = paymentService;
    }    

    public async Task PlaceOrderAsync(OrderDetails order)
    {
        try
        {
            // Step 1: Check inventory
            await _inventoryService.CheckInventoryAsync(order.ProductId, order.Quantity);            
            // Step 2: Reserve inventory
            await _inventoryService.ReserveInventoryAsync(order.ProductId, order.Quantity);            
            // Step 3: Process payment
            await _paymentService.ProcessPaymentAsync(order.Amount);
        }
        catch (Exception ex)
        {
            // Handle errors
            Console.WriteLine($"Order processing failed: {ex.Message}");            
            // Compensate for failed steps
            await Compensate(order);
        }
    }    

    private async Task Compensate(OrderDetails order)
    {
        // Compensate by releasing reserved inventory
        await _inventoryService.ReleaseInventoryAsync(order.ProductId, order.Quantity);        
        // Compensate by refunding payment
        await _paymentService.RefundPaymentAsync(order.Amount);
    }
}

In this version, the Compensate method explicitly handles the compensation steps for each action, releasing the reserved inventory and refunding the payment.

Benefits and disadvantages

Benefits:

  1. Resilience:
    If one microservice fails, the saga and compensation pattern help maintain system integrity.
  2. Flexibility:
    Microservices can evolve independently, allowing for continuous improvement.
  3. Scalability:
    Different microservices can scale independently based on their specific needs.

Disadvantages:

  1. Complexity:
    Implementing sagas and compensation can be complex, requiring careful design and management.
  2. Consistency:
    Achieving consistency in a distributed environment can be challenging.
  3. Latency:
    Coordinating actions between microservices may introduce latency.

Conclusion

Microservices sagas and compensation patterns are like a well-choreographed dance, ensuring that even if a step falters, the performance continues smoothly. While they bring resilience and flexibility, they also introduce complexity. Like superheroes, microservices require a balance of power and responsibility to create robust and efficient applications.

So, just like assembling LEGO blocks, developers carefully craft microservices sagas to tell a story, ensuring that each step contributes to a successful ending.

Похожее
29 июля 2019 г.
От переводчика: некоторые скорее всего уже читали этот титанический труд от Мартина Фаулера и его коллеги Джеймса Льюиса, но я все же решил сделать перевод этой статьи. Тренд микросервисов набирает обороты в мире enterprise разработки, и эта статья является ценнейшим...
Nov 9, 2020
Author: Akhil Mittal
Microservices The term microservices portrays a software development style that has grown from contemporary trends to set up practices that are meant to increase the speed and efficiency of developing and managing software solutions at scale. Microservices is more about...
Nov 6
Author: Sylvain Tiset
Earlier I presented one useful design pattern to migrate to a monolithic application to microservices. This pattern is the Strangler Fig pattern and the article can be found here. Here some other specific microservices design patterns will be presented. What...
Sep 7, 2020
Microservices are the face of the future. Organizations are keen to adapt to Microservices, either by creating a new setup or by transforming monolithic applications into Microservices. Though the inclination towards migrating to Microservices quite high, how to approach the...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Стили именования переменных и функций. Используйте их все
10 историй, как «валят» айтишников на технических интервью
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Семь итераций наивности или как я полтора года свою дебютную игру писал
Вопросы с собеседований, которые означают не то, что вы думаете
Путеводитель по репликации баз данных
5 приемов увеличения продуктивности разработчика
Топ 8 лучших ресурсов для практики программирования в 2018
Использование SQLite в .NET приложениях
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile