> For the complete documentation index, see [llms.txt](https://kdongs.gitbook.io/kdocs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kdongs.gitbook.io/kdocs/event-driven-architecture/event-driven-architecture.md).

# Event Driven Architecture

## About

An [**event**](#events)**-oriented** or [**event**](#events)**-driven** architecture, is a solution for **distributed** [**transactions**](#what-is-a-transaction) in a **Microservice environment** having:

* Low coupling;
* Asynchronism (With [Queues](#queues));
* Without the need of an [orchestrator](#orchestrated-saga).

{% hint style="info" %}
Tecnically only used in a Microservice Architecture.
{% endhint %}

{% hint style="success" %}
**Advantages**

* Low coupling between Usecases inside and outside of a service.
* Fail tolerance with the capacity if returning from where it stopped.
* More control over technical debt.
* Higher availability and scalability.
* Lower costs with infrastructure.
* Better understanding over what happened, with possibility of *PITR*.
  {% endhint %}

{% hint style="danger" %}
**Disavantages**

* Higher technical complexity.
* Must deal with event duplication.
* Lack of workflow clarity.
* More difficulty in treating and diagnosing errors.
  {% endhint %}

## What is a Transaction

It is an abstraction of a set of operations that must be treated like a single logical unit, where either:

* &#x20;**ALL** of the Transaction operations **succeed**.
* Or everything is **undone**.

{% hint style="info" %}
Ex.: Concept of *ACID* for relational databases.
{% endhint %}

{% hint style="warning" %}
The more complex and distributed an Architecture is, the greater the changes of bad things happening.

So **resilience** is the ability to keep it running and recover from failure.
{% endhint %}

#### Example

In a distributed environment, not every operation of a Transaction are for Databases. *(You could have operations that check files, or external APIs, or Different DB types, or has to wait for a scritp to calculate something, etc...)*

So in these chained distributed environments, what happens if we have a fatal error in the middle of a Transaction?

## Events

Events are facts that happened in the Domain and can be a trigger to execute business rules.

Events are facts that were published and must be consumed/treated.

{% hint style="info" %}
*Ex.:* `OrderPlaced`*,* `PaymentApproved`*,* `InvoiceGenerated`*,* `RideRequested`*,* `RideEnded`*, ...*
{% endhint %}

<img src="https://3792343559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSVfaTfyoHBzPgzE6jDl0%2Fuploads%2FoHQkJ2ejiKRgPnuS09P7%2Ffile.excalidraw.svg?alt=media&amp;token=94e05d8e-40ae-419d-b852-ee87df28e50a" alt="" class="gitbook-drawing">

## Commands

Commands are solicitations, and eventually can be rejected.

### Command Handler

Involves separating a solicitation that was synchronous in 2 steps.

* One that receives the command.
* The second one that process the command.

<br>

## Queues

They exist to balance resource availability with resource demand. Since there isn't always enough available resources, and it would be too expensive to have it, we can queue demand.

Queuing demand avoids waist of resources, because of peak behavior of demand.

### Implementing Queues

#### Locally

Can be locally done in the code with help of [Broken mention](broken://pages/p1sH2jAi8FYAwrlbSVJi#mediator) and [Broken mention](broken://pages/p1sH2jAi8FYAwrlbSVJi#observer).

#### Externally

With plataforms like:

* `RabbitMQ`
* `Kafka`
* `AWS SQS`
* `ActiveMQ`
* `Google Pub/Sub`
* `ZeroMQ`
* `Pulsar`

## Patterns

### Retry

Retry pattern **simply makes one or more retries in a small time interval**.

They can resolve simple problems like package loss, network oscillations and even a out of time deploy.

### Fallback

When encountering unavailability during execution, this pattern helps by trying another service.

{% hint style="info" %}
Ex.: E-commerces work with several credit card services to avoid unavailabilities.
{% endhint %}

{% hint style="warning" %}
Same essence of [Broken mention](broken://pages/p1sH2jAi8FYAwrlbSVJi#chain-of-responsibility).
{% endhint %}

### SAGA

This pattern is responsible for managing long duration transactions, by using a sequence of local transactions.

{% hint style="info" %}
They are not necessarily related to microservices, and can be applied to any type of long duration distributed transaction.
{% endhint %}

<figure><img src="https://3792343559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSVfaTfyoHBzPgzE6jDl0%2Fuploads%2FRWxtWdUhxIwo0l2BXPQX%2Fflow.png?alt=media&amp;token=e408749c-2b6c-4345-8c36-3c0e5dc6a64c" alt="" width="479"><figcaption></figcaption></figure>

#### SAGA has 3 types of Transactions

<table data-view="cards"><thead><tr><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Pivot Transaction</strong></td><td><ul><li>They are <code>go</code> or <code>no go</code> transactions.</li><li>These are transactions that decide if entire flow of execution goes forward or gets aborted.</li></ul></td><td></td></tr><tr><td><strong>Compensable Transaction</strong></td><td><ul><li>These transactions are undone in case the entire transaction is aborted.</li></ul></td><td></td></tr><tr><td><strong>Retriable Transaction</strong></td><td><ul><li>These have a guarantee of execution. </li><li>They can recover from a possible fail or unavailability.</li></ul></td><td></td></tr></tbody></table>

#### Orchestrated SAGA

In these types of SAGA, there is a centralized logic that coordinates each of the steps.

{% hint style="success" %}
Easier to see/understand the workflow.
{% endhint %}

{% hint style="danger" %}
As a drawback, it is highly dependent in this central orchestrator.
{% endhint %}

The orchestrator knows which step he is supposed to call next, even on failures.

{% hint style="info" %}
*This centralized logic could be in the simpler way, just a script that can call each step and a database table that holds which step of the entire Transaction it is in.*
{% endhint %}

<img src="https://3792343559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSVfaTfyoHBzPgzE6jDl0%2Fuploads%2FGXlrhhShF0P1DaImYblW%2Ffile.excalidraw.svg?alt=media&amp;token=c3166f51-474f-48e1-8c10-34f6a99ff95b" alt="" class="gitbook-drawing">

#### Choreographed SAGA

In these types of SAGA, each participant publishes and treat events independently, deciding if it should continue or not the flow.

{% hint style="danger" %}
As a drawback, it may be harder to see/understand the workflow.
{% endhint %}

<img src="https://3792343559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSVfaTfyoHBzPgzE6jDl0%2Fuploads%2F7tUfQ53jom7Xk477dzrL%2Ffile.excalidraw.svg?alt=media&amp;token=d0d20b4a-977d-499e-bd4f-d2088bed500e" alt="" class="gitbook-drawing">
