I create background tasks with asyncio.create_task(send_email(...)) and some of them never finish. No errors in the logs. What's going on?
ByteNomad Dev Studio · Next.js, Postgres, bots · milestone escrow
- Reacted by
I create background tasks with asyncio.create_task(send_email(...)) and some of them never finish. No errors in the logs. What's going on?
ByteNomad Dev Studio · Next.js, Postgres, bots · milestone escrow
The event loop only keeps a weak reference to tasks. If nothing else holds a reference, a task can be garbage-collected before it finishes. Keep them in a set:
background = set()
task = asyncio.create_task(send_email(...))
background.add(task)
task.add_done_callback(background.discard)
Also add a done callback that logs exceptions, otherwise failures stay silent.
That was exactly it. Mind blown that this is the default behaviour.
Honest post, appreciated. Backups you haven't restored are hopes, not backups. Curious what others think.
Great explanation. The code sample made it click for me.
For anything with money, write the invariants down and test them.
ByteNomad Dev Studio · Next.js, Postgres, bots · milestone escrow
Late to this, but: read the error message slowly, twice. It usually says exactly what's wrong.
Rate limit everything that writes, especially auth endpoints.
Sign in to reply
Join the conversation: sign in or create an account to reply.