0
# Context Management
1
2
Context variables for storing and accessing correlation IDs throughout async request and task execution, providing thread-safe access to tracking identifiers across the entire application lifecycle.
3
4
## Capabilities
5
6
### Request Correlation ID
7
8
Context variable that stores the correlation ID for the current HTTP request, making it accessible throughout the request processing lifecycle.
9
10
```python { .api }
11
correlation_id: ContextVar[Optional[str]]
12
```
13
14
This context variable:
15
- **Default Value**: `None`
16
- **Scope**: HTTP request lifecycle
17
- **Thread Safety**: Automatically isolated per async context
18
- **Usage**: Set by middleware, accessed by logging filters and application code
19
20
The `correlation_id` is automatically set by `CorrelationIdMiddleware` and remains available throughout the entire request processing, including:
21
- Route handlers and business logic
22
- Database operations and external API calls
23
- Background tasks spawned during request processing
24
- Log statements and error handling
25
26
### Celery Parent ID
27
28
Context variable that tracks the correlation ID of the parent process that spawned the current Celery task, enabling hierarchical tracing across distributed task processing.
29
30
```python { .api }
31
celery_parent_id: ContextVar[Optional[str]]
32
```
33
34
This context variable:
35
- **Default Value**: `None`
36
- **Scope**: Celery task execution
37
- **Purpose**: Track which process/request spawned the current task
38
- **Usage**: Set by Celery extension hooks, accessed by logging filters
39
40
Use cases for parent ID tracking:
41
- Tracing task chains and workflows back to originating requests
42
- Understanding task dependency hierarchies
43
- Correlating distributed task processing with web requests
44
- Debugging complex async workflows
45
46
### Celery Current ID
47
48
Context variable that stores a unique identifier for the current Celery task process, providing task-specific correlation tracking.
49
50
```python { .api }
51
celery_current_id: ContextVar[Optional[str]]
52
```
53
54
This context variable:
55
- **Default Value**: `None`
56
- **Scope**: Celery task execution
57
- **Purpose**: Unique identifier for the current task process
58
- **Usage**: Set by Celery extension hooks, accessed by logging filters
59
60
The current ID can be:
61
- Generated UUID for each new task (default behavior)
62
- Celery's internal task ID (when `use_internal_celery_task_id=True`)
63
- Custom ID from configured generator function
64
65
## Usage Examples
66
67
### Accessing Correlation ID in Application Code
68
69
```python
70
from asgi_correlation_id import correlation_id
71
import logging
72
73
logger = logging.getLogger(__name__)
74
75
async def process_data(data):
76
# Get current correlation ID
77
current_id = correlation_id.get()
78
79
if current_id:
80
logger.info(f"Processing data for request {current_id}")
81
else:
82
logger.info("Processing data outside request context")
83
84
# Process data...
85
return result
86
```
87
88
### Manual Context Management
89
90
```python
91
from asgi_correlation_id import correlation_id
92
93
async def background_task():
94
# Set correlation ID for background processing
95
correlation_id.set("background-task-123")
96
97
# Process task...
98
logger.info("Background task processing") # Will include correlation ID
99
100
# Clear when done (optional, context will be cleaned up automatically)
101
correlation_id.set(None)
102
```
103
104
### Celery Task Context
105
106
```python
107
from asgi_correlation_id import celery_current_id, celery_parent_id
108
from celery import Celery
109
110
app = Celery('tasks')
111
112
@app.task
113
def process_task(data):
114
current = celery_current_id.get()
115
parent = celery_parent_id.get()
116
117
logger.info(f"Task {current} spawned by {parent}")
118
119
# Process task...
120
return result
121
```
122
123
## Context Variable Behavior
124
125
### Automatic Cleanup
126
127
Context variables are automatically managed:
128
- **HTTP Requests**: Cleaned up when request completes
129
- **Celery Tasks**: Manually cleaned up by extension hooks
130
- **Background Tasks**: Follow async context rules
131
132
### Thread Safety
133
134
All context variables use Python's `contextvars` module, providing:
135
- Automatic isolation between concurrent requests
136
- Inheritance by spawned async tasks
137
- Thread-safe access patterns
138
- No manual synchronization required
139
140
### Inheritance
141
142
Context variables are inherited by:
143
- Async tasks spawned during request processing
144
- Celery tasks when properly configured with extensions
145
- Background threads created with `contextlib.copy_context()`
146
147
## Types
148
149
```python { .api }
150
from contextvars import ContextVar
151
from typing import Optional
152
153
# Context variable type definitions
154
CorrelationIdVar = ContextVar[Optional[str]]
155
CeleryParentIdVar = ContextVar[Optional[str]]
156
CeleryCurrentIdVar = ContextVar[Optional[str]]
157
```