集群扩缩容

MynaDB 集群专为弹性扩展设计。添加 Data 节点以增加写入吞吐量和查询并行度, 或在低流量时段移除节点以降低成本。由于所有持久化数据存储在共享对象存储(S3、MinIO 或 OSS)中, 扩缩容操作永远不需要数据迁移或重平衡。本页涵盖完整的节点生命周期、扩容和缩容流程、 故障检测、冷备复制和运维最佳实践。

前提条件:本页假设您已有运行中的 MynaDB 集群。如果您是首次搭建集群, 请先阅读集群快速入门指南, 并查看集群架构页面了解 Meta 共识、写入协调和缓存失效的背景知识。

节点生命周期

MynaDB 集群中的每个 Data 节点都经历一组明确定义的状态。理解这些状态对于规划维护窗口、 执行缩容操作和分析故障恢复至关重要。Meta 集群跟踪每个已注册节点的当前状态, 并将状态转换作为事件发布给所有 Router 和 Admin 控制台。

  Node Lifecycle State Machine
  ============================

  +-----------+     RegisterNode      +----------+
  | Starting  | --------------------> |  Active  | <----- heartbeat refreshes lease
  |   (1)     |    (auto on boot)     |   (2)    |
  +-----------+                       +----+-----+
                                           |
                        +------------------+------------------+
                        |                                     |
                   drain request                     heartbeat timeout
                        |                              (3 missed)
                        v                                     |
                  +-----------+                               v
                  | Draining  |                        +------------+
                  |   (3)     |                        |  Inactive  |
                  +-----+-----+                        |    (4)     |
                        |                              +------------+
                   scale-in plan                  (detected by Meta leader;
                   assigns tables                  triggers recovery manager)
                   to other nodes
                        |
                        v
                  +-----------+       flush complete    +-----------+
                  | Retiring  | --------------------->  |  Drained  |
                  |   (5)     |   memtable flushed,     |   (6)     |
                  +-----------+   tables reassigned     +-----------+
                                                     (safe to terminate)
        
状态 ID 描述 接受写入 提供查询
Starting 1 节点正在初始化:加载配置、连接 Meta、回放 WAL。对 Router 不可见,不接受流量。 否 否
Active 2 健康且完全运行。持续向 Meta 发送心跳,提供读写服务,如被选为领导者则运行后台任务。 是 是
Draining 3 维护模式。不接受新写入。允许现有进行中的请求完成。活跃连接在可配置超时(默认 30 秒)内排空。 否 是(仅现有)
Inactive 4 节点已死亡或不可达,在 Meta 领导者观察到连续 3 次心跳缺失(默认 5 秒间隔即 15 秒)后检测到。触发恢复管理器。 否 否
Retiring 5 缩容进行中。节点正在将内存中的 DataCache 刷新到对象存储,其表所有权正由 Meta 领导者重新分配给其他活跃节点。 否 是(只读)
Drained 6 缩容完成。所有缓存数据已刷新到 S3,所有表所有权已转移。节点可以安全终止或退役。 否 否

扩容(添加节点)

扩展 MynaDB 集群非常简单:使用指向 Meta 集群的正确配置启动新节点, 它将自动注册并开始提供服务。由于所有节点共享同一个对象存储后端,无需数据迁移。

添加 Data 节点

当新的 Data 节点启动时,以下序列自动发生:

  1. Data 节点加载配置并通过 gRPC 连接 Meta 集群。
  2. 向 Meta 领导者调用 RegisterNode,提供节点 ID、通告地址、HTTP 端口、Flight 端口和能力。
  3. Meta 领导者将注册信息持久化到 Raft 日志,并将节点转换为 Active 状态。
  4. NodeRegistered 事件发布给所有订阅者(Router、Admin 控制台)。
  5. 每个 Router 接收事件并更新 ShardCache,将新节点加入路由表。
  6. 尚未被任何节点拥有的表的新写入可能被路由到新节点(最低负载选择)。
  7. 新节点可以立即对共享对象存储中的历史数据提供查询服务。
toml
# dev/configs/cluster-local/data3.toml
[data]
node_id = "data-3"
http_port = 5200
flight_port = 5201
advertise_addr = "127.0.0.1:5201"
meta_endpoints = ["127.0.0.1:6001", "127.0.0.1:6101", "127.0.0.1:6201"]

[storage]
backend = "local"
data_dir = "./dev/data/cluster/data3"

[cache]
flush_interval_secs = 60
max_size_mb = 1024

[wal]
enabled = true
sync_on_write = false
rotate_size_mb = 128
bash
# Start the new data node
./target/release/mynadb -c dev/configs/cluster-local/data3.toml data start

# Verify registration (should show 3 data nodes)
curl -s http://localhost:7000/cluster/nodes | jq '.nodes[] | {node_id, state, http_addr}'

添加 Router 节点

Router 节点完全无状态。它们通过 Meta 集群发现 Data 节点, 并维护通过 Meta 事件订阅刷新的内存路由表(ShardCache)。 添加新 Router 不需要与现有 Router 协调。

bash
# Start the second router
./target/release/mynadb -c dev/configs/cluster/router2.toml router start

# Add to HAProxy backend (example)
# server router2 127.0.0.1:7010 check inter 5s fall 3 rise 2

# Verify the new router can serve queries
curl "http://localhost:7010/query/testdb" -d "SELECT * FROM cpu LIMIT 5"
无需数据迁移!由于所有数据存储在共享对象存储(S3/MinIO/OSS)中, 任何节点都可以读取任何表的历史数据,不受所有权限制。所有权仅决定哪个节点接受给定表的写入。 查询分布到所有活跃节点。

缩容(移除节点)

从 MynaDB 集群中移除节点需要精心编排以防止数据丢失。缩容过程确保所有内存数据都刷新到对象存储, 且所有表所有权都转移到剩余节点后,才终止节点。MynaDB 提供规划(试运行)API 和执行 API 以安全进行缩容操作。

优雅缩容流程

阶段 操作 描述
1. 规划 确定目标节点 根据选择的策略(least_loaded 或 most_idle)选择要退役的 Data 节点。验证是否有足够的活跃节点为集群提供服务。试运行模式显示计划而不执行。
2. 迁移 重新分配表所有权 对于退役节点拥有的每个表,Meta 领导者调用 ReassignTable 将所有权转移到健康的活跃节点。Router 接收 TableReassigned 事件并更新 ShardCache。
3. 排空 刷新和排空 退役节点标记为 Retiring(状态 5)。停止接受新写入,将整个 DataCache 刷新到对象存储,完成任何进行中的写操作,并发布所有已刷新文件的缓存失效事件。
4. 已排空 安全终止 所有数据刷新完毕且所有表重新分配后,节点转换为 Drained(状态 6)。现在可以安全终止,释放其资源。

缩容 API

步骤 1:规划(试运行)

bash
# Preview which nodes will be retired and which tables will be reassigned
curl -s -X POST http://localhost:7000/cluster/scale-in/plan \
  -H "Content-Type: application/json" \
  -d '{
    "reduce_primaries": 2,
    "strategy": "least_loaded",
    "dry_run": true
  }' | jq .

步骤 2:执行

bash
# Execute the scale-in plan (removes dry_run flag)
curl -s -X POST http://localhost:7000/cluster/scale-in/execute-plan \
  -H "Content-Type: application/json" \
  -d '{
    "reduce_primaries": 2,
    "strategy": "least_loaded"
  }' | jq .

步骤 3:监控进度

bash
# Check progress of an active scale-in operation
curl -s http://localhost:7000/cluster/scale-in/status | jq .

# Poll until all retiring nodes reach Drained state
watch -n 5 'curl -s http://localhost:7000/cluster/nodes | \
  jq ".nodes[] | select(.state == \"Retiring\" or .state == \"Drained\") | {node_id, state}"'

故障检测与恢复

MynaDB 使用心跳和租约机制来检测节点故障。当 Data 节点不可达时, Meta 领导者自动触发恢复工作流,无需运维人员干预即可保持数据完整性和恢复集群健康。

心跳与租约系统

参数 默认值 描述
heartbeat_interval_secs 5 每个 Data 节点向 Meta 领导者发送心跳的频率
lease_ttl_secs 15 最后一次心跳后租约过期的时间(应为心跳间隔的 3 倍)
expire_check_interval_secs 5 Meta 领导者扫描过期租约的频率
max_missed_heartbeats 3 节点被认为死亡前的心跳缺失次数(信息性;实际检测基于租约)

崩溃恢复流程

当 Meta 领导者检测到过期的租约时,以下恢复序列自动触发:

  1. 租约过期检测:Meta 领导者的周期性 ExpireLeases 任务发现故障节点的陈旧租约。
  2. 节点标记为 Inactive:Meta 领导者将节点状态更新为 Inactive(状态 4)。发布 NodeStateChanged 事件。
  3. 恢复管理器触发:在可配置的 recovery_delay_secs(默认 3 秒)后,恢复管理器开始处理故障节点。
  4. Standby 刷新(如已配置):如果故障节点有配置的冷备节点,备用节点将其复制的 DataCache 刷新到对象存储,保留主节点尚未持久化的数据。
  5. 孤立表重新分配:故障节点之前拥有的所有表被重新分配给健康的活跃节点。
  6. Router 通知:Router 接收 NodeStateChanged 和 TableReassigned 事件,更新 ShardCache。
  7. 写入自动重路由:受影响表的后续写入透明地路由到新的所有者节点。
  Crash Recovery Timeline
  ========================

  Time (seconds)
  0s        5s       10s       15s       18s       20s       25s
  |---------|---------|---------|---------|---------|---------|
  ^         ^         ^         ^         ^         ^
  |         |         |         |         |         |
  Node      Last      Missed    Lease     Recovery  Tables
  crashes   heartbeat heartbeat expires   manager   reassigned;
            received  #3        (Meta     triggers  writes
                      detected  marks                rerouted
                                Inactive)

  |<-- heartbeat_interval -->|
                      |<-- lease_ttl (15s) -->|
                                        |<-3s->|
                                        delay    |<-- ~5s -->|
                                                  recovery     traffic
                                                  processing   restored

  Total recovery time: ~20-25 seconds (worst case)
        

冷备复制

对于需要在节点故障期间最小化数据丢失的工作负载,MynaDB 支持冷备复制模型。 每个 Primary Data 节点可以有一个 Standby 节点,异步复制 Primary 的内存 DataCache。 如果 Primary 故障,Standby 可以在表所有权重新分配之前将复制的缓存刷新到对象存储, 保留尚未持久化的数据。

模式 接受写入 提供查询 复制 描述
Primary 是 是 发送到 Standby 分配表的主动写入所有者。通过 Arrow Flight 异步将缓存数据复制到配置的 Standby 节点。
Standby 否(仅复制) 是(只读) 从 Primary 接收 维护 Primary DataCache 的副本。可提供读查询以分担 Primary 负载。Primary 故障时自动刷新缓存。

配置

toml
# Primary data node configuration (data1.toml)
[data]
node_id = "data-1"
mode = "primary"
http_port = 5000
flight_port = 5001
advertise_addr = "10.0.1.10:5001"
meta_endpoints = ["10.0.1.1:6001", "10.0.1.2:6001", "10.0.1.3:6001"]

# Configure the standby that will receive replication data
[data.replication]
backing_standby = "data-1-standby"      # Node ID of the standby
replication_mode = "async"               # "async" (default) or "sync"
batch_size = 1000                        # Records per replication batch
max_lag_secs = 30                        # Alert if standby falls behind
toml
# Standby data node configuration (data1-standby.toml)
[data]
node_id = "data-1-standby"
mode = "standby"
http_port = 5010
flight_port = 5011
advertise_addr = "10.0.1.11:5011"
meta_endpoints = ["10.0.1.1:6001", "10.0.1.2:6001", "10.0.1.3:6001"]

# Configure the primary this standby replicates from
[data.replication]
replication_source = "data-1"            # Node ID of the primary
flight_endpoint = "10.0.1.10:5001"       # Primary's Flight address for receiving data
数据丢失窗口:在异步复制模式下,Standby 可能落后 Primary 最多 max_lag_secs(默认 30 秒)。Primary 已接受但尚未复制到 Standby 的写入在 Primary 崩溃时将丢失。 如需零数据丢失,请使用 replication_mode = "sync",但代价是更高的写入延迟。

表所有权 TTL

MynaDB 中的表所有权通过 TTL(生存时间)租约机制维护。此设计防止节点崩溃或未经优雅缩容即被移除时, 陈旧的所有权记录无限期保留。活跃的 Data 节点必须定期刷新其所有权租约以维持写入权限。

toml
# Table ownership TTL configuration
[data.ownership]
ttl_secs = 600                   # Ownership expires after 10 minutes without refresh
refresh_interval_secs = 60       # Refresh every 60 seconds (should be << ttl_secs)
cleanup_interval_secs = 120      # Meta checks for expired ownership every 2 minutes

监控集群健康

健康端点

bash
# Basic health check (returns 200 if healthy, 503 if degraded)
curl -s http://localhost:7000/health | jq .

# Detailed cluster status (node count, leader info, coordinator state)
curl -s http://localhost:7000/cluster/status | jq .

# List all registered nodes with their states
curl -s http://localhost:7000/cluster/nodes | jq .

Prometheus 指标

以下 Prometheus 指标在每个节点的 /metrics 端点上暴露,对于监控扩缩容操作和集群健康特别有用:

指标 类型 描述
mynadb_cluster_nodes_totalGauge已注册节点总数(所有状态)
mynadb_cluster_nodes_healthyGauge处于 Active 状态且租约有效的节点数
mynadb_cluster_nodes_by_stateGauge(带标签)按状态统计的节点数:state="active|draining|retiring|inactive|drained"
mynadb_cluster_lock_acquisitions_totalCounter分布式锁获取总次数
mynadb_cluster_lock_wait_secondsHistogram等待获取分布式锁的时间
mynadb_cluster_heartbeat_latency_secondsHistogramData 节点到 Meta 的心跳 RPC 往返时间
mynadb_cluster_tables_ownedGauge该节点拥有的表数量
mynadb_cluster_replication_lag_secondsGaugeStandby 复制落后 Primary 的延迟(仅 Standby 节点)
mynadb_cluster_scale_in_operations_totalCounter已执行的缩容操作总数
mynadb_cluster_table_reassignments_totalCounter表所有权重新分配总次数

Grafana 告警规则

以下告警规则推荐用于生产部署:

yaml
groups:
  - name: mynadb_cluster_health
    interval: 15s
    rules:
      # Alert if any node has been inactive for more than 2 minutes
      - alert: MynaDBNodeInactive
        expr: mynadb_cluster_nodes_by_state{state="inactive"} > 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "MynaDB node is inactive"
          description: "{{ $value }} node(s) have been in Inactive state for over 2 minutes."

      # Alert if healthy node count drops below minimum
      - alert: MynaDBClusterDegraded
        expr: mynadb_cluster_nodes_healthy < 2
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "MynaDB cluster has fewer than 2 healthy nodes"

      # Alert if heartbeat latency is elevated
      - alert: MynaDBHeartbeatSlow
        expr: histogram_quantile(0.99, rate(mynadb_cluster_heartbeat_latency_seconds_bucket[5m])) > 5
        for: 3m
        labels:
          severity: warning
        annotations:
          summary: "MynaDB heartbeat latency is high"

      # Alert if standby replication lag exceeds threshold
      - alert: MynaDBReplicationLag
        expr: mynadb_cluster_replication_lag_seconds > 60
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "MynaDB standby replication lag is high"

      # Alert if a scale-in operation is stuck
      - alert: MynaDBScaleInStuck
        expr: mynadb_cluster_nodes_by_state{state="retiring"} > 0
        for: 15m
        labels:
          severity: warning
        annotations:
          summary: "MynaDB scale-in operation appears stuck"

最佳实践

Meta 集群

Router 层

扩缩容操作

高可用