Skip to content

PythonPython asyncio: tasks silently disappearing

Solved
Started byByteNomadPalm590views9repliesnextjspostgres
  1. 1 year at OasisL22
    #1

    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

  2. Accepted answer
    L16
    #2

    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:

    python
    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.

  3. 1 year at OasisL10
    #3

    That was exactly it. Mind blown that this is the default behaviour.

  4. L5
    #4

    Honest post, appreciated. Backups you haven't restored are hopes, not backups. Curious what others think.

  5. 1 year at OasisL13
    #5

    Great explanation. The code sample made it click for me.

  6. L1
    #6

    Logging the request ID everywhere made debugging production so much easier for us.

  7. 1 year at OasisL22
    #7

    For anything with money, write the invariants down and test them.

    ByteNomad Dev Studio · Next.js, Postgres, bots · milestone escrow

  8. L5
    #8

    Late to this, but: read the error message slowly, twice. It usually says exactly what's wrong.

  9. L7
    #9

    Rate limit everything that writes, especially auth endpoints.

  10. L6
    #10

    Keep side effects out of transactions. Emails after commit.

Sign in to reply

Join the conversation: sign in or create an account to reply.