如何在 Nginx 层配置幂等重试而不穿透到业务服务?

解读

国内高并发场景下,网关层(Nginx) 常被要求“零侵入业务”地解决“瞬态失败重试”问题。
面试官真正想确认的是:

  1. 你能否区分“可重试的幂等请求”与“不可重写的非幂等请求”;
  2. 你能否用纯 Nginx 配置(不改动 Java/Go 代码)完成重试+幂等校验,且绝不把重试流量打到下游;
  3. 你能否给出可落地的配置片段与测试验证思路,而不是背八股文。

知识点

  1. 幂等键(Idempotency-Key)
    国内大厂通行做法:客户端在 Header 中带入 X-Idempotency-Key 或 X-Req-Id,长度≤64 字节,业务全局唯一。
  2. Nginx 共享内存字典
    lua_shared_dict idem_cache 10m; 10 MB 内存可缓存约 200 万个 64 字节 Key,单机 QPS 5w+ 无锁竞争。
  3. OpenResty 阶段模型
    access_by_lua_block 阶段做幂等判重;body_filter_by_lua_block 阶段把首次成功响应缓存;log_by_lua_block 阶段异步落地日志,不阻塞主请求。
  4. 缓存过期策略
    采用滑动窗口 + 固定 TTL 双保险:TTL=7 天,窗口期=业务最大重试周期(通常 30 s)。
  5. 降级开关
    通过 lua_var 读取 Consul/Nacos 下发的动态开关,一旦共享内存超限或 Redis 故障,直接放行,避免重试风暴。

答案

以下示例基于 OpenResty 1.21+,单 Nginx 节点即可实现“重试不穿透”。
假设下游业务域名 order.svc,只针对 POST /api/pay 做幂等重试。

# 1. 共享内存
lua_shared_dict idem_cache 10m;
lua_shared_dict idem_lock 1m;

upstream order_backend {
    server 10.0.0.11:8080 max_fails=0;   # 关闭 Nginx 自带重试,逻辑自己控
}

server {
    listen 80;
    server_name gateway.example.com;

    location = /api/pay {
        access_by_lua_block {
            local key = ngx.req.get_headers()["X-Idempotency-Key"]
            if not key or #key == 0 then
                ngx.exit(400)   -- 国内规范:缺少幂等键直接 400
            end

            local cache = ngx.shared.idem_cache
            local lock = ngx.shared.idem_lock

            -- 双检锁:先读缓存,再抢锁,再读一次,防止并发重试穿透
            local resp = cache:get(key)
            if resp then
                ngx.status = 200
                ngx.say(resp)   -- 直接返回缓存报文
                ngx.exit(200)
            end

            local elapsed, err = lock:lock(key)
            if not elapsed then
                ngx.exit(503)   -- 锁失败直接拒绝,防止雪崩
            end

            resp = cache:get(key)  -- 抢到锁再查一次
            if resp then
                lock:unlock(key)
                ngx.status = 200
                ngx.say(resp)
                ngx.exit(200)
            end

            -- 未命中,放行到后端,并把 key 存入 ngx.ctx 供后续阶段使用
            ngx.ctx.idem_key = key
            lock:unlock(key)
        }

        # 2. 代理到真实服务
        proxy_pass http://order_backend;
        proxy_set_header Host order.svc;

        # 3. 缓存成功响应
        body_filter_by_lua_block {
            local key = ngx.ctx.idem_key
            if not key then return end

            local cache = ngx.shared.idem_cache
            local chunk = ngx.arg[1]
            local eof   = ngx.arg[2]

            -- 只缓存 2xx 且报文≤64KB,防止内存爆炸
            if ngx.status >= 200 and ngx.status < 300 and eof then
                local resp_so_far = cache:get(key .. "_body") or ""
                resp_so_far = resp_so_far .. chunk
                if #resp_so_far <= 65536 then
                    cache:set(key .. "_body", resp_so far, 30)  -- 30s 滑动窗口
                end
            end
        }

        # 4. 最终把完整报文写回共享内存
        log_by_lua_block {
            local key = ngx.ctx.idem_key
            if not key then return end

            local cache = ngx.shared.idem_cache
            local full_body = cache:get(key .. "_body")
            if full_body and ngx.status >= 200 and ngx.status < 300 then
                cache:set(key, full_body, 7 * 24 * 3600)  -- 7 天长期有效
            end
            cache:delete(key .. "_body")  -- 清理临时碎片
        }
    }
}

测试验证

  1. 使用 JMeter 5.5 线程组 200 并发,同一 X-Idempotency-Key 重复发 POST /api/pay,后端只收到 1 次;
  2. 用 tcpdump 抓包确认第二次请求在 Nginx 层直接返回 200,无 upstream 流量;
  3. 通过 Grafana + Prometheus 监控 nginx_lua_dict_used_ratio,内存占用≤60% 即达标。

拓展思考

  1. 多节点一致性
    单节点共享内存无法解决横向扩容场景,可引入 Redis 集群 作为二级缓存,Nginx 层使用 lua-resty-redis-connector 做异步回写,读miss 再回源 Redis,写成功再删 Redis,最终一致性 满足国内金融合规。
  2. 版本化缓存
    对响应体较大的接口,可缓存响应摘要(SHA256)+ 304 跳转,减少 70% 内存占用。
  3. 灰度重试
    通过 Consul-Template 动态下发重试白名单,只对特定 App-Version ≥ 2.8.0 开启幂等缓存,防止老版本客户端异常重试。
  4. 压测陷阱
    注意 Linux 内核参数 net.core.somaxconn 与 Nginx worker_connections 需同步调大,否则高并发下锁竞争会导致误判 503,压测前务必 slabtop -s c 观察共享内存锁开销。

掌握以上要点,即可在面试中从“背配置”升级为“讲方案”,直接对标阿里 P7+ 网关中间件要求。