Should we close long living connections?

55 views
Skip to first unread message

Nishant Varma

unread,
Mar 7, 2025, 3:17:05 AMMar 7
to Pika
Hello all,

We have long-lived connections that recreates itself when broken:

class RMQ():
    def __init__(self):
        self.connection = ...

    def recreate(self):
        self.connection = ...

    def publish(self):
        """All methods have retry logic to restore connection."""
        try:
            self.connection.channel.basic_publish(...)
        except AMQPConnectoinError:
            self.recreate()
            self.connection.channel.basic_publish(...)

    def __del__(self):
        if self.connection.is_open:
            self.connection.close()

Should we explicitly close connections during program shutdown? If so, where should we do it: atexit or some other place?

Putting this logic in __del__ doesn't seem to work as the underlying socket is
already closed. Pytest even hangs if we simulate a reconnection
scenario. __del__ behaviour is unpredictable as per:

1) https://docs.python.org/3/reference/datamodel.html#object.__del__
2) https://github.com/PyMySQL/PyMySQL/issues/961

Thanks in advance,
Nishant
Reply all
Reply to author
Forward
0 new messages