## モジュール 1: TiDBクラスターとデータの初期化

### 手順 1. TiUP 制御マシンに接続

+ ここをクリック - [ターミナル 1](ssh://monitor1-ssh#1) で、ハンズオン演習用に割り当てられた仮想マシンに接続された新しいターミナルを開きます。

### 手順 2. TiDB クラスタのステータスを確認

+ TiDBクラスタはTiProxyと共に稼働中であり、クラスタに1つの tidb サーバーおよび3つの tikv サーバーがあることを確認します。

   ```bash
   ~/.tiup/bin/tiup cluster display tidb-demo
   ```

   ```output
   Cluster type:       tidb
   Cluster name:       tidb-demo
   Cluster version:    v${LAB:TIDB_VERSION}
   Deploy user:        ec2-user
   SSH type:           builtin
   Dashboard URL:      http://35.74.236.1:2379/dashboard
   Grafana URL:        http://10.90.4.196:3000
   ID                 Role          Host         Ports        OS/Arch       Status  Data Dir                      Deploy Dir
   --                 ----          ----         -----        -------       ------  --------                      ----------
   10.90.4.196:9093   alertmanager  10.90.4.196  9093/9094    linux/x86_64  Up      /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
   10.90.4.196:3000   grafana       10.90.4.196  3000         linux/x86_64  Up      -                             /tidb-deploy/grafana-3000
   10.90.2.178:2379   pd            10.90.2.178  2379/2380    linux/x86_64  Up|L    /tidb-data/pd-2379            /tidb-deploy/pd-2379
   10.90.4.196:9090   prometheus    10.90.4.196  9090/12020   linux/x86_64  Up      /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
   10.90.1.140:4000   tidb          10.90.1.140  4000/10080   linux/x86_64  Up      -                             /tidb-deploy/tidb-4000
   10.90.1.169:20160  tikv          10.90.1.169  20160/20180  linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.1.88:20160   tikv          10.90.1.88   20160/20180  linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.1.99:20160   tikv          10.90.1.99   20160/20180  linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.4.196:6000   tiproxy       10.90.4.196  6000/3080    linux/x86_64  Up      -                             /tidb-deploy/tiproxy-6000
   Total nodes: 9
   ```

> [!TIP]
> ご注意ください！モジュール 1 を開始した場合、モジュール 1 の第 7 ステップまでの各ステップの間に、あまり長い時間間隔（10 分以上）を空けないことをお勧めします。例えば、他の作業を挟んでから戻って操作を続けると、PD コンポーネントが自動的にデータ分布の調整を行う可能性があります。そのため、期待する結果が得られないことがあります。

### 手順 3. sysbench の設定を作成

   ```bash
   cat << EOF > sysbench_config
   mysql-host=${HOST_MONITOR1_PRIVATE_IP}
   mysql-port=6000
   mysql-user=root
   mysql-password=
   mysql-db=sbtest
   time=120
   threads=14
   report-interval=5
   EOF
   cat sysbench_config
   ```

   ```output
   mysql-host=${HOST_MONITOR1_PRIVATE_IP}
   mysql-port=6000
   mysql-user=root
   mysql-password=
   mysql-db=sbtest
   time=120
   threads=14
   report-interval=5
   ```

### 手順 4. TiDB クラスタに接続し、空のデータベース `sbtest` を作成

   ```bash
   mysql -h ${HOST_MONITOR1_PRIVATE_IP} -P 6000 -uroot
   ```

   ```output
   Welcome to the MySQL monitor.  Commands end with ; or \g.
   Your MySQL connection id is 0
   Server version: 8.0.11-TiDB-v${LAB:TIDB_VERSION} TiDB Server (Apache License 2.0) Community Edition, MySQL 8.0 compatible

   Copyright (c) 2000, 2023, Oracle and/or its affiliates.

   Oracle is a registered trademark of Oracle Corporation and/or its
   affiliates. Other names may be trademarks of their respective
   owners.

   Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

   mysql>
   ```

   ```sql
   CREATE DATABASE sbtest;
   EXIT;
   ```

   ```output
   Query OK, 0 rows affected (0.11 sec)
   Bye
   ```

### 手順 5. スキーマデータの準備

+ sysbench`データの準備には約5分から10分かかります。データのインポートを待っている間に、次の手順に進んで、後の手順で使用する関連監視について理解を深めることができます。

   ```bash
   sysbench --config-file=sysbench_config oltp_read_only --tables=10 --table-size=3000000 prepare
   ```

   ```output
   sysbench 1.0.17 (using bundled LuaJIT 2.1.0-beta2)

   Initializing worker threads...

   Creating table 'sbtest2'...
   Creating table 'sbtest8'...
   Creating table 'sbtest5'...
   Creating table 'sbtest6'...
   Creating table 'sbtest7'...
   Creating table 'sbtest9'...
   Creating table 'sbtest1'...
   Creating table 'sbtest4'...
   Creating table 'sbtest3'...
   Creating table 'sbtest10'...
   Inserting 3000000 records into 'sbtest10'
   Inserting 3000000 records into 'sbtest1'
   Inserting 3000000 records into 'sbtest5'
   Inserting 3000000 records into 'sbtest7'
   Inserting 3000000 records into 'sbtest4'
   Inserting 3000000 records into 'sbtest8'
   Inserting 3000000 records into 'sbtest2'
   Inserting 3000000 records into 'sbtest6'
   Inserting 3000000 records into 'sbtest3'
   Inserting 3000000 records into 'sbtest9'
   ```

### 手順 6. スケールアウト/スケールインに関連する監視について学びます

+ これからTiKVのスケールアウト/スケールインに関連する監視についてご説明します。受講者がこれらの監視項目について理解している場合は、手順7に進んでください。[Grafana 監視](http://${LAB:HOST_MONITOR1_PUBLIC_IP}:3000)にログインし、受講者にはこの手順で開いている監視ページを保持し、監視の時間範囲を最近5分または15分に設定し、更新頻度を5秒に変更することをお勧めします。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/9c787410ab425dd7eb7e7297cc46711ec63ccc22.png)

+ TiDBクラスター全体のデータ総量を確認します。[Grafana 監視](http://${LAB:HOST_MONITOR1_PUBLIC_IP}:3000)に入り、`Home`を選択し、次に`tidb-demo`を選択し、続いて`tidb-demo-PD`を選択します。`tidb-demo-PD`の上半分では、`Current storage size`が現在のTiDBクラスターのデータ総量を示し、`Normal Stores`が現在のTiKVノードの数を示し、`Number of Regions`が現在のリーダーの数を示し、`Current peer count`が現在のすべてのリージョンの数を示しています。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/f5789ae1bf0d0012aadb2efd25ebb019aced7755.png)

+ スケールアウト/スケールインの進捗を観察します。`tidb-demo-PD`の上半分では、`Online store progress`が現在のスケールアウトコマンド実行後のバランスの進捗を示し、`Offline store progress`が現在のスケールインコマンド実行後のバランスの進捗を示し、`Left time`が現在のスケールアウト/スケールイン過程におけるバランス完了時間の予測を示し、`Current scaling speed`が現在のスケールアウトまたはスケールイン過程におけるバランスの速度を示しています（単位は`MB/s`）。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/33ca440cdffeacf0f0c761c01569128f4095568b.png)

+ PDにおけるスケールアウトおよびスケールインの関連設定を観察します。`tidb-demo-PD`の下半分で、`Cluster`タブを開くと、`PD scheduler config`パネルにPDコンポーネントのスケジュールに関連する設定が表示され、`Store limit`パネルにはすべてのTiKVノードの`Store limit`設定が表示されます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/abe91e672688c726ab01f31d5a328ea16c519d59.png)

+ PDコンポーネントが生成するスケジュール指令の効率を監視します。`tidb-demo-PD`の下半分で、`Operator`タブを開くと、`Scheduler operator create`パネルにはPDコンポーネントが生成するオペレーターの効率が表示され、`Scheduler operator finish`パネルにはPDコンポーネントが生成したオペレーターの実行効率が表示されます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/166bae9064df01fac2ea5ebcbab5da006b303d0f.png)

+ PDコンポーネントで有効になっているスケジュールを監視します。`tidb-demo-PD`の下半分で、`Scheduler`タブを開くと、`Scheduler`パネルにはPDコンポーネントで現在有効になっているスケジューラが表示されます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/0dc48adba12cd619c1504728f9e4af549ddbd5a5.png)

+ TiKVクラスターのデータ分布状況を監視します。`tidb-demo-PD`の下半分で、`Statistics - balance`タブを開くと、`Store available`パネルには現在の各TiKVノードの利用可能データ量が表示され、`Store available ratio`パネルには現在の各TiKVノードの利用可能ストレージ容量の割合が表示されます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/8f9c5b2cd165337e7b1685e8a905bc0e32ddf951.png)

+ TiKVクラスターのIO負荷を監視する方法についてご説明いたします。[Grafana 監視](http://${LAB:HOST_MONITOR1_PUBLIC_IP}:3000)にログインし、`Home`に入り、次に`tidb-demo`を選択し、続いて`tidb-demo-TiKV-Details`を選択します。`Cluster`タブを開くと、`Cluster`タブの下にある`CPU`パネルには各TiKVノードのCPU使用率が表示され、`IO utilization`パネルには各ノードのIO使用率が表示されます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/4731b3d2183b8d351eae72b449cb547bf23f52ec.png)

### 手順 7. TiDBクラスターの設定

+ `手順5`のデータインポートが完了するのを待ち、PDコンポーネントのスケジューラ設定を確認します。初回実行時には1〜2分待機する必要があります。これは`PD ctl`コンポーネントをダウンロードする必要があるためです。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 scheduler show
   ```

   ```output
   The component `ctl` version v${LAB:TIDB_VERSION} is not installed; downloading from repository.
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION}/ctl pd -u http://10.90.2.178:2379 scheduler show
   [
   "evict-slow-store-scheduler",
   "balance-region-scheduler",
   "balance-leader-scheduler",
   "balance-hot-region-scheduler"
   ]
   ```

+ PDコンポーネントの`balance-region-scheduler`を削除し、次のモジュール手順の準備をします。`balance-region-scheduler`を削除する理由については、次の手順で説明します。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 scheduler remove balance-region-scheduler
   ```

   ```output
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION}/ctl pd -u http://10.90.2.178:2379 scheduler remove balance-region-scheduler
   Success!
   ```

+ PDコンポーネントの`balance-region-scheduler`が削除されたことを確認します。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 scheduler show
   ```

   ```output
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION}/ctl pd -u http://10.90.3.229:2379 scheduler show
   [
   "balance-leader-scheduler",
   "balance-hot-region-scheduler",
   "evict-slow-store-scheduler"
   ]
   ```

+ [Grafana 監視](http://${LAB:HOST_MONITOR1_PUBLIC_IP}:3000)にログインし、`Home`に入り、次に`tidb-demo`を選択し、続いて`tidb-demo-PD`を選択します。`tidb-demo-PD`の下半分で、`Scheduler`タブを開くと、PDコンポーネントの`balance-region-scheduler`スケジューラが削除されていることが確認できます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/d39ff1e27d81d847844986d80fba45691a8036db.png)

+ PDコンポーネントの`region-schedule-limit`変数を`0`に変更し、次のモジュール手順の準備をします。次の手順で、`region-schedule-limit`変数を`0`に設定する理由について説明します。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 config set region-schedule-limit 0
   ```

   ```output
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION}/ctl pd -u http://10.90.2.178:2379 config set region-schedule-limit 0
   Success!
   ```

+ PDコンポーネントの`region-schedule-limit`変数が`0`に変更されたことを確認します。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 config show
   ```

   ```output
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION}/ctl pd -u http://10.90.2.178:2379 config show
   {
      "replication": {
         "enable-placement-rules": "true",
         "enable-placement-rules-cache": "false",
         "isolation-level": "",
         "location-labels": "",
         "max-replicas": 3,
         "strictly-match-label": "false"
      },
      "schedule": {
         "enable-cross-table-merge": "true",
         "enable-diagnostic": "true",
         "enable-heartbeat-breakdown-metrics": "true",
         "enable-heartbeat-concurrent-runner": "true",
         "enable-joint-consensus": "true",
         "enable-tikv-split-region": "true",
         "enable-witness": "false",
         "high-space-ratio": 0.7,
         "hot-region-cache-hits-threshold": 3,
         "hot-region-schedule-limit": 4,
         "hot-regions-reserved-days": 7,
         "hot-regions-write-interval": "10m0s",
         "leader-schedule-limit": 4,
         "leader-schedule-policy": "count",
         "low-space-ratio": 0.8,
         "max-merge-region-keys": 540000,
         "max-merge-region-size": 54,
         "max-movable-hot-peer-size": 512,
         "max-pending-peer-count": 64,
         "max-snapshot-count": 64,
         "max-store-down-time": "30m0s",
         "max-store-preparing-time": "48h0m0s",
         "merge-schedule-limit": 8,
         "patrol-region-interval": "10ms",
         "patrol-region-worker-count": 1,
         "region-schedule-limit": 0,
         "region-score-formula-version": "v2",
         "replica-schedule-limit": 64,
         "slow-store-evicting-affected-store-ratio-threshold": 0.3,
         "split-merge-interval": "1h0m0s",
         "store-limit-version": "v1",
         "switch-witness-interval": "1h0m0s",
         "tolerant-size-ratio": 0,
         "witness-schedule-limit": 4
      }
   }
   ```

+ [Grafana 監視](http://${LAB:HOST_MONITOR1_PUBLIC_IP}:3000)の`tidb-demo-PD`に戻ります。`tidb-demo-PD`の下半分で、`Operator`タブを開くと、`Scheduler operator create`パネルと`Scheduler operator finish`パネルには現在、オペレーターが生成されていないことが確認できます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/41b41866585731f9bd597a4e19180e3465da3fff.png)

+ すべてのTiKVノードの`store limit`の項目を`1`に設定し、次の手順の準備をします。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 store limit all 1
   ```

   ```output
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION} /ctl pd -u http://10.90.2.178:2379 store limit all 1
   Success! Set store limit successfully.
   ```

+ すべてのTiKVノードの`store limit`のすべての項目が`1`に設定されたことを確認します。

   ```bash
   ~/.tiup/bin/tiup ctl:v${LAB:TIDB_VERSION} pd -u http://${HOST_PD1_PRIVATE_IP}:2379 store limit
   ```

   ```output
   Starting component ctl: /home/ec2-user/.tiup/components/ctl/v${LAB:TIDB_VERSION}/ctl pd -u http://10.90.2.178:2379 store limit
   {
   "1": {
      "add-peer": 1,
      "remove-peer": 1
   },
   "4": {
      "add-peer": 1,
      "remove-peer": 1
   },
   "7": {
      "add-peer": 1,
      "remove-peer": 1
   }
   }
   ```

+ [Grafana 監視](http://${LAB:HOST_MONITOR1_PUBLIC_IP}:3000)の`tidb-demo-PD`に戻ります。`tidb-demo-PD`の下半分で、`Cluster`タブを開くと、`PD scheduler config`パネルの`region-schedule-limit`が`0`になっており、`Store limit`パネルのすべての項目が`1`になっていることが確認できます。

  ![70%](https://lab-static.pingcap.com/images/2025/7/24/95665cbee2ec67dd9104e8508364a2379b9d6ead.png)

+ これで、TiDBクラスターの設定とデータの準備が完了しました。スケールアウトおよびスケールインを開始することができます。

### 手順 8.「PDコンポーネントの `balance-region-scheduler` を削除し、PDコンポーネントの `region-schedule-limit` 変数を `0` に設定し、`Store limit` を `1` に変更する」についての説明

+ ここでは、TiKVのスケールアウトを例に、PDとTiKVがどのように協力してデータのバランスの取れた分布を維持するかを説明します。下の図では、すべてのTiKVノードとリーダー役割のリージョンレプリカがハートビートを利用して関連情報をPDコンポーネントに送信するため、PDコンポーネントは、データが各TiKVノードにどのように分布しているかを把握することができます。

  ![85%](https://lab-static.pingcap.com/images/2025/7/24/aba924da1fff5a1a82ae02d05393a50a4358b9d6.png)

+ 新しいTiKVノードが追加されると、PDコンポーネントはそのハートビート情報を受け取ります。PDコンポーネントが現在のデータ分布が不均一であると判断した場合、その `balance-region-scheduler`コンポーネントは複数の `balance-region-operator` を作成します。各 `balance-region-operator` にはデータのバランスを取るための具体的な手順が含まれており、これらの手順は関連するリーダー役割のリージョンレプリカに送信され、その後、所属するリージョングループがデータのバランスを取る作業を開始します。

  ![85%](https://lab-static.pingcap.com/images/2025/7/24/52c6ded417e9c8bcbae6621023f4b39349c3b5a9.png)

+ 前の手順（手順 7）でPDコンポーネントの `balance-region-scheduler` を削除した後、PDコンポーネントはデータ分布が不均一であることを発見しても `balance-region-operator` を発行することができません。そのため、スケールアウト後には `balance-region-scheduler` を再度追加しなければデータのバランスを取ることができないことがわかります。

+ `region-schedule-limit` はPDコンポーネントが同時に生成できるオペレーターの数を示しており、これが`0`の場合、PDコンポーネントは`balance-region-operator`を生成することができません。これを`0`より大きい値に設定する必要があります。そうしないと、データのバランス操作は開始されません。

+ `Store limit`はTiKVがPDから送られてくるオペレーター操作を1分間に実行できる最大数を定義しており、これによりデータのバランスを取る動作の速さを調整することができます。

+ 今後のモジュールや手順では、「PDコンポーネントの `balance-region-scheduler`を削除し、PDコンポーネントの`region-schedule-limit`変数を`0`に設定し、`Store limit`を`1`に変更する」ことによって引き起こされる現象を観察し、適切な調整を行う予定です。

+ `region-schedule-limit` については、こちらをご参照ください：<https://docs.pingcap.com/ja/tidb/stable/pd-configuration-file/#code-region-schedule-limit-code>

+ `Store limit` については、こちらをご参照ください：<https://docs.pingcap.com/ja/tidb/stable/configure-store-limit/>

+ PDの`balance-region-scheduler` コンポーネントが `balance-region-operator`を正常に作成した場合、最初のステップでは選択されたリーダー役割のリージョンレプリカにデータをコピーし、新しいTiKVノード（TiKV Node 4）に送信するよう通知します。新しいTiKVノード（TiKV Node 4）にはLearner役割のデータレプリカが存在します。

  ![85%](https://lab-static.pingcap.com/images/2025/7/24/e7874791484e5f440de4f9a5e9763043c23399f9.png)

+ 次に、PDコンポーネントの`balance-region-operator`が第二ステップを行い、同じRaftグループ内のLearner役割のレプリカとFollower役割のレプリカの役割を交換します。図の通り、新しく追加されたTiKVノード（TiKV Node 4）内のRegion3レプリカがFollower役割に変わり、既存のTiKVノード（TiKV Node 1）内のRegion3レプリカがLearner役割に変わります。

  ![85%](https://lab-static.pingcap.com/images/2025/7/24/223b9ba88e98391b1cd31e419b7558c78d75a576.png)

+ 次に、PDコンポーネントの `balance-region-operator`が第三ステップを行い、Raftグループ内のLearner役割のレプリカを削除します。

  ![85%](https://lab-static.pingcap.com/images/2025/7/24/6e66f0bc2fd1eddfe263bf1f7800da9fbc543c99.png)

+ 最後に、PDコンポーネントとTiKVコンポーネントが共同で協力し、スケールアウト後のデータバランス操作を完了しました。

  ![85%](https://lab-static.pingcap.com/images/2025/7/24/f7bfe57d10aaaee6ffb7a3e6f1f6467f42c71514.png)

+ スケールインについては、同じRaft Group内のリージョンレプリカの移動原理はスケールアウト操作と同様ですが、異なる点はPDコンポーネントが発行するオペレーターの名称が`replace-rule-offline-peer` または `replace-rule-offline-leader-peer`であることです。詳細については、コース内容をご参照ください。
