Server cleanup after a client disconnects

One technique is to implement a “keepalive” method that each client regularly calls. This assumes you’ve got a user_id held in each client’s Session.

// server code: heartbeat method
Meteor.methods({
  keepalive: function (user_id) {
    if (!Connections.findOne(user_id))
      Connections.insert({user_id: user_id});

    Connections.update(user_id, {$set: {last_seen: (new Date()).getTime()}});
  }
});

// server code: clean up dead clients after 60 seconds
Meteor.setInterval(function () {
  var now = (new Date()).getTime();
  Connections.find({last_seen: {$lt: (now - 60 * 1000)}}).forEach(function (user) {
    // do something here for each idle user
  });
});

// client code: ping heartbeat every 5 seconds
Meteor.setInterval(function () {
  Meteor.call('keepalive', Session.get('user_id'));
}, 5000);

Leave a Comment