17.8.4 长期存储与分层存储设计

长期存储与分层存储设计的目标是兼顾查询体验、成本与可用性,满足“热数据快查、冷数据低成本保留”的需求。设计时需明确数据保留周期、查询模式与合规要求,并结合远端存储能力进行分层与路由。

原理草图(热/温/冷分层与数据通路):

文章图片

分层模型与时间窗口示例:
- 热存储(本地 TSDB):7~30 天,高频查询、实时告警。
- 温存储(远端存储/对象存储):3~12 个月,中长期分析。
- 冷存储(归档/离线):1~3 年,合规审计。

示例:Prometheus 本地与远端写入配置(带关键参数解释)
文件:/etc/prometheus/prometheus.yml

global:
  scrape_interval: 15s
  evaluation_interval: 15s

storage:
  tsdb:
    retention: 15d     # 热数据保留天数
    min_block_duration: 2h
    max_block_duration: 2h

remote_write:
  - url: "http://thanos-receive.monitoring.svc:19291/api/v1/receive"
    queue_config:
      max_shards: 8            # 并发写入分片
      max_samples_per_send: 2000
      batch_send_deadline: 5s
      capacity: 10000          # 队列容量,缓冲远端故障
    write_relabel_configs:
      - source_labels: [job]
        regex: "kube-.*"
        action: keep            # 仅写入部分指标,降低成本

remote_read:
  - url: "http://thanos-query.monitoring.svc:9090/api/v1/read"
    read_recent: false          # 超过本地保留期再读远端

示例:Thanos Sidecar 与对象存储配置(简化可运行示例)
1) 对象存储配置 /etc/thanos/objstore.yaml

type: S3
config:
  bucket: "prometheus-longterm"
  endpoint: "s3.example.com"
  access_key: "AKIA..."
  secret_key: "SECRET..."
  insecure: false

2) Sidecar 启动命令(与 Prometheus 同节点)

/usr/local/bin/thanos sidecar \
  --prometheus.url=http://127.0.0.1:9090 \
  --tsdb.path=/var/lib/prometheus \
  --objstore.config-file=/etc/thanos/objstore.yaml \
  --http-address=0.0.0.0:10902 \
  --grpc-address=0.0.0.0:10901

预期效果:Prometheus 本地数据按 block 上传对象存储;Thanos Query 可跨集群查询历史数据。

示例:查询路由策略(短期本地、长期远端/降采样)

文章图片

容量与成本估算示例(命令 + 解释)
1) 统计当前 series 数量(估算基数)

curl -s "http://localhost:9090/api/v1/status/tsdb" | jq '.data.seriesCount'

2) 估算公式(示例)

总存储量/天 ≈ series数 × 每series日增量(1~3MB) × 压缩系数(0.6~0.8)

安装与验证(本节关键组件)
- 安装 Thanos(以二进制为例)

wget https://github.com/thanos-io/thanos/releases/download/v0.34.0/thanos-0.34.0.linux-amd64.tar.gz
tar -xzf thanos-0.34.0.linux-amd64.tar.gz
sudo mv thanos-0.34.0.linux-amd64/thanos /usr/local/bin/
thanos --version
  • 验证远端写入状态(Prometheus)
curl -s http://localhost:9090/api/v1/status/flags | jq '.data."remote_write.url"'

排错与常见问题(带命令)
1) 远端写入队列堆积(写入慢或失败)

curl -s http://localhost:9090/metrics | grep -E "remote_write.*pending|failed|retries"
# 观察 pending/failed/retries 是否持续升高

处理:增加 queue_config.max_shards、检查远端存储性能与网络。

2) 远端对象存储不可用(Sidecar 上传失败)

thanos tools bucket verify \
  --objstore.config-file=/etc/thanos/objstore.yaml

处理:检查 endpoint/AK/SK、DNS 与证书;确认 bucket 权限。

3) 查询结果缺失(查询路由或保留期设置不当)

# 本地查询与远端查询对比
curl -G "http://localhost:9090/api/v1/query_range" \
  --data-urlencode "query=up" \
  --data-urlencode "start=$(date -d '10 days ago' +%s)" \
  --data-urlencode "end=$(date +%s)" \
  --data-urlencode "step=60"

处理:确认 retention、远端写入时长与 read_recent 设置。

练习与实验
1) 将本地保留期设置为 7 天,将远端保留期设置为 180 天,观察 10 天前数据查询结果是否走远端。
2) 启用降采样(如 Thanos Compactor),分别查询 30 天与 180 天范围对比查询耗时。
3) 人为断开对象存储网络 5 分钟,观察远端写入队列与重试指标变化,并恢复后验证数据是否完整。