Skip to content

Blocking calls in async event loop cause listen/pusher pod saturation under load #6020

Closed

Description

@beastoin

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_sync for sync routes, db_async for 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 uvloop to 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 requests with shared httpx.AsyncClient in 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_sync for existing sync routes until migrated
  • Migrate Translation to TranslationServiceAsyncClient
  • Evaluate global redis.asyncio migration scope

Recommended Issue Split

Keep #6020 as umbrella. Create child issues by execution stream:

  • P0 hotfix: asyncio.to_thread wrapping + uvloop + thread pool sizing
  • WS hot-path async I/O: httpx + hot-path redis.asyncio
  • Firestore async migration: dual-client for WS paths
  • Redis async migration: scoped then global

Files to Modify

  • backend/Dockerfile — add --loop uvloop to CMD
  • backend/main.py — set default executor size + add instrumentation
  • backend/utils/stt/vad_gate.py — bounded worker queue + dedicated executor
  • backend/routers/transcribe.py — wrap blocking calls with semaphore-bounded asyncio.to_thread()
  • backend/utils/app_integrations.py — rewrite with httpx.AsyncClient
  • backend/utils/translation.py — use TranslationServiceAsyncClient
  • backend/utils/webhooks.py — replace requests with httpx.AsyncClient
  • backend/utils/conversations/location.py — httpx.AsyncClient + add timeout
  • backend/routers/pusher.py — wrap Firestore and location calls
  • backend/database/redis_db.py — add async variant for hot-path calls
  • backend/database/conversations.py — introduce db_async for 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

  1. added
    p0
    on Mar 25, 2026
  2. beastoin commented on Mar 25, 2026

    @beastoin
    CollaboratorAuthor

    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)

    # Change Impact Detail
    1 Lower activeConnectionsPerPod 22→15 (listen) / 22→16 (pusher) HIGH Forces HPA to ~33-35 pods, spreads load thinner. Single biggest quick win.
    2 Increase probe timeoutSeconds 1→5 HIGH Tolerates short event loop stalls without failing probes.
    3 Uncomment CPU-based HPA target (70%) HIGH Prevents HPA scaling DOWN during cascade (when WS connections drop but CPU spikes). Currently HPA only watches WS count — sees fewer connections during incident → tries to scale down.
    4 Increase backend-listen CPU limit 2→3 MED 50% more burst headroom before CPU throttling. Nodes are n4-highcpu-4, can accommodate.

    Items 1-4 can go in a single Helm upgrade.

    Code + Helm changes (1-2 days)

    # Change Impact Detail
    5 /healthz HTTP probe endpoint HIGH Async heartbeat timer checks if event loop is alive vs just TCP accept queue. If timer stops → truly dead. If timer alive but load high → still ready.
    6 App-level connection limit / load shedding HIGH Reject new WS with 503 when pod exceeds threshold. Client retries on different pod. No service mesh needed.

    Slower infra changes (4-8 hours)

    # Change Impact Detail
    7 Node pool resize n4-highcpu-4 → n4-highcpu-8 MED Better bin-packing (4 pods/node), more burst room per pod.

    Not needed / no action

    • GKE BackendConfig: backend-listen uses direct TCP, not HTTP LB. Connection draining already configured (120s grace + 15s preStop).
    • PDB: Current 80% minAvailable is correct. PDB only protects voluntary disruptions; the incident was involuntary (probe kills).

    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

  3. beastoin commented on Mar 25, 2026

    @beastoin
    CollaboratorAuthor

    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

    Time Event Error Count
    14:44 Pusher keepalive ping timeout errors begin 81/min
    14:46 Peak pusher errors 228/min
    14:51 Second peak 237/min
    14:55 Prometheus scrape drops (pods going unready) 141/min
    14:57 Pods being killed 14/min
    15:20-15:29 Pusher retry storm during recovery 409/min peak

    Total: 2,350+ pusher 1011 errors in 12 minutes, 3,000+ retry warnings during recovery.

    Confirmed Cascade Mechanism

    Pusher service degradation (keepalive ping timeouts at 14:44)
      → 1011 close on audio_bytes WS connections
      → backend-listen closes client WS (code 1011)
      → app reconnects → new stream_handler
      → new pusher connect attempt (BLOCKING on event loop)
      → pusher still timing out → exponential backoff retries (BLOCKING)
      → event loop saturated (14:55, 11 min after first pusher errors)
      → TCP probe timeouts → pods marked unready
      → liveness kills pods → reconnect storm on survivors
      → recovery attempts also hit pusher retries → 3.5h extended outage
    

    Fix Priority Update

    P0 (immediate):

    1. PR fix(backend): unblock event loop during Deepgram WebSocket connect #6021 — asyncio.to_thread for connect_to_deepgram() (ready for merge)
    2. NEW: Pusher connection must also be non-blocking — connect_to_transcript_pusher() retry cycle blocks the event loop identically to the DG connect issue
    3. NEW: Circuit breaker for pusher retries — stop retrying a dead pusher instead of exponential backoff that saturates the event loop

    Remaining 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    p0

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions