How Meteor manage Mongo connections?

Hello everyone,
we have an app and see that number of Mongo connections grow as users login and use our app. We do not see those connections being released after users close browser windows and we suspect that’s causing performance issues… Few questions, if you don’t mind:

  1. How db connections are managed in Meteor? Are they managed by Meteor, Node or Mongo itself decide how many connections to open and maintain?
  2. What’s causing the growth of open Mongo connections? Is that ‘one-per-subscription’ or ‘one-per-user’ kind of thing?
  3. Are we supposed to explicitly track user activity and close connections/subscriptions in our app?

Thank you!

Hi,

Mongo connections in Meteor are managed per cursor. Each cursor represents a unique query. All documents matched by this query will be stored into a cache which is Minimongo. When 2 clients subscribe with exactly the same query, then there will only be one cursor connected. It basically means that in order to reduce the amount of connections, you will have to reuse queries.

You can reuse queries by letting people subscribe to a cursor with exactly the same mongo selector.

That’s good to know, thank you!
If I understand you correctly, that means Meteor is supposed to close/release a DB connection once all clients stop their subscription to connection’s cursor, correct? Are we supposed to manually stop all subscriptions when user close the browser or Meteor track that and does that for us somehow?

Thank you!

If you close your browser, all subscriptions will stop. Meteor does this with its live connection. When there is a disconnect, the subscription will be cancelled. Same thing for when templates or components are destroyed / unmounted eg:

const ReactComponent = () => (<div>Some stuff</div>);

export default withTracker(() => {
  Meteor.subscribe('articles'); // Will unsubscribe
})(ReactComponent);

Similarly

Template.something.onCreated(function() {
  this.subscribe('articles'); // Will unsubscribe on destroy
});

Thank you, @cloudspider!