Commit 1dbb048
Fix HTTPX thread-safety issue with thread-local connections for incremental rendering
Problem:
The HTTPX stream_bidi plugin has a critical limitation - only the thread that creates
the bidirectional streaming connection can write chunks to the request stream. This
causes race conditions in multi-threaded production environments (e.g., Puma) where
different HTTP requests run on different threads.
When the first request creates a connection on Thread A and stores it in an instance
variable, subsequent requests on Thread B cannot write to that connection, causing
connection errors and unpredictable behavior.
Solution:
Implement thread-local storage for incremental rendering connections. Each thread now
gets its own persistent bidirectional streaming connection stored in Thread.current
instead of a shared instance variable.
Changes:
- Modified `incremental_connection` to use `Thread.current[:react_on_rails_incremental_connection]`
- Added `reset_thread_local_incremental_connections` to properly clean up all thread-local connections
- Updated `reset_connection` to call the new cleanup method
- Removed `@incremental_connection` instance variable
Trade-offs:
- ✅ Eliminates race conditions and thread-safety issues
- ✅ Simple implementation using Ruby's built-in thread-local storage
- ✅ Each thread has isolated, persistent connection
- 1 parent 8703f5d commit 1dbb048
1 file changed
+13
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
10 | 10 | | |
11 | 11 | | |
12 | 12 | | |
13 | | - | |
14 | 13 | | |
15 | | - | |
| 14 | + | |
16 | 15 | | |
17 | 16 | | |
18 | 17 | | |
| |||
135 | 134 | | |
136 | 135 | | |
137 | 136 | | |
| 137 | + | |
| 138 | + | |
138 | 139 | | |
139 | | - | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
140 | 150 | | |
141 | 151 | | |
142 | 152 | | |
| |||
0 commit comments