CQRS+ES実践ガイド / CQRS+ES Practice Guide

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on. →
nrs
November 28, 2026

CQRS+ES実践ガイド / CQRS+ES Practice Guide

JJUG CCC 2026 Fall の講演資料です
CQRS+ES を実践するために必要な、実装の手法からモデリング、各種落とし穴の対策等をお話しています

イベント概要:https://jjug.doorkeeper.jp/events/199505
CQRS+ES実践ガイド:https://link.amazon/B08LW2qdD

# URL
YouTube: https://www.youtube.com/c/narusemi
HomePage: https://nrslib.com
Twitter: https://twitter.com/nrslib
Instagram: https://www.instagram.com/nrslib/

nrs

November 28, 2026

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

160 slides
  1. 判定に使う状態と読み取り専⽤の項⽬ 削除判定に必要な状態と表示・検索だけに使う項目が同じオブジェクトに入る public record User( String userId, boolean deleted, Instant

    lastLoginAt, int daysSinceCreated ) { // 省略 } deleted:削除済みなら更新不可という判定に使う lastLoginAt・daysSinceCreated:表示・検索用 4
  2. CQRS+ESを学ぶ意義 困難な要求に応えるアーキテクチャとして知っておく 通常の設計 まずはシンプルな モデルとDBで扱う 困った とき CQRS + ES

    書き込みと読み取りを分け 変更をイベント履歴として残す 採⽤後の課題と対処も選択肢の⼀部 たとえば……? 読み取り要件で 書き込みが複雑化 応答性能‧拡張を 既存設計で確保困難 履歴から別の Read Modelが必要 6
  3. 現在値に代わる状態変更の記録 従来のCRUDシステムとイベントソーシングの違い 従来のCRUDシステム イベントソーシング 商品テーブル Event Stream 項⽬ 値 0

    商品が5個入荷された 商品ID ABC123 1 商品が3個出荷された 名称 サンプル商品 2 商品が8個入荷された 在庫数 10個 現在の在庫数:5 - 3 + 8 = 10個 11
  4. Event Storeのリプレイによる現在の在庫データのリビルド 商品ABC123のEvent Streamを取得し、イベントを先頭から適用する Event Store(domain̲event̲entry) sequence_number Event Stream 商品ABC123のイベント列

    payload 0 商品が5個入荷された 0 商品が5個⼊荷された 1 商品が3個出荷された 1 商品が3個出荷された 2 商品が8個⼊荷された 2 商品が8個入荷された SELECT payload FROM domain_event_entry WHERE aggregate_identifier = 'ABC123' ORDER BY sequence_number; 取得 リプレイによる在庫の状態遷移 +5 在庫 0個 ­3 在庫 5個 +8 在庫 2個 現在 10個 12
  5. CQRSとESによる相互補完 単体の適用 CQRS単体 残る課題 もう一方で補うこと 状態変化の経緯が残るとは限らない ESで起きたことを記録し Read Modelへの反映仕組みも必要 イベントを購読して反映する

    イベントの積み重ねから ES単体 現在状態を求めるコスト 利用者向けのデータ整形 CQRSでRead Modelを 事前計算して照会する 記録したイベントを購読してRead Modelを更新する 14
  6. CQRSとESを組み合わせた全体構造 Event Storeへ追記しProjectionでRead Modelを更新する User Commands Queries Command Model 集約

    追記 Event Store Results Query Model イベント購読 Projection 読み取り Read Model 15
  7. 表⽰要件の変更に対するRead Modelのリビルド 画面に必要な項目を最初から決め切らずにイベント履歴からRead Modelを作り直す 現在状態だけを保持する構成 CQRS+ESの構成 現在のRead Model Event Store

    新しいProjection 過去の変更履歴は保持しない 全変更履歴 過去イベントを再⽣ 後から必要になった表示項目を 新しいRead Modelを作成し 過去分まで計算しにくい 表示要件の変更へ対応する 17
  8. Axon Frameworkを使った実装 CQRSとEvent Sourcingを実装するためのフレームワーク Axon Framework コマンド処理 Event Sourcing Query・Projection

    コマンドの配送と イベントの保存と クエリ処理と ハンドラ呼出 集約のリプレイ イベント購読 @CommandHandler @EventSourcingHandler @QueryHandler @EventHandler 19
  9. ユーザ⼀覧へのイベント反映 UserCreatedEventの購読とUserDataModelの保存 Event Store Projection UserCreatedEvent user-123 イベントを購読し 別トランザクションで Read

    Modelを更新 UserDataModel ユーザID・名前 メールアドレス ユーザ照会 Read Modelを参照 コマンドの完了と読み取り反映は同じタイミングではない 反映までの遅延を画面と運用で扱う 22
  10. ユーザ登録を表すコマンド public record CreateUserCommand( String name, String email ) {

    } CreateUserCommandは名前とメールアドレスだけを持つ 新規登録に必要な⼊⼒をひとつのコマンドへまとめる 23
  11. 新規登録⽤コマンドハンドラ @Aggregate public class UserAggregateAdapter { private User user; //

    省略 } @CommandHandler public UserAggregateAdapter(CreateUserCommand command) { var userId = UUID.randomUUID().toString(); var event = User.create(userId, command.name(), command.email()); AggregateLifecycle.apply(event); } User.createで⼊⼒検証とイベント⽣成を⾏う AggregateLifecycle.applyでイベントを適⽤する 24
  12. User.createによる登録イベントの⽣成 public record User(String userId) { // 省略 } public

    static UserCreatedEvent create( String userId, String name, String email ) { if (email == null || email.isEmpty()) { throw new IllegalArgumentException( "Email is required" ); } return new UserCreatedEvent(userId, name, email); } ⼊⼒を検証してUserCreatedEventを返す 25
  13. User.applyEventによるイベントの適⽤ public record User(String userId) { // 省略 public static

    User applyEvent(UserCreatedEvent event) { return new User(event.userId()); } } public User applyEvent(UserEvent event) { return switch (event) { case UserCreatedEvent e -> applyEvent(e); case UserUpdatedEvent _ -> this; default -> throw new IllegalStateException( "Unexpected event: " + event ); }; } イベントの適用によって状態が変更される 26
  14. イベントストアの記録情報 { } "eventIdentifier": "dfee010c-aca5-4beb-a8d1-0ae299f6502f", "aggregateIdentifier": "user-123", "aggregateSequenceNumber": 0, "aggregateType":

    "UserAggregate", "payloadType": "org.example...UserCreatedEvent", "payloadRevision": "", "timestamp": "2025-03-08T08:17:42.037Z", "payload": { "userId": "user-123", "name": "John", "email": "[email protected]" } 27
  15. 既存ユーザ更新時のイベントロードとリプレイ Event Store domain̲event̲entry aggregate̲identifier seq event̲type user-123 0 UserCreated

    user-123 1 UserUpdated user-123 2 UserUpdated User 0 登録 ロード userId = user-123 name = ⽥中 email = [email protected] userId = user-123 1 name = 鈴⽊ 名前更新 email = [email protected] userId = user-123 2 name = 鈴⽊ メール更新 email = [email protected] イベント適用ごとにフィールドが更新される リプレイの完了後に更新用コマンドハンドラを実行する 29
  16. ユーザ更新を表すコマンド public record UpdateUserCommand( @TargetAggregateIdentifier String userId, String name, String

    email ) { } 更新対象のuserIdと変更内容をコマンドに含める @TargetAggregateIdentifierで更新対象の集約を特定する 30
  17. 更新⽤コマンドハンドラ @Aggregate public class UserAggregateAdapter { private User user; //

    省略 } @CommandHandler public void handle(UpdateUserCommand command) { var event = user.update( command.name(), command.email() ); AggregateLifecycle.apply(event); } リプレイで再構成したuserのupdateを呼び出す 31
  18. User.updateによる更新イベントの⽣成 public record User(String userId) { // 省略 } public

    UserUpdatedEvent update( String name, String email ) { return new UserUpdatedEvent( userId, name, email ); } リプレイ後のuserIdと更新内容からUserUpdatedEventを⽣成する 32
  19. 削除⽤コマンドハンドラ @Aggregate public class UserAggregateAdapter { private User user; //

    省略 } @CommandHandler public void handle(DeleteUserCommand command) { if (user.deleted()) return; var event = new UserDeletedEvent(command.userId()); AggregateLifecycle.apply(event); } 削除済みなら新しいイベントを追記しない ⼆重削除を例外にするかはビジネス要件で決める 35
  20. 削除イベントを含むイベントの適⽤ public record User(String userId, boolean deleted) { // 省略

    } public User applyEvent(UserEvent event) { return switch (event) { case UserCreatedEvent e -> new User(e.userId(), false); case UserUpdatedEvent _ -> this; case UserDeletedEvent _ -> new User(userId, true); default -> throw new IllegalStateException( "Unexpected event: " + event ); }; } 削除も現在状態へのリプレイに使うイベントとして扱う 36
  21. ユーザ⼀覧への登録イベント反映 @Component public class UserProjection { private final UserDataModelRepository repository;

    // コンストラクタは省略 } @EventHandler public void on(UserCreatedEvent event) { var model = new UserDataModel( event.userId(), event.name(), event.email() ); repository.save(model); } UserCreatedEventからUserDataModelを⽣成して保存する 38
  22. ユーザ⼀覧への更新イベント反映 @Component public class UserProjection { private final UserDataModelRepository repository;

    // コンストラクタと他のハンドラは省略 } @EventHandler public void on(UserUpdatedEvent event) { var user = repository.findById(event.userId()) .orElseThrow(); user.setName(event.name()); user.setEmail(event.email()); repository.save(user); } 既存のUserDataModelを更新して保存する 39
  23. ユーザ⼀覧への削除イベント反映 @Component public class UserProjection { private final UserDataModelRepository repository;

    // コンストラクタと他のハンドラは省略 } @EventHandler public void on(UserDeletedEvent event) { repository.deleteById(event.userId()); } Event Storeの履歴は残しRead Modelからは削除する 40
  24. リードモデルへのクエリ @Component public class UserQueryHandler { private final UserDataModelRepository repository;

    // コンストラクタは省略 } @QueryHandler public FindUserQueryResult handle( FindUserQuery query ) { var data = repository.findById(query.userId()); return new FindUserQueryResult(data); } FindUserQueryはuserIdを保持する 41
  25. 予約の状態を表す列挙型 ステートマシンの各状態をReservationStatusとして定義する public enum ReservationStatus { TENTATIVE, SLOT_SECURED, CONFIRMED, COMPLETED,

    CANCELLED, } TENTATIVE:仮予約 CONFIRMED:確定 SLOT_SECURED:枠確保済み COMPLETED:完了 CANCELLED:取消 49
  26. 不変条件に基づく集約の境界 予約集約だけにした場合 予約 A 予約 B TENTATIVE SLOT̲SECURED 予約集約と予約枠集約に分ける場合 予約集約

    各予約のstatusを管理 枠確保済み以外は承認しない 予約 C 予約 D CONFIRMED CANCELLED 各予約は自分のstatusだけを持つ 予約枠集約 capacity・確保数を管理 定員を超える確保を拒否 予約枠の定員と確保数は判定できない 即時に守る条件を定めて、その範囲を集約の単位にする 53
  27. 予約実装のクラス図 ReservationAggregateAdapter - reservationId: String - reservation: Reservation + handle(command)

    + on(event) Reservation ReservationSlotAggregateAdapter - slotId: String - slot: ReservationSlot + handle(command) + on(event) ReservationSlot - reservationId / slotId / status - capacity / claimedReservations + request() / from() + applyEvent(event) + claimSlot(reservationId) + applyEvent(event) 56
  28. 申込から承認までの処理の全体像 予約と予約枠を別々に更新し 確保結果を予約へ反映して確保済みだけを承認する TENTATIVE 1 仮予約の登録 Reservation.request 2 予約枠の確保 ReservationSlot.claimSlot

    確保結果を記録 3 確保結果の反映 Reservation.secureSlot Reservation.failRequest SLOT_SECURED CANCELLED 4 主催者の承認 Reservation.approve CONFIRMED 57
  29. 仮予約登録の処理順 申込イベントの記録とTENTATIVEへのリプレイ RequestReservationCommand 1 申込の入力を受け取る 2 参加者IDと予約枠IDを検証する Reservation.request 3 申込が成立した事実を記録する

    ReservationRequestedEvent 4 仮予約としてイベントをリプレイする Reservation.from → TENTATIVE TENTATIVEは枠確保と主催者承認の前の状態 59
  30. ReservationAggregateAdapterのCommand受付 @Aggregate public class ReservationAggregateAdapter { @AggregateIdentifier private String reservationId;

    private Reservation reservation; protected ReservationAggregateAdapter() {} @CommandHandler public ReservationAggregateAdapter(RequestReservationCommand command) { AggregateLifecycle.apply( Reservation.request( command.reservationId(), command.participantId(), command.slotId() ) ); } // 確保結果の反映‧取消‧承認などのCommand Handlerは省略 } 60
  31. 申込の記録としてのEvent 成立した申込を過去形のイベントとして定義する public record ReservationRequestedEvent( String reservationId, String participantId, String

    slotId ) implements ReservationEvent { } approvedByなど未実施の操作の情報は持たない 集約のリプレイとRead Model更新に同じEventを使う 62
  32. Reservation.requestによる申込イベントの⽣成 public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { // 他のメソッドは省略 } public static ReservationRequestedEvent request( String reservationId, String participantId, String slotId ) { if (participantId == null || participantId.isBlank()) { throw new IllegalArgumentException("参加者IDは必須です"); } if (slotId == null || slotId.isBlank()) { throw new IllegalArgumentException("予約枠IDは必須です"); } return new ReservationRequestedEvent( reservationId, participantId, slotId ); } 検証を通過した申込だけをReservationRequestedEventとして返す 63
  33. ReservationAggregateAdapterのイベント適⽤ @Aggregate public class ReservationAggregateAdapter { @AggregateIdentifier private String reservationId;

    private Reservation reservation; // Command Handlerは省略 } @EventSourcingHandler public void on(ReservationEvent event) { if (event instanceof ReservationRequestedEvent e) { this.reservationId = e.reservationId(); this.reservation = Reservation.from(e); } else { this.reservation = reservation.applyEvent(event); } } 64
  34. Reservation.fromによる仮予約のイベント適⽤ public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { // 他のメソッドは省略 } public static Reservation from(ReservationRequestedEvent event) { return new Reservation( event.reservationId(), event.slotId(), event.participantId(), ReservationStatus.TENTATIVE ); } 申込イベントから各項⽬とTENTATIVEを持つ予約を⽣成する 65
  35. ReservationSlotAggregateAdapterのCommand受付 @Aggregate public class ReservationSlotAggregateAdapter { @AggregateIdentifier private String slotId;

    private ReservationSlot slot; protected ReservationSlotAggregateAdapter() {} @CommandHandler public void handle(ClaimSlotCommand command) { slot.claimSlot(command.reservationId()) .ifPresent(AggregateLifecycle::apply); } // Event Sourcing Handlerは省略 } Optionalに結果があるときだけEventを発⾏する 68
  36. 重複予約IDに対するイベント⽣成の抑⽌ public record ReservationSlot( String slotId, int capacity, Set<String> claimedReservations

    ) { // 省略 } public Optional<ReservationSlotEvent> claimSlot(String reservationId) { if (claimedReservations.contains(reservationId)) { return Optional.empty(); } return claimAvailableSlot(reservationId); } Optional.emptyは新しいイベントなしを表す 70
  37. 残り定員に応じた確保と満員の返却 public record ReservationSlot( String slotId, int capacity, Set<String> claimedReservations

    ) { // 省略 } private Optional<ReservationSlotEvent> claimAvailableSlot( String reservationId ) { if (remaining() <= 0) { return Optional.of( new SlotClaimFailedEvent(slotId, reservationId) ); } return Optional.of( new SlotClaimedEvent(slotId, reservationId) ); } 満員と確保のどちらも結果イベントとして記録する 71
  38. Reservation.secureSlotによる確保済みへの遷移判定 public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { // 他のメソッドは省略 } public Optional<ReservationSlotSecuredEvent> secureSlot() { if (status == ReservationStatus.CANCELLED) { return Optional.empty(); } if (status != ReservationStatus.TENTATIVE) { throw new IllegalStateException( "仮予約以外は確保済みへ変更できません" ); } return Optional.of( new ReservationSlotSecuredEvent(reservationId) ); } 仮予約だけを確保済みへ変更し、取消済みならOptional.emptyを返す 72
  39. Reservation.failRequestによる失敗判定 public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { // 他のメソッドは省略 } public Optional<ReservationRequestFailedEvent> failRequest( String reason ) { if (status == ReservationStatus.CANCELLED) { return Optional.empty(); } if (status != ReservationStatus.TENTATIVE) { throw new IllegalStateException("仮予約以外は失敗にできません"); } return Optional.of( new ReservationRequestFailedEvent(reservationId, slotId, reason) ); } 仮予約だけを失敗イベントへ変え、CANCELLEDへの遅延指⽰はOptional.emptyを返す 73
  40. 確保結果のイベントの適⽤ public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { // 他のメソッドは省略 } public Reservation applyEvent(ReservationEvent event) { return switch (event) { case ReservationRequestedEvent e -> from(e); case ReservationSlotSecuredEvent _ -> withStatus(ReservationStatus.SLOT_SECURED); case ReservationRequestFailedEvent _ -> withStatus(ReservationStatus.CANCELLED); default -> throw new IllegalArgumentException(); }; } 確保成功ならSLOT_SECURED、確保失敗ならCANCELLEDへ遷移する 74
  41. ReservationAggregateAdapterの承認Command受付 @Aggregate public class ReservationAggregateAdapter { @AggregateIdentifier private String reservationId;

    private Reservation reservation; @CommandHandler public void handle(ApproveReservationCommand command) { AggregateLifecycle.apply( reservation.approve(command.approvedBy()) ); } // Event Sourcing Handlerでreservationをリプレイ } リプレイ済みのreservationに対してapproveを呼び出す 77
  42. Reservation.approveによる承認判定 public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { // 省略 } public ReservationApprovedEvent approve(String approvedBy) { if (status != ReservationStatus.SLOT_SECURED) { throw new IllegalStateException("枠確保済み以外は承認できません"); } return new ReservationApprovedEvent(reservationId, approvedBy); } 枠確保済みのときだけ承認イベントを返す 78
  43. 承認‧取消‧完了の適⽤ public record Reservation( String reservationId, String slotId, String participantId,

    ReservationStatus status ) { public Reservation applyEvent(ReservationEvent event) { return switch (event) { case ReservationApprovedEvent _ -> withStatus(ReservationStatus.CONFIRMED); case ReservationRejectedEvent _ -> withStatus(ReservationStatus.CANCELLED); case ReservationCancelledEvent _ -> withStatus(ReservationStatus.CANCELLED); case ReservationCompletedEvent _ -> withStatus(ReservationStatus.COMPLETED); default -> throw new IllegalArgumentException(); }; } } 79
  44. 複数集約にまたがる進⾏管理の課題 予約・予約枠の更新は別トランザクションなので処理の途中状態が残る 予約集約 枠確保の 指示 予約枠集約 確保結果の 反映 予約集約 申込イベントを記録

    枠確保を実行 確保結果を反映 status = TENTATIVE 成功・失敗を記録 確保済みまたは取消 各集約は自分の更新を守れるが、全体の進行と中断後の再開は担わない 申込のあと、誰が次のCommandを送り、確保結果を予約へ返すのか 81
  45. ReservationSagaの開始 @Saga public class ReservationSaga { @Inject private transient CommandGateway

    commandGateway; private String reservationId; private String slotId; @StartSaga @SagaEventHandler(associationProperty = "reservationId") public void on(ReservationRequestedEvent event) { this.reservationId = event.reservationId(); this.slotId = event.slotId(); commandGateway.send( new ClaimSlotCommand(slotId, reservationId) ); } // 確保結果のEvent Handlerは省略 } 申込イベントで進⾏状態を作り予約枠へClaimSlotCommandを送る 85
  46. 確保結果に応じたCommand送信とSaga終了 @Saga public class ReservationSaga { // フィールドと開始Event Handlerは省略 @EndSaga

    @SagaEventHandler(associationProperty = "reservationId") public void on(SlotClaimedEvent event) { commandGateway.send(new SecureReservationCommand(reservationId)); } } @EndSaga @SagaEventHandler(associationProperty = "reservationId") public void on(SlotClaimFailedEvent event) { commandGateway.send( new FailReservationRequestCommand(reservationId, "満員") ); } 成功は確保済みへの反映‧失敗は取消へ進めて進⾏状態を終了する 86
  47. イベントストーミングで業務の出来事を洗い出す 過去形のイベントを時間軸に並べ 関係者と順序と例外を確かめる 正常な流れ 予約が 申し込まれた 枠が 確保された 満員なら 枠の確保に失敗した

    予約が 承認された 予約が 完了した 参加者が取り消すと 予約がキャンセルされた 出来事の名前と順序から 操作・登場物・例外の論点が見える 90
  48. 真の不変条件から集約の境界を決める 操作の完了時に一緒に守る状態を集め 変更の単位を決める 予約集約 保持する状態 各予約のstatus 予約枠集約 保持する状態 枠確保の結果 真の不変条件

    枠確保済みの 予約だけを承認 定員・確保数 確保済みの予約ID 真の不変条件 確保数は定員以下 同じ予約IDで 二重確保しない 別々の集約に分けた範囲は Sagaで最終的な一致を進める 94
  49. 不変条件とは別のRead Model反映遅延 予約枠の更新が完了しても画面の空き数はイベント反映まで古いまま Command完了直後 イベント反映後 • • • • •

    • 予約枠の空き状況 12月20日 10:00 Eventを 購読 予約枠の空き状況 12月20日 10:00 残り 1 / 1 残り 0 / 1 Read Modelは更新前 SlotClaimedEventを反映 91
  50. 対処:予約枠集約による最終可否の判定 画面の空き数は参考値にとどめCommand側の現在状態と不変条件で判定する PC画面 残り 1 / 1 Read Modelの参考値 予約を

    申し込む ReservationSlot capacity = 1 claimedReservations = 1 確保できない SlotClaimFailed Event 確保数 < 定員を判定 画⾯の表⽰値ではなくCommand実⾏時の集約状態で最終可否を判定する 予約枠の不変条件はReservationSlotが守る 93
  51. DB更新後にAckだけが失敗 Read ModelのDB更新はコミット済みだが完了通知・AckだけがPublisherへ届かない Event Publisher E-104の完了を待つ ① 初回配送 E-104 Projection

    E-104を処理 ② 予約数 +1 Read Model DB 予約数 10 → 11 コミット成功 ③ AckをPublisherへ返す Ackだけが失敗・消失 DBは予約数11のままだが、配送側には処理完了が伝わらない 95
  52. 同じeventIdの再配送で⼆重加算 未完了と判断されたE-104が再度Projectionへ届き、予約数をもう一度増やす Event Publisher 再配送 E-104 Projection 再び予約数 +1 同じE-104を再処理

    E-104を再配送 Read Model DB 予約数 11 → 12 ⼆重加算 配送順 eventId Read Modelの更新 予約数 初回 E-104 予約数 +1 10 → 11 再配送 E-104 予約数 +1 11 → 12 96
  53. 対処: 処理済みイベントIDによる⼆重加算の防⽌ 処理済みイベントIDで再配送を判定し初回のID登録と集計を原子化する 初回‧再配送とも eventId = E-104 processed_eventを Read Model

    DBで照会 未処理 同一トランザクション processed_eventに E-104をINSERT E-104は登録済みか 処理済み reservation_summaryを 予約数 +1で更新 上書きで済む更新は同じ値を再設定 累積処理は処理済みIDと集計を 同一トランザクションで保存 予約数は更新しない Ackを返して再配送を終了 97
  54. 対処: 例外の再送出による更新のロールバック 例外を再送出してRead Modelと処理位置を同じトランザクションで戻す E-105の同⼀トランザクション Read Model更新 Tracking Token更新 DB例外で失敗

    処理位置を105へ進める処理 例外を再送出 Read Modelと処理位置を両⽅ロールバック E-104の状態へ戻す 処理位置もE-104へ戻るため⼀時障害の回復後にE-105を再処理できる 103
  55. 対処: DLQの利⽤(処理できないイベントの隔離領域) 再試行しても処理できないイベントを失敗情報とともに保持する仕組み DLQ(Dead Letter Queue)=隔離領域 通常処理 E-104 → E-106

    通常のイベントを継続処理 E-105 再試⾏してもDB更新に失敗 隔離 eventId E-105 payload ReservationApprovedEvent exception SQLException: value too long 処理位置 E-104(最後に成功) retryCount 3 通常の処理位置とは別に失敗情報を保持し原因調査と再処理に使う 105
  56. 再試行で回復しないイベントのDLQ隔離 E-105だけを隔離し、 他の集約のイベントは通常どおり処理を進める 通常処理 E-104 処理成功 E-105 再試⾏上限 DLQ:E-105を保持 eventId‧aggregateId‧exception

    通常処理からは外す E-106 他の集約を処理 E-107 通常処理を継続 原因を修正 コード・DBなど 処理位置は処理グループ(セグメント)ごとに管理 再処理では集約内の順序も確認する → … 修正後にE-105を再処理 Read Modelへ反映 106
  57. Read Model再構築で対処できること イベント履歴からRead Modelを作り直し破損からの回復と新しい表⽰要件に対応する Event Store E-101 E-102 E-103 …

    全イベント履歴 既存Read Modelを作り直す Read Model 再構築 破損からの回復 イベントを順に適用 新しいRead Modelを追加する 新しい表⽰要件への対応 現在のRead Modelを再投⼊するのではなくイベント履歴から再計算する 109
  58. Read Model DBの参照先切替 再構築用テーブルが最新の処理位置へ追いついたら参照先を切り替える Read Model DB reservation_view reservation_view_v2 旧テーブル

    切替後は参照しない 再構築用テーブル 最新位置まで反映済み tracking_token = 最新のイベント位置 旧参照を終了 Query Handler 画面・APIからの参照 追従を確認して 新テーブルへ切替 旧テーブルは切替が完了するまで参照を維持する 110
  59. ResetHandlerによるRead Modelの初期化 リビルド開始前にRead Modelをクリアする @Component @ProcessingGroup("user-projection") public class UserProjection {

    private final UserDataModelRepository repository; // イベントハンドラは省略 } @ResetHandler public void reset() { repository.deleteAll(); } resetTokensの内部でリビルド開始時に⼀度だけ呼び出される 112
  60. resetTokensによるリビルドの開始 @Service public class ProjectionManagementService { private final EventProcessingConfiguration config;

    // 省略 } public void resetUserProjection() { config.eventProcessorByProcessingGroup("user-projection", StreamingEventProcessor.class).ifPresent(processor -> { processor.shutDown(); processor.resetTokens(); processor.start(); }); } resetTokensはResetHandlerの呼出とReplayTokenへの置換を⾏う 113
  61. リプレイ時の外部通知の再送信 Read Model再構築で過去の承認イベントを再生すると通知も再送信される ReservationNotificationHandler @EventHandler 過去のE-104 public void on( ReservationApprovedEvent

    e) { Reservation ApprovedEvent reservationView.save(...); notificationClient.send(...); } 再構築でもこのメソッドを再実⾏ Read Modelを 作り直す → 必要 外部通知を 再送信 → ⼆重送信 再構築ではRead Model更新を再実行し外部通知は通常配信時だけに限定する 114
  62. Read Model更新と外部通知の処理グループ分離 再構築の対象をRead Model用の処理グループだけに限定する reservation-projection notification リプレイ対象 リプレイ対象外 Read Modelを更新

    通常の新着イベントだけで通知 resetTokensで履歴からリプレイ 処理位置はリセットしない resetTokensで巻き戻すのは reservation-projection だけ 115
  63. どうしても同⼀ハンドラであるときはReplayStatus判定 Read Model更新と外部通知が同じハンドラにある場合はリプレイ中かを判定する @Component public class ReservationNotificationHandler { // 省略

    } @EventHandler public void on( ReservationApprovedEvent event, ReplayStatus replayStatus ) { // Read Modelを更新 if (!replayStatus.isReplay()) { // 外部通知を送信 } } 116
  64. 長いイベント列による集約ロード時間 Commandのたびに同じ履歴を先頭からリプレイする Command 1 ロード 次の申込を1件追加 適用 E1からE10,000までをロード 申込を1件追加 Command

    2 Event Store ロード Event Store ReservationSlot 10,000件をリプレイ 適用 E1からE10,001までをロード ReservationSlot 10,001件をリプレイ 履歴が増えるほど、リプレイの読込量と適用回数が増える 118
  65. 全履歴を⾼速ストレージへ保持する費⽤ 参照頻度の低い古いイベントも同じデータベースに増え続ける 高速なEvent Store用ストレージ 2024 過去イベント 120万件 2025 過去イベント 480万件

    2026 過去イベント 1,200万件 容量が増加 古い履歴も同じ単価 参照頻度に関係なく 容量費用が増える 最近のイベントと滅多に読まない履歴を同じ保存条件で扱っている 121
  66. 保存済みイベントと新しいイベント定義の不⼀致 項目名の変更や必須項目の追加で古いイベントを復元できない 保存済みイベント { "password": "..." } 項目名が 違う 必須項目が

    不足 新しいイベント定義 record UserRegisteredEvent( String passwordHash, LocalDate birthDate ) {} 古いJSONにはpasswordHashとbirthDateがなく、そのままでは新定義へ変換できない 126
  67. イベント定義変更の内容による対処⽅法 変更例 任意項目の追加 項目名や 必須項目の変更 複雑な再構成 方式 Weak Schema (Optional項目の追加)

    @RevisionとUpcaster Copy-and-Transform 保存済みイベントの扱い そのまま読み込む 読み込み時に 新しい表現へ変換 新しいストアへ 変換して書き出す 127
  68. 対処:Upcasterによる保存済みイベントの変換 読み込み時に古い表現を新しい表現へ変換する 保存済み v1 Upcaster アプリケーション v2 password 誕生日なし passwordを

    passwordHashへ変換 passwordHash 誕生日あり payloadRevision = 1.0 誕生日を補完 保存データは不変 保存済みイベントを書き換えずに読み込み時の表現を変える birthDateの仮値は不明を示し年齢確認には使わない 128
  69. Upcasterによる対象リビジョンの判定 @Component public class UserRegisteredEventUpcaster extends SingleEventUpcaster { private static

    final SimpleSerializedType TARGET_TYPE = new SimpleSerializedType( UserRegisteredEvent.class.getTypeName(), "1.0" ); @Override protected boolean canUpcast( IntermediateEventRepresentation representation ) { return representation.getType().equals(TARGET_TYPE); } // doUpcastは省略 } revision 1.0のUserRegisteredEventだけを変換対象にする 129
  70. Upcasterによるシリアライズ形式の変換 public class UserRegisteredEventUpcaster extends SingleEventUpcaster { // canUpcastは省略 }

    @Override protected IntermediateEventRepresentation doUpcast( IntermediateEventRepresentation representation ) { return representation.upcastPayload( new SimpleSerializedType( TARGET_TYPE.getName(), "2.0" ), JsonNode.class, this::convert ); } upcastPayloadでrevision 2.0へ変換しJsonNodeを加⼯する 130
  71. Upcasterによる項⽬名の変更と必須項⽬の補完 @Component public class UserRegisteredEventUpcaster extends SingleEventUpcaster { // canUpcastとdoUpcastは省略

    } private JsonNode convert(JsonNode event) { ObjectNode object = (ObjectNode) event; object.set("passwordHash", object.get("password")); object.remove("password"); object.put("birthDate", "1900-01-01"); return object; } passwordをpasswordHashへ変更しbirthDateは例として1900-01-01を補完 131
  72. 追記専⽤イベントに残る個⼈情報 メールアドレスや住所をイベントに含めると過去の履歴にも残る E-101 予約を登録 email = [email protected] [email protected] も履歴に残る E-102

    予約を承認 個⼈情報は変更なし 最新値への訂正を追記 E-105 メールアドレスを訂正 email = [email protected] 新しい値を追記しても、過去のE-101は変更されない 133
  73. 対処:個⼈情報の暗号化とCrypto-Shredding イベント内の個人情報を暗号化し削除要求時には復号不能にする Event Store userId = user-123 keyId = user-123

    encryptedEmail = 8f2... encryptedAddress = 91a... 暗号化した個人情報は履歴に残る 復号に利用 暗号鍵ストア user-123 → 復号鍵 削除要求時に復号鍵を削除 暗号文は残っても鍵がなければ個人情報を復号できない 136
  74. 複数システムにまたがる障害箇所の特定 予約承認後に通知が届かず、どのシステムで止まったか分からない 予約APIのログ 10:15:01 通知APIのログ 予約を承認 ? reservationId = R-42

    イベントハンドラのログ 10:15:02 通知処理を開始 ? 10:15:03 送信に失敗 status = 503 eventId = E-105 共通のtraceIdがなく、R-42‧E-105‧通知失敗を 同じ予約の記録として結べない 138
  75. 対処:相関IDによる複数システムの記録の追跡 同じcorrelationIdをコマンド・イベント・ログへ引き継ぐ 予約API 予約イベント 通知ハンドラ メール送信 correlationId C-904 metadata C-904

    処理ログ C-904 送信結果 C-904 AxonではCommandからEventのメタデータへ相関IDを引き継ぐ 追跡用の項目をドメインモデルへ混ぜず純粋性を保つ イベントハンドラと外部APIのログにも同じIDを残す 集約内の順序はaggregateSequenceNumberで確認する 139
  76. 既存システムからの移⾏⼿順 現在状態の 取り込み 移行時点の状態を 移行イベント化 変更の接続 結果の照合 書き込みの 切り替え Transactional

    Outboxを使う デュアルライト 状態・金額など 同じ意味の項目を 照合する コマンドの受付を 一方のシステムに 限定する 現在値しか残っていない時期の経緯を推測でイベント化しない 142
  77. 移⾏イベントと通常イベントの区別 移行後の通常イベント 移行前 ReservationMigratedEvent 現在値だけが残り 過去の操作順や 操作者を復元できない 移行時点の現在状態を保持 ReservationCancelledEvent status

    = CONFIRMED 実際に発生した変更だけを source = legacy-reservation 移行イベントの後へ追記 移行前の承認日時や操作者が不明ならReservationApprovedEventを推測で作成しない 143
  78. CQRSの非同期処理に伴うクライアント負担 Command受付とRead Model反映が非同期に進み 完了確認・再取得・再試行がクライアントの担当になる POST Command クライアント Web API 処理IDを保持

    完了を繰り返し確認 タイムアウトと再試行 完了後に再取得 Commandを受付 202 Accepted +処理ID CQRS+ESサーバ Command受付 非同期に進行 Projection反映 状態を繰り返し取得 処理IDとポーリングの状態を画面側で管理する 144
  79. WebFluxによる同期HTTPへの変換 サーバ側で非同期処理の完了をノンブロッキングに待ち クライアントには通常の同期HTTPとして応答する HTTP POST クライアント WebFlux API 通常の同期HTTP CompletionStageの完了を

    ポーリング不要 ノンブロッキングに待ち 同期HTTPで応答 201 Created +最新の予約 Command 非同期処理 Event Store Projection Read Model 処理完了 クライアントは処理IDの保持・完了確認・再試行の状態管理を行わない 146
  80. PROFILE nrs / 成瀬允宣 プログラマ Title 株式会社ドットロフト代表取締役 Findy Freelance顧問 /

    Kimi Ambassador NOW OSS「TAKT」 / CooSenpAI / その他 AI プロダクト BOOK 『ドメイン駆動設計入門 ボトムアップでわかる!ドメイン駆動設計の基本』 『CQRS+ES実践ガイドイベント駆動型モデリング/システム構築手法』 HOBBY カンファレンス講演 / 写真 / 経営学 LINKS X @nrslib / GitHub @nrslib / Web nrslib.com

More Decks by nrs

Other Decks in Programming