socketio / socket.io-postgres-adapter

The Socket.IO Postgres adapter, allowing to broadcast events between several Socket.IO servers
https://socket.io
MIT License
24 stars 8 forks source link

Each Namespace Holds a Connection #3

Closed dave-apex closed 2 years ago

dave-apex commented 2 years ago

First, we love this package and the opportunities that it opens up for us. Great job :).

We have an app that started having database connection problems after adding socket.io. After doing some digging it appears that the issue is that the postgres adapter holds a connection for each namespace. That would be fine for many apps but our design is based on custom namespaces. It appears that every namespace that is accessed by some user will then hold a connection indefinitely. Is that the expected behavior? Are there any patterns that could free up these connections when the last user disconnects from the namespace?

darrachequesne commented 2 years ago

It appears that every namespace that is accessed by some user will then hold a connection indefinitely.

Yes, that's indeed the current behavior, but I think we could change it.

As a temporary workaround, you can close the connection when the last user disconnects:

const namespace = io.of("/the-namespace");

namespace.on("connection", (socket) => {
  socket.on("disconnect", () => {
    const isLast = namespace.sockets.size === 0;
    if (isLast) {
      namespace.adapter.close();
    }
  });
});
dave-apex commented 2 years ago

Thanks makes a lot of sense. In the meantime, we have moved from Namespaces to Rooms and that is working fine for us.

darrachequesne commented 2 years ago

This should be fixed in version 0.3.0, implemented in https://github.com/socketio/socket.io-postgres-adapter/commit/651e28169185d91c7a1a86152d21aa265d5500f2.