在 FastAPI 的 BackgroundTasks 中,如何传递 SpanContext
解读
面试官抛出这道题,核心想验证三件事:
- 你是否真的在生产环境用 Jaeger 做过端到端链路追踪,而不是只跑过 Demo;
- 对 Python 异步生态(asyncio 上下文变量)与 OpenTelemetry 的 Context Propagation 机制是否熟悉;
- 面对 FastAPI 的 BackgroundTasks(本质是 Starlette 的 BackgroundTask,跑在线程池里)这一“跨线程”场景,能否把 SpanContext 完整、安全地带过去,并保证下游链路不“断链”。
国内一线厂用 FastAPI 做高并发网关或 BFF 层的情况越来越多,背景任务常用来写日志、发消息、刷缓存。如果 SpanContext 丢在后台线程,Jaeger UI 就会出现“孤链”或“断链”,SRE 排障直接抓瞎,所以这道题是“真刀真枪”的生产痛点。
知识点
- OpenTelemetry 的 Context 本质上是 asyncio 的 contextvars 封装,只在同一线程内的协程间自动传播;
- BackgroundTasks 由 Starlette 在响应返回后扔给 concurrent.futures.ThreadPoolExecutor 执行,跨线程后 contextvars 会被清空;
- 跨进程/跨线程传播必须显式“序列化”SpanContext,再用 inject → extract 模式还原;
- 官方推荐载体是 opentelemetry.propagators.textmap.TextMapPropagator(W3C Trace-Context 或 B3),把 traceparent/tracestate 注入普通字典即可;
- 后台任务侧需用 opentelemetry.trace.set_span_in_context 把还原出的 Span 重新塞进当前上下文,后续任何 get_tracer().start_as_current_span 才能挂在原链路上;
- 如果后台任务里还有异步函数(如 httpx.post),需要再用 asyncio.create_task 并绑定还原后的 Context,否则二次断链;
- 内存泄漏点:后台任务若引用了原请求的大对象,可能导致闭包生命周期过长,需用弱引用或 Pydantic 的 copy_on_model_validate 规避。
答案
生产级最小可用代码(可直接贴在 FastAPI 项目里跑):
from fastapi import FastAPI, BackgroundTasks
from opentelemetry import trace, propagate
from opentelemetry.trace import SpanContext, NonRecordingSpan
from opentelemetry.propagators.textmap import DictGetter
import asyncio
import contextvars
app = FastAPI()
tracer = trace.get_tracer(__name__)
propagator = propagate.get_global_textmap()
# 1. 请求主链路
@app.post("/order")
async def create_order(tasks: BackgroundTasks):
with tracer.start_as_current_span("create_order") as span:
# 把当前 SpanContext 序列化到普通 dict
carrier = {}
propagator.inject(carrier)
# 丢给后台线程
tasks.add_task(do_in_background, carrier)
return {"ok": True}
# 2. 后台任务函数
def do_in_background(carrier: dict):
# 在子线程里还原 SpanContext
ctx = propagator.extract(carrier, getter=DictGetter())
span_context = trace.get_current_span(ctx).get_span_context()
# 重新包装成 NonRecordingSpan 并绑定到当前线程
span = NonRecordingSpan(span_context)
ctx = trace.set_span_in_context(span)
# 后续任何新建 span 都会挂在原链路上
with tracer.start_as_current_span("do_in_background", context=ctx):
# 模拟 IO 密集逻辑
asyncio.run(send_msg())
async def send_msg():
# 如果后台任务里还有异步调用,必须再把 ctx 传进来
with tracer.start_as_current_span("send_msg"):
...
关键点复盘:
- inject 在请求线程做,extract 在后台线程做,中间用普通 dict 做载体,零第三方依赖;
- 后台线程里先还原出 SpanContext,再包成 NonRecordingSpan(只读,不占内存),用 set_span_in_context 绑回去;
- 若后台任务里还有异步协程,需要把 Context 对象显式传进去,否则二次断链。
拓展思考
- 如果后台任务量极大(每日千万级),dict 载体可以换成字节数组(propagator.inject 到 bytearray,再 base64 编码),减少一次内存拷贝;
- 对延迟极敏感的场景,可把 BackgroundTasks 换成 celery + opentelemetry-instrumentation-celery,利用消息头传播,彻底避开线程池;
- 国内部分自研注册中心(如 Nacos)支持直接把 trace-id 作为服务元数据推送,可做“链路染色”灰度,结合 BackgroundTasks 的 SpanContext 回写,实现灰度流量一键追踪;
- 安全合规:后台任务若落到日志文件,trace-id 属于可关联用户行为的标识,需做脱敏(打码后四位)或走内网 ELK,避免 GDPR/《个人信息保护法》风险;
- 未来 FastAPI 可能支持任意可等待对象作为后台任务(PEP 692),一旦合并,opentelemetry-python 社区会提供官方 async background instrumentation,届时只需一行
FastAPIInstrumentor().instrument()即可自动完成 SpanContext 传播,今天的手动方案将成为历史,但理解其原理仍是面试加分项。