FastAPI - Design of tracking_id

Introduction In real business scenarios, tracing a request’s complete processing path in logs based on a tracking_id is a common requirement. However, FastAPI does not provide this functionality out of the box, so developers need to implement it themselves. This article introduces how to add a tracking_id to the entire request lifecycle based on contextvars and automatically record it in logs. What is contextvars Python 3.7 added a module contextvars to the standard library, which stands for “Context Variables”. It is typically used to implicitly pass some environmental information variables, similar to threading.local(). However, threading.local() is thread-specific, isolating data states between threads, while contextvars can be used in asynchronous coroutines within the asyncio ecosystem. PS: contextvars can not only be used in asynchronous coroutines but can also replace threading.local() in multi-threaded functions. ...

December 11, 2025 · 11 min · Rainux He