Search code examples
design-patternsmicroservices

Transactional outbox pattern vs Event Sourcing


What is the exact difference between transactional outbox and event sourcing patterns? Both are competitive pattern and can be used for same purpose. Is there any example through which I can understand when to use what?


Solution

  • I found these two links very useful:

    https://microservices.io/patterns/data/transactional-outbox.html https://microservices.io/patterns/data/event-sourcing.html

    They are both used in microservices environment to guarantee consinstency across different microservices and databases without using two-phase-commit (2PC)

    The Transactional Outbox pattern allows you to have a traditional design of entities in your database and each update operation performed on the entities actually updates some rows in the database. The pattern also requires the use of an outbox table in the database so that you can have a local transaction which

    • Updates the database
    • Creates the message entry in the outbox table

    A message relay is then used to read the outbox table and send messages to the broker

    With the Event Sourcing pattern the database design results slightly different from a traditional design.

    Think of an Account entity which has the following properties:

    • Id (string)
    • Credit (number)

    Suppose you have an Account table as follows:

    | Id       | Credit |
    | account1 | 5      |
    

    If you perform an update operation which adds 1 to the credit it would affect the table in the following way:

    | Id       | Credit |
    | account1 | 6      |
    

    With the event sourcing pattern you don't store the Account directly in the database, instead you store the transactions happened on the accounts:

    | TransactionType   | AccountId | Credit |
    | Create            | account1  | 5      |
    | Add               | account1  | 1      |
    

    Since the read operations are a bit more complex with this approach (you should go along all the rows to sum and subtract the credit of each transactions to get the current credit) it is often used along with the CQRS pattern