Yes, it is possible that request_transcription will run again before it finishes running — if it is a regular synchronous function.
Let’s break this down:
🔍 Your Code Overview
You have an async for loop receiving messages over a WebSocket. Each time a message is received and parsed as a TranscriptionRequestMessage, you call:
response_message = request_transcription(payload)
await websocket.send(models.pack_message(response_message))
Now, the critical question is:
Is request_transcription an async def function?
- ✅ If yes → you should
await request_transcription(...)
- ❌ If no → it's a synchronous function, and calling it blocks the event loop until it completes.
⚠️ Why This Matters
Since you're inside an async for loop (receiving from a WebSocket), each message is handled in the context of an asynchronous event loop.
However, if request_transcription is a blocking/synchronous function, and it does heavy processing (like audio transcription or large file parsing), then:
- It will block the entire event loop.
- Other incoming messages won’t be processed during that time.
- And more importantly to your question: It cannot be "run again" concurrently because Python’s asyncio runs coroutines one at a time unless explicitly told to do so.
But if request_transcription is an async function and you forget to await it, like:
response_message = request_transcription(payload) # <-- forgot await
Then response_message becomes a coroutine object instead of a result, which may raise an error when passed into models.pack_message(...) — but not necessarily start another execution.
🧠 So What Causes Re-entrancy?
The only way request_transcription could be called again before finishing is if you schedule it to run concurrently using something like:
asyncio.create_task(request_transcription(...))
or
await asyncio.gather(
request_transcription(...),
request_transcription(...),
)
In your current code, this isn't happening. You're processing messages sequentially.
✅ Summary
| Scenario | Can request_transcription run again before finishing? |
|---|
request_transcription is sync | ❌ No (but it blocks the loop; only one runs at a time) |
request_transcription is async and you use await | ❌ No (sequential execution) |
request_transcription is async and you don't await it (e.g., create a task) | ✅ Yes |
💡 Recommendations
-
If request_transcription is CPU-intensive, offload it to a thread pool:
loop = asyncio.get_event_loop()
response_message = await loop.run_in_executor(None, request_transcription, payload)
-
If it's already async, make sure to await it properly:
response_message = await request_transcription(payload)
-
If you want concurrent handling of multiple requests, spawn tasks:
task = asyncio.create_task(handle_request(payload))
...
async def handle_request(payload):
response_message = await request_transcription(payload)
await websocket.send(...)
Let me know what kind of function request_transcription is, and I can give you the best version of the code!