Repository navigation
Description
Sync blocking calls in the async WebSocket handlers for /v4/listen (transcribe.py) and pusher saturate the event loop under load, causing TCP probe timeouts, pod kills, and reconnect storms. Root cause of multi-hour production outage (2026-03-24 14:56–18:24 UTC).
Codex-reviewed: All items verified against live code. Priorities, fix approaches, and phase order reviewed by Codex.
Deployment Context
- Single uvicorn worker per pod (single event loop per pod)
- Default asyncio thread pool: ~6 threads (Python default with 2-CPU limit)
- backend-listen: 2 CPU limit (burstable), 20-40 pods, 22 WS connections/pod
- pusher: 0.7 CPU limit (guaranteed QoS), 20-40 pods, 22 WS connections/pod
- TCP health probes: 10s interval, 30 failures = 300s before kill
- uvloop installed (uvicorn auto-detects, but should verify/pin with
--loop uvloop) - No service mesh / sidecars
Current Behavior
- 17 sync blocking call sites found across listen API, pusher, and shared utils (14 original + 3 found by Codex review)
- Under load, these calls stack up and starve the single event loop — TCP health probes time out, GKE kills pods, clients reconnect, creating a death spiral
Expected Behavior
All I/O and CPU-heavy work in async WebSocket handlers should be non-blocking — either using async-native client libraries, offloaded to a thread pool with adequate capacity, or moved to a separate process/service for CPU-bound work.
Affected Areas
P0 — Fix immediately (per-chunk or high-frequency hot path):
| # | File | Line | Description | Fix approach |
|---|---|---|---|---|
| 1 | utils/stt/vad_gate.py |
426 | Silero VAD neural network inference per audio chunk (~50+/s). CPU-bound — GIL blocks threads. | Bounded per-connection worker queue + dedicated ThreadPoolExecutor (ProcessPool has too much IPC/serialization overhead for 30ms chunks; existing VAD microservice is file-based, not streaming). |
| 2 | routers/transcribe.py |
2312, 2338, 2422 | dg_socket.send(chunk) — Deepgram SDK sync TCP write per chunk. |
asyncio.to_thread() with ordering preserved per connection. Do NOT fire-and-forget thread submits — use sequential await to maintain chunk order. |
| 4 | routers/transcribe.py |
880-892 | Firestore writes + zlib.compress() + AES encrypt every 0.6s. Mixed CPU+I/O. |
asyncio.to_thread() for immediate containment; migrate to async Firestore in Phase 3. Add semaphore to bound concurrency. |
| 8 | utils/app_integrations.py |
183-192, 511, 595 | Fake-async wrappers: async functions calling sync code with thread.join(). |
Replace requests with shared httpx.AsyncClient (strict connect/read timeouts, retries). Remove thread.join() pattern entirely. Do not create per-call clients. |
| 14 | routers/transcribe.py |
1783 | Lifecycle manager sync Firestore read every 5s per connection. Scales poorly with concurrent sockets. | asyncio.to_thread() immediate; async Firestore in Phase 3. |
P1 — Fix soon (feature-gated, lower frequency, or amplified during reconnect storms):
| # | File | Line | Description | Fix approach |
|---|---|---|---|---|
| 3 | utils/translation.py |
301, 360 | Sync Google Cloud Translate v3 gRPC + sync Redis cache. Feature-gated but 100ms+ latency. | translate_v3.TranslationServiceAsyncClient (verified available). Hot-path Redis calls via redis.asyncio. |
| 5 | database/conversations.py |
171 | Firestore read on cache miss + decompress/decrypt. Every 30s cache refresh. | asyncio.to_thread() immediate; async Firestore in Phase 3. |
| 6 | utils/webhooks.py |
118 | requests.post() to user webhook, 15s timeout. Blocks pusher event loop. |
Shared httpx.AsyncClient with strict timeouts. |
| 7 | utils/webhooks.py |
166 | requests.post() for audio bytes, 15s timeout. |
Same — shared async HTTP client. |
| 9 | utils/conversations/location.py |
32 | requests.get() to Google Maps, no timeout set — unbounded stall risk. |
httpx.AsyncClient + add explicit timeout. |
| 12 | routers/pusher.py |
136-137 | Sync Firestore reads at WS connect time. Moved from P2: reconnect storms make connect-path latency critical. | asyncio.to_thread() immediate; async Firestore in Phase 3. |
| 13 | routers/transcribe.py |
439, 454 | Sync Redis every 60s per active WS connection. Moved from P2: systemic sync Redis in async loop, scales with connection count. | redis.asyncio for hot-path Redis. |
| 15 | routers/transcribe.py |
527, 569, 465 | NEW (Codex): Credits/subscription path — get_remaining_transcription_seconds() (sync Firestore), get_user_valid_subscription() (sync Firestore), record_usage() (sync Firestore write). Runs in periodic async loop. |
asyncio.to_thread() immediate. |
P2 — Fix later (low frequency, session init/teardown):
| # | File | Line | Description | Fix approach |
|---|---|---|---|---|
| 10 | routers/pusher.py |
64, 77, 92 | Sync Firestore in async conversation processing. Low frequency. | Async Firestore client. |
| 11 | utils/other/storage.py |
63-77 | Sync GCS blob.exists()/reload(). Once per session init. |
asyncio.to_thread() or async GCS client. |
| 16 | routers/transcribe.py |
654, 660, 312 | NEW (Codex): Sync Firestore in WS startup path — is_exists_user(), get_user_private_cloud_sync_enabled(), get_user_language_preference(). Once per connection. |
asyncio.to_thread(). |
| 17 | database/user_usage.py |
38 | NEW (Codex): Sync Firestore write in usage accounting every minute. | asyncio.to_thread(). |
Systemic: database/redis_db.py:12 uses sync redis.Redis. However, global migration to redis.asyncio is NOT drop-in — API methods become coroutines, pipeline/pubsub/close semantics differ. Migrate hot-path WS Redis calls first, keep sync client for existing sync routes.
Solution — Industry Best Practice for Python Async on GKE
1. CPU-bound work needs dedicated executor, not just threads
VAD inference (#1): Use a bounded per-connection worker queue with a dedicated ThreadPoolExecutor. ProcessPoolExecutor has too much IPC/serialization overhead for 30ms audio chunks. The existing VAD microservice (charts/vad/) is file-upload-based, not streaming — not a drop-in replacement. Longer term, evaluate a streaming VAD service design.
2. I/O-bound work should use async-native clients
Verified available in current dependency versions:
google.cloud.firestore_v1.async_client.AsyncClient(firestore 2.17.0) — not drop-in: async transactions/query iteration differ. Use staged dual-client approach (db_syncfor sync routes,db_asyncfor WS hot paths).translate_v3.TranslationServiceAsyncClient(translate 3.20.2) — verified working.redis.asyncio.Redis(redis 5.0.8) — not drop-in: methods become coroutines, pipeline/pubsub/close semantics differ. Migrate hot-path first.httpx.AsyncClient— use shared instance with explicit timeouts and retries. Do not create per-call clients.
3. Thread pool must be sized for asyncio.to_thread() usage
Current default: ~6 threads. Must increase:
import asyncio
from concurrent.futures import ThreadPoolExecutor
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=64))Also add bounded concurrency (semaphore) to prevent moving saturation from event loop to threadpool.
4. Quick wins (minimal code changes)
- Pin uvloop: add
--loop uvloopto Dockerfile CMD (2-4x event loop throughput) - Consider HTTP health check endpoint instead of TCP probes (more resilient to event loop blocking)
5. Instrumentation (required before/after each phase)
- Event loop lag (asyncio debug mode or custom metric)
- Executor queue depth
- p95 WS handler latency
- TCP probe success rate
Recommended Fix Phases
Phase 1 — Emergency containment (hours):
- Enable uvloop explicitly in Dockerfile
- Increase default thread pool to 64
- Wrap P0 I/O items in
asyncio.to_thread()with semaphore bounds - Add event loop lag instrumentation
Phase 2 — Hot-path async I/O (days):
- Replace
requestswith sharedhttpx.AsyncClientin webhooks + integrations + location - Migrate WS-hot-path Redis calls to
redis.asyncio(not global migration yet) - Move VAD gate/send to bounded per-connection worker queue
Phase 3 — Async client migration (weeks):
- Introduce
db_async(Firestore AsyncClient) for listen/pusher hot paths only - Keep
db_syncfor existing sync routes until migrated - Migrate Translation to
TranslationServiceAsyncClient - Evaluate global
redis.asynciomigration scope
Recommended Issue Split
Keep #6020 as umbrella. Create child issues by execution stream:
P0 hotfix: asyncio.to_thread wrapping + uvloop + thread pool sizingWS hot-path async I/O: httpx + hot-path redis.asyncioFirestore async migration: dual-client for WS pathsRedis async migration: scoped then global
Files to Modify
backend/Dockerfile— add--loop uvloopto CMDbackend/main.py— set default executor size + add instrumentationbackend/utils/stt/vad_gate.py— bounded worker queue + dedicated executorbackend/routers/transcribe.py— wrap blocking calls with semaphore-boundedasyncio.to_thread()backend/utils/app_integrations.py— rewrite withhttpx.AsyncClientbackend/utils/translation.py— useTranslationServiceAsyncClientbackend/utils/webhooks.py— replacerequestswithhttpx.AsyncClientbackend/utils/conversations/location.py—httpx.AsyncClient+ add timeoutbackend/routers/pusher.py— wrap Firestore and location callsbackend/database/redis_db.py— add async variant for hot-path callsbackend/database/conversations.py— introducedb_asyncfor WS paths
Impact
Fixes root cause of event loop saturation under load. No functional behavior changes — same operations, non-blocking execution.
Verification
- Codex reviewed all 17 call sites — all verified as genuine sync-in-async blocking
- Deployment config verified with ops team
- Async client availability verified against installed package versions (firestore 2.17.0, translate 3.20.2, redis 5.0.8)
- VAD microservice confirmed as file-upload-only (not streaming), ruling out direct offload
by AI for @beastoin
Activity
beastoin commentedon Mar 25, 2026
Infrastructure Mitigations (while code fixes are in progress)
Infra audit by ops team. Current live state: backend-listen 25 pods (19.9/22 WS target), pusher 22 pods (21.5/22 WS target) — both running warm with little headroom.
Immediate Helm-only changes (5 min deploy, zero downtime)
activeConnectionsPerPod22→15 (listen) / 22→16 (pusher)timeoutSeconds1→5Items 1-4 can go in a single Helm upgrade.
Code + Helm changes (1-2 days)
/healthzHTTP probe endpointSlower infra changes (4-8 hours)
Not needed / no action
Key insight: HPA works against us during cascades
Current HPA only watches WS connection count. During pod kills, clients disconnect → WS count drops → HPA sees lower metric → scales DOWN. Adding CPU as secondary metric (already commented out in values) fixes this — dual-metric HPA uses whichever metric suggests the MOST replicas.
by AI for @beastoin
fix(backend): wrap connect_to_deepgram in asyncio.to_thread to unbloc…
test(backend): add test verifying asyncio.to_thread usage in DG connect
fix(backend): wrap connect_to_deepgram in asyncio.to_thread to unbloc…
test(backend): add test verifying asyncio.to_thread usage in DG connect
beastoin commentedon Mar 25, 2026
Root Cause Confirmed: Pusher Keepalive Timeout Cascade
Production Cloud Logging confirms the 2026-03-24 outage (14:56-18:24 UTC) was triggered by pusher keepalive ping timeouts starting at 14:44 — 11 minutes before the first pod failures.
Timeline
keepalive ping timeouterrors beginTotal: 2,350+ pusher 1011 errors in 12 minutes, 3,000+ retry warnings during recovery.
Confirmed Cascade Mechanism
Fix Priority Update
P0 (immediate):
asyncio.to_threadforconnect_to_deepgram()(ready for merge)connect_to_transcript_pusher()retry cycle blocks the event loop identically to the DG connect issueRemaining question: What caused the initial pusher keepalive timeouts at 14:44? Need to check pusher pod logs from 14:40-14:50.
by AI for @beastoin
fix(backend): wrap connect_to_deepgram in asyncio.to_thread to unbloc…
test(backend): add test verifying asyncio.to_thread usage in DG connect
fix(backend): wrap connect_to_deepgram in asyncio.to_thread to unbloc…
test(backend): add test verifying asyncio.to_thread usage in DG connect
fix(backend): wrap connect_to_deepgram in asyncio.to_thread to unbloc…
test(backend): add test verifying asyncio.to_thread usage in DG connect
fix(backend): wrap connect_to_deepgram in asyncio.to_thread to unbloc…
test(backend): add test verifying asyncio.to_thread usage in DG connect