Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Using Akka Cluster for a payment service

Using Akka Cluster for a payment service

ScalaMatsuri 2019

Akka Cluster を採用した決済サービスをリリースしました。このセッションでは、Akka Cluster を使った開発で苦労した点や、従来の RDB を用いた CRUD ベースのシステムから、どのようにしてアクターモデルやイベントソーシング・CQRS といったモデルを用いたシステムへと変化させたのかなど、本プロジェクトで Akka Cluster を採用するにあたり我々が取り組んだ内容について話します。

Kazuki Negoro

June 28, 2019
Tweet

More Decks by Kazuki Negoro

Other Decks in Technology

Transcript

  1. Using Akka Cluster
    for a payment service
    © 2019 TIS Inc.
    決済サービスで Akka Cluster 使ってみた
    1 / 73

    View Slide

  2. Who am I ?
    Kazuki Negoro
    TIS Inc.
    Technology & Enginnering Center
    Mission
    Provide High Availability System
    at a low cost
    @negokaz negokaz
    © 2019 TIS Inc.
    根来 和輝
    TIS株式会社 テクノロジー&エンジニアリングセンター
    2 / 73

    View Slide

  3. I ll talk about...
    Technical story of
    TIS Participates in Demonstration Trial of QR Payment
    Using High Availablity and High Throughput Software
    Stack Lerna - Applied to Omotenashi Platform for
    foreigh tourists visiting Japan -
    © 2019 TIS Inc.
    TIS、高可用・高スループットのソフトウェアスタック「Lerna」
    を活用したQR決済の実証実験に参画
    ~ 訪日外国人観光客向け「おもてなしプラットフォーム」に適用 ~
    今日話すこと
    2019/3/27 ニュースリリースの技術的な裏側
    3 / 73

    View Slide

  4. Omotenashi Platform
    A measure promoted by Ministry of Economy to increase
    the satisfication of foreign tourists.
    QR code payment service
    sightseeing information service
    etc...
    © 2019 TIS Inc.
    withJorge - Japan Omotenashi concieRGE
    経済産業省が推進する、訪日外国人の満足度を高めるための施策
    QRコード決済や観光情報提供などのサービスが受けられる
    4 / 73

    View Slide

  5. Akka
    Apache Cassandra
    MariaDB
    Keepalived
    HAProxy
    What is Lerna ?
    A Software Stack for
    High Availablity and High Throughput
    (Reactive System) which is promoted by TIS
    © 2019 TIS Inc.
    Lerna とは何か? TIS が推進している高可用・高スループットを
    実現するためのソフトウェアスタック
    5 / 73

    View Slide

  6. Application Architecture of Lerna
    Event Sourcing + CQRS
    Akka Persistence
    Akka Persistence Query
    Akka Cluster Sharding
    © 2019 TIS Inc.
    Lerna のアプリケーションアーキテクチャ
    6 / 73

    View Slide

  7. Omotenashi Platform Project
    © 2019 TIS Inc. 7 / 73

    View Slide

  8. Project Context
    CRUD version released first
    Reconstructs main features of the system with Lerna
    Needs data migration
    © 2019 TIS Inc.
    CRUD構成版を先行リリース。システムの主要機能部分を再構築。
    データ移行が必要。
    8 / 73

    View Slide

  9. System Overview
    Makes consumers who visit a shop can make payment
    with QR code
    QR-Server
    Consumer
    Merchant
    AgencyPayment
    © 2019 TIS Inc.
    システム概要
    店舗に訪れた顧客がQRコードで決済できるようにする
    9 / 73

    View Slide

  10. Main features of the system
    QR Payment +
    Payment history confirmation
    Cancelling payment
    © 2019 TIS Inc.
    システムの主要機能はQRコード決済、決済履歴確認、
    決済キャンセル。
    10 / 73

    View Slide

  11. Main features of the system
    QR Payment +
    Payment history confirmation
    Cancelling payment
    Reconstructed these features with Akka Cluster
    Sharding and EC + CQRS
    © 2019 TIS Inc.
    システムの主要機能はQRコード決済、決済履歴確認、
    決済キャンセル。
    これら主要機能を Lerna の構成にリプレース。
    11 / 73

    View Slide

  12. Payment process
    Consumer Merchant
    QR-Server
    GenQRCode
    QRCode
    Payment
    resultofpayment
    QRCode
    ReadQRCode
    Notification
    © 2019 TIS Inc.
    決済の手順
    12 / 73

    View Slide

  13. Payment cancellation process
    Consumer Merchant
    QR-Server
    Paymenthistory
    Cancel
    Getpaymenthistory
    resultofcancellation
    © 2019 TIS Inc.
    決済キャンセルの手順
    13 / 73

    View Slide

  14. System Archtecture
    © 2019 TIS Inc. 14 / 73

    View Slide

  15. Server-side without Lerna
    QR-Server
    WebApplicationServer MySQL
    ・Payment
    ・User Management
    ・System Administration
    © 2019 TIS Inc.
    Lerna を適用する前のサーバーサイドのシステム構成
    15 / 73

    View Slide

  16. Server-side with Lerna
    QR-Server
    WebApplicationServer
    ・User Management
    ・System Administration
    ・Payment
    WebApplicationServer
    © 2019 TIS Inc.
    Lerna を適用したサーバーサイドのシステム構成
    16 / 73

    View Slide

  17. Application Architecture
    © 2019 TIS Inc. 17 / 73

    View Slide

  18. Application Architecture
    Event Sourcing + CQRS
    Akka Persistence
    Akka Persistence Query
    Akka Cluster Sharding
    © 2019 TIS Inc.
    アプリケーションアーキテクチャ
    18 / 73

    View Slide

  19. Why is this architecture needed ?
    RDBMS makes it difficult to scale writes
    Using ES + CQRS makes writing easier to scale
    © 2019 TIS Inc.
    RDBMSは書き込みがボトルネックになりやすい
    ES + CQRS を使って書込・読込の両方をスケールできるように
    19 / 73

    View Slide

  20. Event Sourcing ?
    Persist events produced inside a system
    Only INSERT events to datastore
    Account No:10Opened
    Event System State
    ¥2,000Withdrew
    No:10, Balance:¥18,000
    ¥10,000Deposited
    ¥10,000Deposited
    © 2019 TIS Inc.
    システムの中で起きたイベントを永続化
    イベントをデータストアに INSERT だけする
    20 / 73

    View Slide

  21. Pros of Event Sourcing
    Events is immutable
    No need lock・Can write data to multi nodes
    Easy to scale for to write data
    Easy to caching, copying, sharing
    Easy to scala for to read data, too
    © 2019 TIS Inc.
    イベントは不変なのでロック不要で複数のノードに分散書き込み
    が可能。複製も容易なので読み込みもスケール可能。
    21 / 73

    View Slide

  22. Cons of Event Sourcing
    Summarizing data is expensive
    © 2019 TIS Inc.
    データの集計や一覧を作るのにコストがかかる
    CQRSでこの問題を解決
    22 / 73

    View Slide

  23. Cons of Event Sourcing
    Summarizing data is expensive
    CQRS solves it
    © 2019 TIS Inc.
    データの集計や一覧を作るのにコストがかかる
    CQRSでこの問題を解決
    23 / 73

    View Slide

  24. CQRS ?
    Command and Query Responsibility Segregation
    Separate Command(reads) and Query(writes)
    Command
    Query
    Command
    Query
    © 2019 TIS Inc.
    コマンドクエリ責務分離
    コマンド(書き込み)とクエリ(読み込み)を分離
    24 / 73

    View Slide

  25. Pros of CQRS
    Command
    Query
    Command
    Query
    different Database and models
    Command-side uses Event Sourcing.
    Persist on the Query-side in a form easy to sum and list
    © 2019 TIS Inc.
    コマンドとクエリで異なるDB・データ構造が使える。
    クエリサイドには集計や一覧しやすい形で永続化する。
    25 / 73

    View Slide

  26. Cons of CQRS
    Query-Side is updated asynchronus
    There is NO strong consistency between
    Command-Side and Query-Side
    However, sometime it will be updated:
    eventual consistency
    © 2019 TIS Inc.
    クエリサイドへの反映は非同期のためコマンドサイドの
    更新は遅れてクエリサイドに反映される(結果整合性)
    26 / 73

    View Slide

  27. Cons of CQRS
    Query-Side is updated asynchronus
    There is NO strong consistency between
    Command-Side and Query-Side
    However, sometime it will be updated:
    eventual consistency
    Need to design the system or business so that we dont
    have to worry about temporary inconsistencies
    © 2019 TIS Inc.
    クエリサイドへの反映は非同期のためコマンドサイドの
    更新は遅れてクエリサイドに反映される(結果整合性)
    一時的に一貫性が取れていなくても問題ないように
    ビジネスやシステムを設計する必要がある
    27 / 73

    View Slide

  28. Not always acceptable eventual consistency
    Can not withdraw if the balance is not enough
    Only one person can reserve a seat
    One-time password can only be used once
    ...
    © 2019 TIS Inc.
    あらゆる場面で結果整合性を許容できるわけではない
    28 / 73

    View Slide

  29. Not always acceptable eventual consistency
    Can not withdraw if the balance is not enough
    Only one person can reserve a seat
    One-time password can only be used once
    ...
    Need to look the latest state without delay
    to realize these requirements
    © 2019 TIS Inc.
    あらゆる場面で結果整合性を許容できるわけではない
    これらの要求を実現するには、
    遅延無く最新の状態を確認できる必要がある
    29 / 73

    View Slide

  30. How to look latest state
    Akka Persistence makes Actor to be able to persist events
    and look latest state (as self state)
    Account No:10Opened
    Event ActorState
    ¥2,000Withdrew
    No:10, Balance:¥18,000
    ¥10,000Deposited
    ¥10,000Deposited
    © 2019 TIS Inc.
    Akka Persistence によって Actor はイベントの永続化と
    (それ自身の状態として)最新の状態の確認が可能になる
    30 / 73

    View Slide

  31. How to look latest state
    Akka Persistence makes Actor to be able to persist events
    and look latest state (as self state)
    Account No:10Opened
    Event ActorState
    ¥2,000Withdrew
    No:10, Balance:¥18,000
    ¥10,000Deposited
    ¥10,000Deposited
    © 2019 TIS Inc.
    Akka Persistence によって Actor はイベントの永続化と
    (それ自身の状態として)最新の状態の確認が可能になる
    Such an Actor
    as has ID and states
    is called Entity
    このように識別子と状態を持つアクターは Entity と呼ばれる
    31 / 73

    View Slide

  32. ES + CQRS Overview of Akka
    Command-Side
    Query-Side
    Event
    Store
    ReadModelUpdater
    Polling
    UpdateState
    Command
    Query
    APICall
    APICall
    Entity
    Entity
    Query
    Store
    Entity
    Controller
    © 2019 TIS Inc.
    Akka を用いた ES + CQRS の概要
    32 / 73

    View Slide

  33. Important point of Entity
    An Entity which has the ID must exists only one place
    Having one entity in multiple location cases inconsistency
    ID:1 ID:1
    amount:10 amount:11
    © 2019 TIS Inc.
    ある ID の Entity が存在していいのは 1 箇所でだけ
    複数箇所に存在するとデータの整合性が崩れる
    33 / 73

    View Slide

  34. Scale Command-Side safely
    © 2019 TIS Inc.
    コマンドサイドを安全にスケールさせるには
    34 / 73

    View Slide

  35. Scale Command-Side safely
    Akka Cluster Sharding
    © 2019 TIS Inc.
    コマンドサイドを安全にスケールさせるには
    35 / 73

    View Slide

  36. Scale Command-Side safely
    Akka Cluster Sharding
    Feature for load balancing
    Can distribute entities across several servers
    Guarantee that there is at most one entity in the
    cluster
    No single point of failure
    © 2019 TIS Inc.
    コマンドサイドを安全にスケールさせるには
    負荷分散の仕組み。複数のサーバーに Entity を分散できる
    各 Entity は高々1つだけ存在することが保証される。SPOFなし
    36 / 73

    View Slide

  37. Our experience
    © 2019 TIS Inc.
    私たちが経験したこと
    37 / 73

    View Slide

  38. Decide where apply ES + CQRS to
    There is not many enginner who can use Scala/Akka
    Need many cost to change data model and paradigm
    Which do features need high availability and
    high throughput ?
    © 2019 TIS Inc.
    Scala/Akka のエンジニアが多いわけではない。
    データモデルとパラダイムの変更にはコストがかかる。
    38 / 73

    View Slide

  39. Decide where apply ES + CQRS to
    There is not many enginner who can use Scala/Akka
    Need many cost to change data model and paradigm
    Which do features need high availability and
    high throughput ?
    Apply only to features directly related to payment
    © 2019 TIS Inc.
    Scala/Akka のエンジニアが多いわけではない。
    データモデルとパラダイムの変更にはコストがかかる。
    決済に直接関係する機能にだけ適用
    39 / 73

    View Slide

  40. Consumer Merchant
    QR-Server
    GenQRCode
    QRCode
    Payment
    resultofpayment
    QRCode
    ReadQRCode
    Notification
    Consumer Merchant
    QR-Server
    Paymenthistory
    Cancel
    Getpaymenthistory
    resultofcancellation
    Payment flow
    © 2019 TIS Inc. 40 / 73

    View Slide

  41. Requirements
    Sometime QR code is reused.
    Must not give same QR code multiple transactions at
    the same time.
    Consumer confirms payment progress
    Consumer and Merchant confirm payment history
    Merchant can cancel a payment
    © 2019 TIS Inc.
    QRコードは再利用される。顧客は決済の進捗が確認できる。
    決済履歴が確認できる。店舗は決済をキャンセルできる。
    41 / 73

    View Slide

  42. Explore states of the system
    Where is status updated?(Command-side)
    How does status look from outside?(Query-side)
    © 2019 TIS Inc.
    システムの「状態」を探索。状態が更新される箇所は?
    外部から見える状態は?
    42 / 73

    View Slide

  43. Where is status updated? (Command-side)
    Record QR code usage status and expiration time
    Record the progress of payment
    Record results when payment completed
    Record results when payment canceling completed
    © 2019 TIS Inc.
    状態が更新される箇所はどこか
    43 / 73

    View Slide

  44. How does status look from outside? (Query-side)
    Payment progress notification
    Payment history list
    © 2019 TIS Inc.
    状態が外部からどのように参照されるか
    44 / 73

    View Slide

  45. Define entity
    We found two state of the system
    QR code state
    TokenActor
    Payment transaction state
    TransactionActor
    © 2019 TIS Inc.
    Entity を定義。
    このシステムには2つの状態があることがわかった。
    45 / 73

    View Slide

  46. Decide implimentation methods of Queries
    Payment progress notification
    Reply the state of TransactionActor
    Payment history list
    Aggregate multiple TransactionActor states
    © 2019 TIS Inc.
    クエリの実装方法を決定。通知は TransactionActor の状態を
    返し、履歴一覧は複数の TransactionActor の状態を集約
    46 / 73

    View Slide

  47. Design entities as a state machine
    TokenActor
    Unused InUse
    [???]
    [???]
    © 2019 TIS Inc.
    ステートマシンとして Entity を設計
    47 / 73

    View Slide

  48. Design entities as a state machine
    TransactionActor
    WaitingForReadToken PreparingToPayment WaitingForPaymentExecution
    Finished
    WaitingForPaymentCancellation
    [???]
    [???] [???]
    [???] [???]
    [???][???]
    © 2019 TIS Inc.
    ステートマシンとして Entity を設計
    48 / 73

    View Slide

  49. TokenActor
    To use started
    Expired
    TransactionActor
    Token read
    Payment started
    Payment failed
    Payment completed
    Cancellation started
    ...
    Find events to change state of an entity
    © 2019 TIS Inc.
    エンティティの状態を変更するイベントを分析
    49 / 73

    View Slide

  50. Apply events to state machines
    TokenActor
    Unused InUse
    [Tousestarted]
    [Expired]
    © 2019 TIS Inc.
    ステートマシンにイベントを適用
    50 / 73

    View Slide

  51. Apply events to state machines
    TransactionActor
    WaitingForReadToken PreparingToPayment WaitingForPaymentExecution
    Finished
    WaitingForPaymentCancellation
    [Tokengenerated]
    [Tokenread] [Paymentstarted]
    [Paymentfailed] [Paymentcompleted] [Paymentfailed]
    [Cancellationstarted] [Cancellationcompleted] [Cancellationfailed]
    © 2019 TIS Inc.
    ステートマシンにイベントを適用
    51 / 73

    View Slide

  52. Decide implimentation methods of Queries
    Payment progress notification
    Reply the state of TransactionActor
    Payment history list
    Aggregate multiple TransactionActor states
    © 2019 TIS Inc.
    クエリの実装方法を決定。通知は TransactionActor の状態を
    返し、履歴一覧は複数の TransactionActor の状態を集約
    52 / 73

    View Slide

  53. How to construct payment history list
    TransactionActor knows a payment status.
    However, to simply collect the state of the entity is
    inefficient.
    © 2019 TIS Inc.
    TransactionActor は決済のステータスを知っているが、entity
    の状態を単純に集めるのは非効率
    53 / 73

    View Slide

  54. How to construct payment history list
    Construct payment hisotry list
    from events in Command-side to Query-side
    using akka-persistent-query
    © 2019 TIS Inc.
    Persist on the Query-side in a form easy to sum
    and list

    Command-Side のイベントを元に Query-Side へ
    決済履歴一覧を作成
    54 / 73

    View Slide

  55. How to construct payment history list
    Need to consider about the delay of Query-side updates.
    We can accept the delay because payment history list will
    be visible by user action.
    © 2019 TIS Inc.
    There is NO strong consistency between
    Command-Side and Query-Side

    Query-side への反映には遅延があるため許容できるか要検討。
    決済履歴一覧はユーザー操作によって開かれるため許容できた。
    55 / 73

    View Slide

  56. Reduce the delay until updated Query-side
    The delay is about 10 seconds by default.
    How does the delay affect the business ?
    Can not cancel payment
    Some delay is acceptable, but it is better to update faster
    © 2019 TIS Inc.
    クエリサイドが更新されるまでの遅延を短縮する。キャンセル
    できるようにできるだけ早く反映されるほうが望ましい。
    56 / 73

    View Slide

  57. Use pubsub-notification
    We could reduce the delay by Turning on
    of akka-persistence-cassandra.
    However, this option disabled guarantee to order events
    from multiple entities by time.
    © 2019 TIS Inc.
    akka-persistence-cassandra/reference.conf
    pubsub-notification という設定を有効にして遅延を短縮できた
    が、Entity を跨るイベントの順序が保証されなくなる。
    57 / 73

    View Slide

  58. How to get scalability and availability
    of Command-side
    Distribute TransactionActor and TokenActor across
    several server with Akka Cluster Sharding
    © 2019 TIS Inc.
    Akka Cluster Sharding を使って TransactionActor と TokenActor
    を複数サーバーに分散配置
    58 / 73

    View Slide

  59. Prepare for Split Brain
    A phenomenon in which a cluster is divided into multiple
    parts due to a network failure etc.
    This cause to lose consistency of the data.
    © 2019 TIS Inc.
    ネットワーク障害などによりクラスターが分割され、
    データの一貫性が損なわれたりする現象
    59 / 73

    View Slide

  60. Split Brain in Akka Cluster Sharding
    If split brain occurs in Akka Cluster Sharding, multiple
    Entities with the same ID will be created.
    Consistency is lost because the state of entity is not
    synchronized.
    © 2019 TIS Inc.
    Akka Cluster Sharding で Split Brain が発生すると同じ ID の
    Entity が複数生まれてしまい、一貫性が維持できなくなる
    60 / 73

    View Slide

  61. Split Brain in Akka Cluster Sharding
    Akka Cluster Shardings auto failover is disabled by
    default, which prevents Split Brain.
    But it will lower the availability.
    © 2019 TIS Inc.
    Akka Cluster Sharding の自動フェイルオーバーは Split Brain
    を防ぐためデフォルトで無効になっている。
    61 / 73

    View Slide

  62. Split Brain Solutions for Akka Cluster
    Split Brain Resolver (Lightbend: Akka Commercial Addons)
    TanUkkii007/akka-cluster-custom-downing
    mbilski/akka-reasonable-downing
    Stop one or all of the split clusters due to network failure
    to prevent data inconsistency.
    © 2019 TIS Inc.
    akka-cluster スプリットブレインリゾルバ OSS実装一覧 - Qiita
    ネットワーク障害によって分裂したクラスターの片方か、
    もしくは全てを停止させてデータの一貫性が崩れるのを防ぐ
    62 / 73

    View Slide

  63. Split Brain Solutions for Akka Cluster
    Split Brain Resolver (Lightbend: Akka Commercial Addons)
    TanUkkii007/akka-cluster-custom-downing
    mbilski/akka-reasonable-downing
    Stop one or all of the split clusters due to network failure
    to prevent data inconsistency.
    The stop fire an failover of entities.
    © 2019 TIS Inc.
    akka-cluster スプリットブレインリゾルバ OSS実装一覧 - Qiita
    ネットワーク障害によって分裂したクラスターの片方か、
    もしくは全てを停止させてデータの一貫性が崩れるのを防ぐ
    この停止により Entity のフェイルオーバーが引き起こされる
    63 / 73

    View Slide

  64. Consider downtime due to failure
    What will happen if Cluster Sharding nodes crashed or the
    network failure ?
    Part of users will not be able to use the service.
    © 2019 TIS Inc.
    ノードのクラッシュやネットワーク障害によって、
    一部のユーザーがサービスを利用できなくなる。
    64 / 73

    View Slide

  65. Downtime indication
    25 seconds(for a cluster of 10 nodes)
    failure detection: 5 seconds
    stable-after: 10 seconds
    down-removal-margin: 10 seconds
    Downtime increases as nodes increase
    © 2019 TIS Inc.
    Split Brain Resolver · Akka Commercial Addons
    ダウンタイムの目安
    ノードが増えるごとにダウンタイムも増加する。
    65 / 73

    View Slide

  66. Downtime indication
    © 2019 TIS Inc.
    Split Brain Resolver · Akka Commercial Addons
    66 / 73

    View Slide

  67. Tune recovery time
    We can tune recovery time by to change Akka Cluter
    configuration.
    However, it is trade-off between recovery time and false
    positives or temporary Split Brain.
    © 2019 TIS Inc.
    Akka Cluster の設定を調整し、ダウンタイムを短くすることは
    できるが、障害の誤検知や一時的な Split Brain とのトレードオフ
    67 / 73

    View Slide

  68. Data migration
    Command-side datastore (Cassandra) has no data about
    past payments.
    Can not cancel past payments due to it
    We had to construct Command-side data from
    payment history which is in RDBMS
    © 2019 TIS Inc.
    コマンドサイドには過去の決済データがないため、RDBMSの
    決済履歴からコマンドサイドのデータを作成する必要があった
    68 / 73

    View Slide

  69. Summary
    We could reconstruct a part of CRUD style system
    to ES + CQRS with Akka
    It is not necessary to achieve a perfect Reactive
    System from the beginning
    © 2019 TIS Inc.
    CRUDスタイルのシステムの一部分を Akka で再構築。
    最初から完璧なリアクティブシステムを達成する必要はない。
    69 / 73

    View Slide

  70. Summary
    We could reconstruct a part of CRUD style system
    to ES + CQRS with Akka
    It is not necessary to achieve a perfect Reactive
    System from the beginning
    If you want to challenge it...
    © 2019 TIS Inc.
    CRUDスタイルのシステムの一部分を Akka で再構築。
    最初から完璧なリアクティブシステムを達成する必要はない。
    70 / 73

    View Slide

  71. We are hiring!
    Scala で開発したい
    Akka Cluster を実務で使ってみたい
    私服勤務/フルフレックス/在宅勤務制度あり
    © 2019 TIS Inc. 71 / 73

    View Slide

  72. TIS で培われたシステム開発のプラクティス集
    Lerna についても掲載予定!(公開日未定)
    https://fintan.jp/
    © 2019 TIS Inc. 72 / 73

    View Slide

  73. TIS Inc.
    © 2019 TIS Inc. 73 / 73

    View Slide