使用 consistent_hash 插件将同一资源固定到边缘节点,减少回源

解读

国内 CDN/边缘节点面试常把“固定资源”与“减少回源”放在一起问,本质是考察对一致性哈希原理、nginx-upstream-consistent-hash 模块(或 nginx-plus 的 hash $uri consistent)配置细节、以及生产灰度、容灾、热点漂移等全链路治理的理解。面试官希望听到:

  1. 为什么轮询、IP-hash 做不到“资源级”固定;
  2. 一致性哈希如何解决节点上下线时的重哈希风暴;
  3. 在边缘节点场景下如何与缓存 Key、回源 Host、SNI、双活多活、热点限流配合;
  4. 真实故障 case:虚拟节点数设置不合理导致倾斜、节点权重不一致造成回源放大、hash 环漂移引发旧节点脏数据。

回答必须给出可直接落地的 nginx.conf 片段,并说明国内云厂商(阿里云 ENS、腾讯云 ECDN、百度智能边缘 BEC)在“边缘 K8s + DaemonSet nginx”里是怎样把 consistent_hash 做成 ConfigMap 热更新而不 reload 的。

知识点

  1. 一致性哈希原理:2^32 闭环、虚拟节点(replicas)、按顺时针找第一个节点。
  2. nginx 第三方模块:nginx-upstream-consistent-hash(开源)与 nginx-plus 内置 hash $variable consistent 的异同。
  3. 变量选择:uri、uri、request_uri、uriuriis_argsargs、args、http_x_cache_key 的优劣;避免带时间戳的 query string 导致同一资源散列到不同节点。
  4. 虚拟节点数:replicas=160 是 Twitter 论文经验值,边缘节点 8-16 核 4G 内存场景下 80-120 足够, replicas 过大增加 CPU 查环耗时。
  5. 权重与容灾:weight= 与 consistent_hash 互斥,必须所有节点 weight 相等;backup= 和 max_fails=0 配合 down 标记实现平滑摘流。
  6. 热升级:nginx-plus API /upstream/ 接口动态增删节点;开源版通过 lua-resty-upstream-healthcheck + consul-template 无 reload 更新 upstream。
  7. 回源收敛:边缘层 consistent_hash → 中间源站再做一层 consistent_hash,保证“同边缘→同中源→同主源”三级固定,降低主源带宽 30%+。
  8. 监控指标:upstreamaddr与upstream_addr 与 upstream_cache_status 联合日志,Grafana 统计“回源率=MISS/(HIT+MISS)”,单节点回源率突增>5% 时告警。
  9. 热点漂移:虚拟节点数不足导致 1% 节点承担 10% 流量,用“二次哈希”即 consistent_hash + local 缓存 1s 兜底,或启用 nginx-plus 的 “least_time” 做 fallback。
  10. 合规:国内 ISP 要求 60 天内日志留存,hash 环变更记录需写入 Kafka,供管局抽检。

答案

1. 安装与编译

# CentOS 7/8 国内源
yum install -y gcc pcre-devel zlib-devel openssl-devel
wget http://nginx.org/download/nginx-1.24.0.tar.gz
git clone https://github.com/replay/ngx_http_consistent_hash
./configure --prefix=/etc/nginx \
            --with-http_ssl_module \
            --with-http_v2_module \
            --add-module=../ngx_http_consistent_hash
make -j$(nproc) && make install

2. 最小可用配置

http {
    upstream edge_cluster {
        consistent_hash $uri$is_args$args;   # 固定同一资源
        server 10.0.1.11:8080 weight=1 max_fails=2 fail_timeout=10s;
        server 10.0.1.12:8080 weight=1 max_fails=2 fail_timeout=10s;
        server 10.0.1.13:8080 weight=1 max_fails=2 fail_timeout=10s;
    }
    server {
        listen 80;
        location ~* \.(mp4|jpg|ts|m3u8)$ {
            proxy_pass http://edge_cluster;
            proxy_cache edge_cache;
            proxy_cache_key $uri$is_args$args;
            proxy_cache_valid 200 302 10m;
            proxy_cache_lock on;
            proxy_cache_lock_timeout 3s;
            add_header X-Hash-Upstream $upstream_addr;
        }
    }
}

说明:

  • consistent_hash 指令由第三方模块提供,变量必须稳定,去掉 utm_source 等随机参数。
  • proxy_cache_lock 防止同一资源并发回源,降低源站压力。
  • X-Hash-Upstream 回显方便排障。

3. 虚拟节点调优

upstream edge_cluster {
    consistent_hash $uri replicas=120;
}

边缘节点 4G 内存,120 个虚拟节点可把标准差控制在 3% 以内;若节点数>50,replicas 可降到 80,CPU 节约 5%。

4. 灰度摘流

server 10.0.1.13:8080 down;   # 需下线前先在配置里标记 down,reload 后等待 30s 无新连接再杀进程

开源版无 API,需结合 consul-template + inotify 做自动 reload;nginx-plus 可直接调用:

curl -X POST http://127.0.0.1:8080/api/6/http/upstreams/edge_cluster/servers/10.0.1.13:8080/down

5. 回源率监控

log_format 增加:

log_format edge '$remote_addr [$time_local] "$request" $status '
                '$body_bytes_sent "$http_referer" '
                'ups=$upstream_addr cache=$upstream_cache_status';

通过 Grafana + Loki 统计 cache=MISS 且 ups 非“-”即为回源,告警阈值:回源率>5% 且持续 2min。

6. 热点漂移兜底

location ~* \.ts$ {
    set $fallback 0;
    access_by_lua_block {
        local dict = ngx.shared.hot_dict
        local key = ngx.var.uri
        local count = dict:incr(key, 1, 0, 1) -- 1s 过期
        if count > 200 then
            ngx.var.fallback = 1
        end
    }
    proxy_pass http://edge_cluster;
    proxy_cache_bypass $fallback;  -- 热点直接回源,避免打爆单节点
}

拓展思考

  1. 双活场景下,A 机房边缘节点 hash 环与 B 机房对称部署,若跨机房延时>10ms,如何把“同一资源”始终映射到同机房?——可在变量里加入机房前缀:consistent_hash "dcdcuri",dc 通过 consul 注入。
  2. 如果资源 URL 里含有 /app/123456/video.m3u8,而 123456 是用户级 ID,会导致热点集中在少数虚拟节点,如何打散?——取 URI 的 Path+Query 再做一次 MurmurHash,把 64 位截断成 32 位作为新变量,保证随机性。
  3. 国内监管要求“可回溯”,需要证明某次请求确实被固定到某节点,如何在日志里加入 hash 环版本号?——把 replicas 值和节点列表的 CRC32 拼接成 version,通过 lua 注入到日志,变更即产生新 version,方便审计。