A_L
A_L

Reputation: 1146

Meteor data subscription strategy

I'd like some advise on when to subscribe to data on the client. Subscribing upfront to all needed data is the easiest but I would imaging there could be a heavy performance hit on first load. Using Iron-Router, subscription can be done during routing, then data is populated as needed and you have waitOn, which is cool.

Subscribing in routes though (esp. in big projects) would surely become a nightmare to manage because there is no global view of what data has already been subscribed to. Related to this - what happens if the same subscription is called multiple times, from different pages?

Upvotes: 3

Views: 188

Answers (1)

David Weldon
David Weldon

Reputation: 64312

You are correct in assuming that activating all subscriptions immediately isn't a good idea. You pay a performance penalty on both the server and the client every time you activate a subscription. If you want to maximize performance, your goals should be:

  1. Delay making subscriptions for as long as you can.
  2. Publish only the data you need.

Have a look at the following example:

Meteor.subscribe('news');

Tracker.autorun(function() {
  if (Meteor.user()) {
    Meteor.subscribe('friends');
    Meteor.subscribe('room', Session.get('roomId'));
  }
});
  • The news subscription is activated for all clients. Generally you want to avoid this, but maybe it's a requirement that everyone (signed in or not) should see some news. This is a good time to remember goal (2): Consider publishing only the N most recent news items instead of all of them.
  • The other subscriptions will only be activated when the user is logged in (saves resources and delays subscriptions).
  • The friends subscription changes based on the roomId session variable which could be set by the router.

I have a complex production app with a lot of routes, and I personally find having a single subscriptions file easier to maintain. That being said, I think this is a matter of taste so you'll need to try both ways and see what you are most comfortable with.

The answer to your last question is that the published documents get merged. If you activated two subscriptions for the same collection, and each published the same N documents, you would have N documents on the client. If P1 published N documents, and P2 published a M documents, you would have M union N documents on the client. This is talked about in more detail in the meteor book.

Upvotes: 2

Related Questions