通过 `canary=1` cookie 把 5% 流量导入新版本

解读

面试官想考察三件事:

  1. 能否在不侵入业务 Handler 的前提下,用 Negroni 中间件 完成流量灰度;
  2. 对 Cookie 解析、一致性哈希或随机采样 的掌握;
  3. 是否具备 可观测性 意识:灰度决策要可追踪、可回滚、可监控。
    国内大厂(阿里、字节、腾讯)普遍要求灰度逻辑 零侵入、可热更新、可降级,因此必须保证:
  • 决策结果写入 Request Context,下游只读不写;
  • 支持 强制回滚(如紧急 Kill Switch);
  • 日志里带 统一 TraceId,方便 SRE 在 ELK/SkyWalking 中按版本过滤。

知识点

  1. Negroni 中间件执行顺序:洋葱模型,灰度决策必须放在 路由匹配之前,否则后续中间件无法读取决策结果。
  2. Cookie 与一致性采样:单纯 rand.Float32() < 0.05 会导致同一用户多次请求被随机打散,国内产品一般要求 用户维度一致性;因此用 用户 ID 或设备 ID 做 FNV-1a 哈希取模,保证同一用户始终落同一版本。
  3. Context 传值:使用 context.WithValue 把 canary=true 注入 *http.Request.Context(),避免 Header 污染。
  4. 回滚策略:通过 环境变量 或 配置中心(如 Apollo、Nacos)下发 CANARY_WEIGHT=0 实现秒级回滚,无需发版。
  5. 监控埋点:在中间件里用 prometheus.NewCounterVec 记录 canary_version="new"|"old",配合 Grafana 大盘实时对比错误率、P99。

答案

package main

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/urfave/negroni"
)

type ctxKey int

const canaryKey ctxKey = iota

// 可热更新的权重
var canaryWeight = readWeight()

func readWeight() float64 {
	if v, err := strconv.ParseFloat(os.Getenv("CANARY_WEIGHT"), 64); err == nil {
		return v
	}
	return 0.05 // 默认 5%
}

// 灰度中间件
func CanaryMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	// 1. 强制回滚
	if canaryWeight <= 0 {
		next(w, r)
		return
	}

	// 2. 读 cookie
	cookie, err := r.Cookie("canary")
	isCanary := false
	if err == nil && cookie.Value == "1" {
		isCanary = true
	} else {
		// 3. 一致性采样:用随机 token 模拟用户 ID
		token := r.Header.Get("X-Device-Id")
		if token == "" {
			b := make([]byte, 8)
			rand.Read(b)
			token = hex.EncodeToString(b)
		}
		h := fnv32a(token) % 10000
		isCanary = float64(h) < canaryWeight*10000
	}

	// 4. 写入 Context
	ctx := context.WithValue(r.Context(), canaryKey, isCanary)
	next(w, r.WithContext(ctx))
}

// 业务 Handler 示例
func home(w http.ResponseWriter, r *http.Request) {
	if r.Context().Value(canaryKey).(bool) {
		w.Write([]byte("new version"))
	} else {
		w.Write([]byte("old version"))
	}
}

func main() {
	n := negroni.New()
	n.Use(negroni.HandlerFunc(CanaryMiddleware))
	n.UseHandler(http.HandlerFunc(home))
	http.ListenAndServe(":8080", n)
}

// FNV-1a 哈希
func fnv32a(s string) uint32 {
	const prime32 = 16777619
	hash := uint32(2166136261)
	for i := 0; i < len(s); i++ {
		hash ^= uint32(s[i])
		hash *= prime32
	}
	return hash
}

关键点:

  • 中间件 只负责决策,不处理业务;
  • 用 环境变量 实时调整 CANARY_WEIGHT;
  • 日志与监控均通过 Context 透传 的 canaryKey 打标签,保证 可观测性。

拓展思考

  1. 多版本并行:若需 A/B/n 实验,可把灰度标识扩展为 version=canary_v1|canary_v2|baseline,并用 配置中心 下发 哈希环 规则,实现 千人千面。
  2. 网关层灰度:在 Ingress-Nginx 或 APISIX 做统一灰度,业务侧无需任何代码,只需在 Header 中携带 X-Canary: true,Negroni 中间件直接复用,实现 南北向与东西向流量统一治理。
  3. 自动止损:结合 Prometheus Alert,当 canary_version="new" 的错误率连续 2 分钟 > 1% 时,通过 Webhook 调用配置中心接口把 CANARY_WEIGHT 置 0,实现 1 分钟自愈。