如何在 Gunicorn 层根据 Cookie 分桶,实现后端无侵入的 A/B?
解读
面试官想验证两点:
- 你是否理解 Gunicorn 的 pre-fork 架构 与 WSGI 可插拔机制;
- 你是否能在 不修改业务代码 的前提下,用 纯 Gunicorn 层扩展 完成流量切分与染色。
国内大厂线上环境普遍用 Kubernetes + Ingress 做七层路由,但仍有大量场景(老服务、边缘节点、Serverless 容器)直接暴露 Gunicorn。此时若把 A/B 逻辑下沉到 Gunicorn,可 零侵入 地让 Django/Flask 代码感知不到实验流量,同时满足 审计合规(Cookie 里打实验标记,网关层可溯源)。
知识点
- WSGI 中间件协议:PEP 3333 规定
environ字典在start_response之前可被修改,因此可在 Gunicorn 侧插入自定义中间件。 - Gunicorn Server Hook:
pre_request/post_request钩子运行在 worker 进程空间,可读写environ与respiter,但 不能 修改响应体;真正的响应篡改需在 WSGI 层 完成。 - pre-fork 模型限制:master 只做
accept,无法看到 HTTP 报文;因此 Cookie 解析必须在 worker 内完成,不能 在 master 阶段做分流。 - 一致性哈希:国内 A/B 平台(如字节 ByteAir、阿里 Omega)要求同一用户 永居一桶,需把实验号写回 Cookie(
Set-Cookie: ab_ver=1; SameSite=Lax; Path=/),并 持久化 30 天。 - 性能红线:中间件必须 C 加速 或 纯 Python 无阻塞;若引入
geventworker,要禁用threading.local防止 greenlet 切换污染。 - 合规要求:国内《个人信息保护法》规定 用户标识需可撤销,因此 Cookie 名需加
<biz>_ab前缀,且提供 opt-out 接口(/__ab/optout返回204并清除 Cookie)。
答案
步骤一:编写 WSGI 中间件(单文件 ab_middleware.py),不依赖任何业务框架:
import hashlib
import re
from werkzeug.wrappers import Request, Response
class CookieBucketMiddleware:
def __init__(self, app, bucket_count=100, cookie_key='ab_ver'):
self.app = app
self.bucket_count = bucket_count
self.cookie_key = cookie_key
def __call__(self, environ, start_response):
req = Request(environ)
# 1. 读已有实验号
ver = req.cookies.get(self.cookie_key)
if ver is None or not ver.isdigit():
# 2. 用用户标识算桶;无标识则用 IP+UA 降级
uid = req.cookies.get('uid') or f"{req.remote_addr}:{req.headers.get('User-Agent','')}"
bucket = int(hashlib.md5(uid.encode()).hexdigest(), 16) % self.bucket_count
# 3. 国内常用 0-49 对照组,50-99 实验组
ver = '1' if bucket >= 50 else '0'
else:
ver = ver[:1] # 防御超长 Cookie
# 4. 把实验号写进 environ,供下游中间件或日志使用
environ['HTTP_X_AB_VER'] = ver
# 5. 调用真实应用
resp = self.app(environ, start_response)
# 6. 在响应头里种下 Cookie,SameSite 合规
def wrapped_start_response(status, headers, exc_info=None):
headers.append(('Set-Cookie', f'{self.cookie_key}={ver}; Path=/; Max-Age=2592000; SameSite=Lax'))
return start_response(status, headers, exc_info)
# 7. 若响应已是 Response 对象,直接改 headers;否则用迭代器
if isinstance(resp, Response):
resp.headers['Set-Cookie'] = f'{self.cookie_key}={ver}; Path=/; Max-Age=2592000; SameSite=Lax'
return resp(environ, start_response)
return resp(environ, wrapped_start_response)
步骤二:在 Gunicorn 启动配置文件 gunicorn_conf.py 里挂载中间件:
from ab_middleware import CookieBucketMiddleware
def when_ready(server):
server.log.info("AB 中间件已加载")
def post_fork(server, worker):
# 把原始 WSGI 应用包一层
worker.app.callable = CookieBucketMiddleware(worker.app.callable, bucket_count=100)
步骤三:启动命令 零侵入:
gunicorn -c gunicorn_conf.py myproject.wsgi:application \
-k gevent \
-w 8 \
--max-requests 10000 \
--max-requests-jitter 500
验证:
curl -H "Cookie: uid=12345" -I http://localhost/连续 100 次,同一 uid 永远返回同一 ab_ver;- 不带 Cookie 时,首次 302 会种 Cookie,第二次携带 Cookie 后 不再重新分桶;
- 业务代码只需读
request.META['HTTP_X_AB_VER'](Django)或request.headers['X-Ab-Ver'](Flask),无感知。
拓展思考
- 多实验并行:把 Cookie 值从单数字改成 位图(如
ab=1001表示第 0、3 号实验开启),中间件解析后把X-Ab-Bits注入请求头,支持 32 个实验正交。 - 动态推规:把分桶逻辑改为 远程配置(HTTP 拉取 JSON),在
when_ready钩子起 后台线程 每 30 s 更新,无需重启 Gunicorn;失败时 降级本地缓存,符合国内 “变更三可”(可灰度、可回滚、可观测)。 - worker 级缓存:用 共享内存(Python 3.8+
multiprocessing.shared_memory)缓存实验配置,避免 8 个 worker 重复拉取,降低 P99 延迟 3 ms。 - 合规撤销:提供
/__ab/withdraw接口,中间件拦截后 设置 Cookie Max-Age=0 并打审计日志,对接公司数据平台,满足 个人信息可撤销 条款。