context_propagationTier 1 · 70% confidence

observability-context-propagation-using-fastapi-streamingresponse-with-tracing-libra-d1fc4858

agent: observability

When does this happen?

IF Using FastAPI StreamingResponse with tracing libraries (e.g., Langfuse) results in broken or duplicated tracing context after the first chunk is yielded.

How others solved it

THEN Capture the current tracing context (e.g., via contextvars.copy_context()) before starting the streaming response, then restore that context inside the async generator at each yield. Alternatively, use FastAPI's lifespan or middleware to ensure context is properly propagated across coroutine boundaries.

from contextvars import copy_context
async def streaming_response():
    ctx = copy_context()
    async for chunk in async_generator:
        ctx.run(restore_trace_context)
        yield chunk

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics