Sobes.tech
Middle — Middle+

Can you explain the concept of Event Sourcing and how it is used in application architecture?

sobes.tech AI

Answer from AI

Event Sourcing is an architectural pattern where all changes to an application's state are stored as a sequence of events, rather than as the current state.

Instead of storing only the current data, the system saves all events that led to this state. To obtain the current state, these events are replayed sequentially.

Advantages:

  • Complete history of changes, which facilitates auditing and debugging.
  • Ability to revert to any previous state.
  • Simplifies the implementation of complex business logic and integration with other systems through events.

Application: In application architecture, Event Sourcing is often used together with CQRS (Command Query Responsibility Segregation). Commands change the state by creating events, which are stored in an event log. Reading is done from projections built based on these events.

Example in C# (simplified):

public class AccountCreated : IEvent { public Guid AccountId; public decimal InitialBalance; }
public class MoneyDeposited : IEvent { public decimal Amount; }

public class Account
{
    private decimal balance;
    private List<IEvent> changes = new List<IEvent>();

    public void Apply(IEvent e)
    {
        switch(e)
        {
            case AccountCreated ac:
                balance = ac.InitialBalance;
                break;
            case MoneyDeposited md:
                balance += md.Amount;
                break;
        }
    }

    public void Deposit(decimal amount)
    {
        var e = new MoneyDeposited { Amount = amount };
        Apply(e);
        changes.Add(e);
    }
}

Here, the account state is reconstructed from events, and new events are added upon changes.