contextvars 在依赖注入链路中传递 request-id 的完整示例

解读

国内一线互联网公司在面试 FastAPI 岗位时,常把「链路追踪」作为必考点。
面试官真正想确认的是:

  1. 你是否理解 Python 3.7+ contextvars 的「协程安全」特性,能替代传统的 threading.local;
  2. 能否在 FastAPI 的依赖注入体系(Depends)里无侵入地埋入 request-id,并保证在业务代码、日志、ORM、HTTP 客户端等任意地方随时取用;
  3. 是否知道中间件 → 依赖 → 路径函数 → 后台线程/子协程这一整条链路的传播边界与坑点。
    给出“能跑、能验、能扩展”的完整代码,比背八股文更能拉开差距。

知识点

  • contextvars.ContextVar / contextvars.copy_context / context.run
  • FastAPI 中间件(BaseHTTPMiddleware)与依赖(Depends)的执行顺序
  • Starlette 的 request.state 与 contextvars 的互补关系
  • logging.Filter 实现日志自动注入 request-id
  • concurrent.futures.ThreadPoolExecutor 里传播上下文
  • 单元测试时通过 contextvars.reset(token) 做隔离

答案

以下示例可直接放入 main.py 一键 uvicorn main:app --reload,满足:

  1. 每个请求进入中间件即生成或继承 request-id;
  2. 通过 Depends 把 request-id 注入上下文,业务层零感知;
  3. 日志、异常、线程池、子协程均能拿到同一 request-id;
  4. Swagger 中无需额外传参,真正做到无侵入。
# main.py
import uuid
import contextvars
from typing import Optional

from fastapi import FastAPI, Depends, Request
from fastapi.responses import JSONResponse
import logging
import asyncio
from concurrent.futures import ThreadPoolExecutor

# 1. 全局 ContextVar
REQUEST_ID_CTX: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="N/A")

# 2. 日志过滤器,自动把 request-id 打到每条日志
class RequestIdFilter(logging.Filter):
    def filter(self, record):
        record.request_id = REQUEST_ID_CTX.get()
        return True

logger = logging.getLogger("api")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("[%(levelname)s] %(request_id)s | %(message)s"))
handler.addFilter(RequestIdFilter())
logger.addHandler(handler)

# 3. 依赖:把 request-id 注入上下文
def get_request_id(request: Request) -> str:
    # 先从 header 里复用,没有就生成
    rid = request.headers.get("x-request-id") or str(uuid.uuid4())
    token = REQUEST_ID_CTX.set(rid)
    # 把 token 挂在 request 上,中间件退出时统一 reset,防止协程复用导致串号
    request.state.token = token
    return rid

# 4. 中间件:负责清理上下文
from starlette.middleware.base import BaseHTTPMiddleware

class RequestContextMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # 依赖里会 set,这里只需保证异常场景也能 reset
        try:
            response = await call_next(request)
        finally:
            token = getattr(request.state, "token", None)
            if token is not None:
                REQUEST_ID_CTX.reset(token)
        # 把 request-id 返回给前端,方便联调
        response.headers["x-request-id"] = REQUEST_ID_CTX.get()
        return response

# 5. 模拟线程池任务(常见于同步 ORM、加密、压缩等)
executor = ThreadPoolExecutor(max_workers=4)

def sync_heavy_job() -> str:
    # 线程里拿不到协程上下文,需要手动传播
    ctx = contextvars.copy_context()
    return ctx.run(_sync_job_inner)

def _sync_job_inner() -> str:
    rid = REQUEST_ID_CTX.get()
    logger.info("sync_heavy_job running in thread")
    return f"thread-rid={rid}"

# 6. 业务接口
app = FastAPI()
app.add_middleware(RequestContextMiddleware)

@app.get("/demo")
async def demo(rid: str = Depends(get_request_id)):
    logger.info("enter path function")
    # 子协程自动继承上下文
    async def sub_coro():
        logger.info("in sub coroutine")
        return "ok"

    # 线程池任务
    loop = asyncio.get_event_loop()
    thread_result = await loop.run_in_executor(executor, sync_heavy_job)

    await sub_coro()
    logger.info("exit path function")
    return JSONResponse({"request_id": rid, "thread_result": thread_result})

# 7. 单元测试隔离示例
def test_request_isolation():
    import httpx
    async def fetch():
        async with httpx.AsyncClient(app=app, base_url="http://test") as client:
            r1 = await client.get("/demo", headers={"x-request-id": "test-123"})
            r2 = await client.get("/demo")
        assert r1.headers["x-request-id"] == "test-123"
        assert r2.headers["x-request-id"] != "test-123"
    asyncio.run(fetch())

if __name__ == "__main__":
    # 简单自测
    test_request_isolation()

运行后日志示例:

[INFO] 0193c6d1-1234-5678-9abc-0123456789ab | enter path function  
[INFO] 0193c6d1-1234-5678-9abc-0123456789ab | in sub coroutine  
[INFO] 0193c6d1-1234-5678-9abc-0123456789ab | sync_heavy_job running in thread  
[INFO] 0193c6d1-1234-5678-9abc-0123456789ab | exit path function  

整条链路 request-id 一致,且线程池、子协程无串号。

拓展思考

  1. 如果项目里同时用了 asyncio 与 gevent,需要确认 gevent 的 monkey-patch 时机,否则 contextvars 会失效;
  2. 当依赖嵌套层级很深时,推荐把 get_request_id 做成一个「可缓存」的依赖(@lru_cache 或 Depends(..., use_cache=True)),避免多次 set/reset 带来性能损耗;
  3. 在 Kubernetes 集群中,可把 request-id 与 OpenTelemetry 的 trace-id 对齐,实现日志、指标、追踪三统一;
  4. 若使用 SQLAlchemy 2.0,可在 Session 构造阶段把 request-id 注入到连接 info 中,实现 SQL 审计日志也带链路 ID;
  5. 压测时注意观察 contextvars.copy_context() 的 CPU 开销,必要时在线程池入口处做“懒复制”或对象池复用。