Trending

World technology news

→
Isolating concurrent request trace identifiers with Python 3.7 contextvars
Software Engineering · 2018
Software Engineering2018

Isolating concurrent request trace identifiers with Python 3.7 contextvars

Two asyncio tasks preserve separate trace identifiers while suspended together. A tested example shows context inheritance and restoration.

Archive retrospective · Topic year 2018

Developer's JournalPublished: Dec 5, 20266 min read
Reading progress0%
In this article
  1. Two requests on one event loop
  2. Task creation sets the boundary
  3. Running the local example
  4. Restoration and cancellation
  5. Keep trace identifiers at the observability boundary
  6. Evidence from interleaved execution
  7. A small migration before changing the service

Two requests on one event loop

A warehouse import service prepares files for two stores in one process. Each request has its own trace identifier. A validator may wait for an upstream response while the event loop starts work for the other store. With a module-level variable, that other task can overwrite the identifier. When the first request resumes, its logs may use the second store's trace. A single operating-system thread still allows those operations to interleave at suspension points. PEP 567 introduced contextvars in Python 3.7 for small values that travel with an execution context. This example stores identifiers such as A-17 or B-29. File paths, access checks and delivery outcomes stay explicit inputs and outputs. A logging formatter can read a trace deep inside a call chain, while the functions implementing the import retain visible business inputs.

Task creation sets the boundary

The parent sets its identifier to batch before creating two worker tasks. An asyncio task inherits the context current at creation and runs its coroutine with that context. Each worker can then rebind the identifier without changing what the parent or sibling sees. Moving create_task past another parent assignment would change the value inherited by the task. Merely constructing a coroutine object earlier does not create its independent task context. The example uses two Event objects to tell the parent that both workers have set their values. A third Event holds the workers until the parent has checked its own value. This rendezvous makes the test independent of guessed sleep intervals and processor speed. The stored identifier is an immutable string. Context copying does not deep-copy an object stored as a value, so using a shared mutable dictionary here would introduce another source of interference.

Application flowConceptual sketch · summary of the article's technical flow

Running the local example

Worker A announces its readiness after setting A-17, and worker B does so after setting B-29. Both wait for the same release signal. The parent reads batch before releasing them. When the workers resume, each reads its own identifier again. The gather call returns results in argument order, regardless of which worker finishes first. On Windows with Python 3.12.10, the local run printed tasks: A-17, B-29, parent: batch and outside: -. The 3.7 release notes document the original feature. The local example uses the current installed runtime. Run the script with assertions enabled so a value mismatch causes a failure. An additional failure-path test could raise an exception before releasing a worker, check the reported task error and confirm that the parent still reads batch.

import asyncio
import sys
from contextvars import ContextVar

request_id = ContextVar('request_id', default='-')


async def worker(label, ready, proceed):
    token = request_id.set(label)
    try:
        ready.set()
        await proceed.wait()
        assert request_id.get() == label
        return request_id.get()
    finally:
        request_id.reset(token)
        assert request_id.get() == 'batch'


async def main():
    token = request_id.set('batch')
    try:
        ready_a, ready_b, proceed = (asyncio.Event() for _ in range(3))
        a = asyncio.create_task(worker('A-17', ready_a, proceed))
        b = asyncio.create_task(worker('B-29', ready_b, proceed))
        await ready_a.wait()
        await ready_b.wait()
        assert request_id.get() == 'batch'
        proceed.set()
        print('tasks:', ', '.join(await asyncio.gather(a, b)))
        print('parent:', request_id.get())
    finally:
        request_id.reset(token)
    print('outside:', request_id.get())


print('Python', sys.version.split()[0])
asyncio.run(main())

Restoration and cancellation

ContextVar.set returns a token. Reset with that token restores the previous binding. If the variable had no binding, reset removes the newly introduced one and get can return the defined default. Imagine an HTTP request starting with a connection identifier and temporarily using a different identifier while processing a nested batch. Restoring the earlier value lets the final log belong to the connection again. A finally block places restoration on both the ordinary return and exception paths. It can also run when cancellation is delivered at a wait point. If cancellation triggers cleanup in a new task, consider which context will be current at that task's creation. Keep the token with its variable and execution scope. Transferring it to a sibling task cannot restore the original worker's binding there.

Keep trace identifiers at the observability boundary

A trace identifier labels log activity. Authorization still needs explicit checks on the stores and inventory rows a requester may access. Detached work can outlive an HTTP request. A task created within that request may continue to label its logs with the old trace even after the response, which can hide the start of a separate job in operational queries. Give durable queue messages an explicit job identifier and establish a new scope in the consumer. Check the guarantees of the executor used when moving work to a different thread. For work sent across a process or network boundary, pass any needed identifier in a defined protocol field and validate it on receipt. Treat the data needed to authorize, validate and persist work as visible application inputs throughout the journey.

Evidence from interleaved execution

Two requests completed one after another offer weak evidence of isolation. This test reads the parent value while both tasks are suspended and verifies each worker's value after both have been released. Add a nested set and reset to test whether an enclosing value is restored. In production logs, record the trace in its own field so an investigator can query it without matching arbitrary text. The start, validation and result messages for one import should share a value while a concurrent request uses a distinct one. Define how an empty trace is represented so process startup and other context-free messages remain understandable. The example exercises task binding for one small immutable value. Decisions about sampling, redaction and log retention belong to the logging system. The test makes no throughput measurement.

A small migration before changing the service

Start by changing only the logging formatter to read the context variable. Keep explicit function parameters wherever they still support other behaviors. Repeat the same two-import test and compare the business outcome with the earlier version as well as the trace fields. Check where a durable queue consumer creates a fresh scope. If a request suddenly falls back to the default, inspect the entry point where the binding should have been set. A small migration makes the uncovered path visible while the rest of the import contract remains testable.

Further reading / Referencehttps://peps.python.org/pep-0567/ ↗
500 reads ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.