sagaを使用したマイクロサービスのデータ一貫性

sagaを使用したマイクロサービスのデータ一貫性
Richardson氏は、マイクロサービスアーキテクチャでは、各マイクロサービスは、
他のマイクロサービスから直接アクセスできない独自のプライベートデータベースを持つべきであると説明した。
Richardson氏は、これによって結合が緩やかになる一方で、データの一貫性に問題があると指摘している。
「現在、複数のマイクロサービスにまたがるトランザクションはどのように実装するか。」

この問題を解決するために、Richardson氏はsagaパターンを導入した。
その基本的な原則は、ロックを保持する長いトランザクション(2相コミットのような)の代わりに、順番にコミットする一連の短いトランザクションに分割することである。
これにより、以下のACD特性が得られる。

原子性:すべてのトランザクションが実行されるか、またはすべてが相殺されるか
一貫性:参照整合性は、ローカルデータベースとアプリケーションコードの両方によって与えられる
永続性:これはメッセージブローカとデータベースによって保証される
QCONSF 2017 presentation - ACID Is So Yesterday: Maintaining Data Consistency with Sagas

Pattern: Saga

An e-commerce application that uses this approach would create an order using a saga that consists of the following local transactions:

The Order Service creates an Order in a pending state
The Customer Service attempts to reserve credit for that Order.
The Order Service changes the state of the order to either approved or cancelled
Each local transaction publishes an event or message that triggers the next step.

For example, in the CreateOrder saga,
the OrderService publishes an OrderCreated event and the Customer Service publishes either a Credit Reserved event or a CreditLimitExceeded event.