使用 leader_index 设置 auto_follow 的匹配模式

解读

在国内中大型互联网、金融、运营商以及政务云项目中,跨集群复制(CCR) 是 Elasticsearch 做异地多活、冷热分离、日志汇聚的核心手段。面试官问“如何用 leader_index 设置 auto_follow 的匹配模式”,并不是想听你背参数,而是考察三点:

  1. 是否真正在生产环境配过 CCR,知道匹配模式写错会导致全库复制或遗漏索引;
  2. 是否理解匹配模式与 Rollover、ILM、别名、数据流的配合;
  3. 能否在权限、模板、生命周期、网络等维度给出闭环方案。
    一句话:这道题背后是“让你设计一条能抗业务增长的 auto-follow 规则”。

知识点

  1. auto-follow 本质:跟随端(follower cluster)通过 Remote Cluster Client 轮询 leader 端 _ccr/info/follow_stats,用正则或通配表达式匹配 leader 新建索引,再自动创建同名 follower 索引并启动 follow task。
  2. leader_index 匹配模式语法:只支持通配符(*、?)和时间格式化占位符,不支持正则;大小写敏感;必须能精确匹配到物理索引名,而非别名或数据流名。
  3. 典型踩坑:
    • 写成 logstash-* 会把 leader 端所有历史索引一次性拉过来,瞬间打爆 follower 磁盘;
    • 写成 <logstash-{now/d}> 却忘了 leader 端是UTC+8 业务时间,导致跨天滞后 8 小时;
    • 与 ILM 联动时,新滚动索引名带 6 位数字,模式里少写一位就匹配失败;
    • 匹配到系统索引 .kibana* 会直接报错,CCR 不允许跟随以点开头的索引。
  4. 权限要求:leader 端需要给 remote cluster user 赋予 read_ccr 和 monitor 集群权限,以及对应索引的 read 与 view_index_metadata 权限;follower 端需要 manage_ccr 和 manage_follow_index。
  5. 参数细节:
    • max_read_request_operation_count 默认 5120,日志场景建议调到 20480 减少往返;
    • max_outstanding_read_requests 默认 12,高延迟专线可提到 32;
    • settings.index.number_of_replicas 在 follower 端必须≥1,否则单点故障会中断跟随。
  6. 版本兼容性:6.5+ 才支持 CCR,且 leader 版本必须小于等于 follower 版本; Elastic Cloud 国内金区(阿里云)已强制 8.x,6.x 集群无法作为 leader。
  7. 监控告警:通过 GET /_ccr/stats 看 follow_stats.shard_stats.leader_global_checkpoint 与 follower_global_checkpoint 差值,超过 10 万即认为延迟,需触发钉钉/飞书告警。

答案

在跟随端调用

PUT _ccr/auto_follow/my_pattern
{
  "remote_cluster": "leader-prod",
  "leader_index_patterns": ["nginx-log-<yyyy.MM.dd>-*"],  
  "follow_index_pattern": "{{leader_index}}-copy",         
  "settings": {
    "index.number_of_replicas": 1,
    "index.codec": "best_compression"
  },
  "max_read_request_operation_count": 20480,
  "max_outstanding_read_requests": 32
}

关键点:

  1. leader_index_patterns 必须与 leader 端物理索引名完全对齐,若 leader 用 Rollover 产生 nginx-log-2024.06.25-000006,则模式写成 nginx-log-<yyyy.MM.dd>-* 即可命中;
  2. 千万别写 nginx-log-*,否则历史索引会被全量拉回;
  3. 如果业务用数据流(data stream),仍需匹配其底层 backing index,如 .ds-nginx-log-2024.06.25-000006,模式应写 .ds-nginx-log-<yyyy.MM.dd>-*;
  4. 创建前先在 leader 端执行
    POST /_ccr/info
    
    确认远程集群连通且权限 OK;
  5. 规则创建后,用模板提前定义好 follower 索引的 mapping 与 settings,避免跟随瞬间字段类型不一致导致写入阻塞。

拓展思考

  1. 双活场景下的循环复制:如果 A→B 已有 auto_follow,B 端又开启写入,必须给 B 索引加 index.routing.allocation.exclude._name 隔离,否则 B→A 再建规则会产生循环 follow,Elasticsearch 8.x 已内置 leader_index_shard_follow_tasks 校验,但6.x 会直接宕机。
  2. 匹配模式动态更新:业务方突然把索引名从 app-log-<yyyy-MM-dd> 改成 app_log@<yyyy_MM_dd>,auto_follow 规则不会自动迁移,需要写定时脚本调用 GET /_ccr/auto_follow → 删除旧 pattern → 新建 pattern,期间新索引会漏同步;
  3. 成本优化:国内公有网跨境专线费用高,可在 leader 端用 ILM 把热数据保留 2 小时即滚动,follower 端只跟随热索引,冷数据通过快照仓库跨区恢复,节省 60% 流量;
  4. 合规要求:金融专网要求日志不可出境,可在 leader 端用索引级别的 IP 白名单配合 xpack.security.remote_cluster_server.filter.alternative_names,把 auto_follow 匹配模式限定在指定索引前缀,实现“索引级跨境隔离”。