i have multiple deepgram.STT objects running simul...
# ask-ai
r
i have multiple deepgram.STT objects running simultaneously in my code, after a fixed amount of time I get deepgram connection closed unexpectedly and the code worker stops. what is the problem?
t
Thanks for reaching out, Shahaf. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m looking at the issue where multiple
deepgram.STT
instances run concurrently and after some time you see
deepgram connection closed unexpectedly
and the worker stops. What’s happening (most likely) • Each
deepgram.STT
opens a streaming WebSocket. Running many at once can hit Deepgram’s concurrent-connection or rate limits, which will terminate connections and surface as “connection closed unexpectedly.” • The plugin has reconnection logic, but if retries exhaust (it will retry with exponential backoff up to many times) the stream throws a fatal error and can stop your worker. • Running many streams can also exhaust local resources (event loop, CPU, memory, or aiohttp session handling), which can lead to similar failures. What you can do next (practical steps) • Check Deepgram dashboard for rate-limit or concurrency/billing alerts and confirm your plan supports the number of parallel streams you need. • Add logging around STT lifecycle and reconnection attempts to capture the exact error and timing: ◦ Log the WebSocket close code and exception stack traces. ◦ Log retry attempts and when the reconnection loop gives up. • Limit concurrency: ◦ If real-time, use a semaphore to cap simultaneous STT objects. ◦ If offline/recorded audio, switch to non-streaming transcription or batch uploads instead of many simultaneous streams. • Ensure efficient resource usage: ◦ Share/reuse a single
aiohttp.ClientSession
where appropriate. ◦ Avoid buffering large in-memory audio for many streams. • Handle errors gracefully so a failed STT doesn’t crash the whole worker: ◦ Catch the STT error, call `end_input()`/`aclose()` and allow the worker to continue processing other tasks. To diagnose further, could you share: • A short code snippet showing how you create/manage
deepgram.STT
objects (how many, concurrency control, session usage)? • The exact error/log output around the disconnect (close code, exception text)? • Your Deepgram plan tier or observed concurrent connection count? With those I can point to the precise fix (concurrency limit change, code change, or retry handling). Would you like help formatting the logs or a small example to implement a semaphore around STT creation? Sources: livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt.py | plugins/deepgram/src/stt.ts | Quotas and limits | LiveKit docs
r
i use Pay As You Go i do real-time, what is semaphore? the error is in task_rcev
t
Thanks — I see you use Pay As You Go, you do real‑time STT, and the error occurs in
task_recv
. Here’s a concise explanation and what to do next. What a semaphore is • A semaphore limits how many concurrent operations can run at once. Think of it as N permits; a task must acquire a permit before opening a Deepgram stream and release it when done. If no permits remain, the task waits instead of opening another connection. Why that helps • Pay As You Go still enforces concurrent real‑time stream limits. Using a semaphore prevents your app from opening more simultaneous WebSocket streams than Deepgram allows, avoiding unexpected connection closures that surface in
task_recv
. Quick Python pattern (asyncio) • Create a semaphore sized to your allowed concurrency (example uses 5):
Copy code
import asyncio

sema = asyncio.Semaphore(5)

async def handle_track(track):
    async with sema:
        stt_stream = stt.stream()   # create Deepgram STT stream
        try:
            async for event in stt_stream:
                # process events
                pass
        except Exception as e:
            # log error from task_recv / connection closed
            logger.error("STT error in task_recv: %s", e, exc_info=True)
        finally:
            await stt_stream.aclose()
• Adjust the semaphore count to match the maximum concurrent streams your Deepgram plan supports. Other recommended steps • Check Deepgram console for concurrent stream usage / rate-limit events. • Add logging around
task_recv
to capture close codes and exception text. • Ensure you reuse an
aiohttp.ClientSession
where appropriate and avoid large in‑memory buffers. • Wrap STT work so a single failing stream doesn’t crash the whole worker. If you want, share: • the short snippet that creates STT streams (how many, where), and • the exact
task_recv
log/error text I’ll suggest the exact semaphore size and show how to integrate it into your worker. Sources: Speech-to-text (STT) models | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AI | Deepgram STT plugin guide | LiveKit docs
r
i dont think that's the reason, that's 4-10 minutes of silence and then crush, it doesn't change if i speak
t
Thanks — I hear that the disconnects happen after 4–10 minutes of silence and happen whether or not you speak, and that semaphore/concurrency feels unlikely. I’ll help narrow this down. Quick checklist and next steps I need from you • Share the exact error/log around the crash in
task_recv
(full stack trace and any WebSocket close code or exception text). • Confirm whether you use any VAD/endpointing (Silero VAD or Deepgram endpoint settings like
eager_eot_threshold
) or keep‑alive/heartbeat code. • Confirm how you open/close the STT stream: do you explicitly call
end_input()
or
aclose()
on silence or do you leave it open? • Tell me if you see any Deepgram-side messages in your Deepgram console (disconnects, rate-limit, or idle timeout events). What to check while you grab those logs • Look for WebSocket close codes or messages indicating idle timeout or normal closure. • Check Deepgram dashboard for any inactivity timeout notes or dropped connections around the timestamps. • Verify your agent code gracefully catches STT errors in the
task_recv
loop and closes/restarts the stream instead of letting the worker crash. Short mitigation you can try now • Add explicit keep-alive or periodic small audio/heartbeat to the stream during long silences to test if the connection is timing out. • Wrap
task_recv
processing in a try/except that logs errors and attempts a controlled reconnect (call
aclose()
and recreate the stream), so a single disconnect doesn’t crash the worker. If you share the
task_recv
log and a short snippet showing how you create/manage the STT stream, I’ll point to the exact lines to change and provide a small reconnection pattern to prevent the worker from stopping. Sources: Deepgram STT plugin guide | LiveKit docs | Deepgram STT | LiveKit docs | Silero VAD plugin | LiveKit docs | Building an Automated IVR Menu Caller | LiveKit docs