Search code examples
node.jsreal-timelong-polling

implementing long polling with nodejs


I implemented social-network-like notification, using long-polling with nodeJs

database, I'm using redis and cassandra

I saved a timestamp as "user_read" in redis

everytime users read the notifications, I refresh the "user_read"

when database got notifications timestamp larger than "user_read"

I will respond them to users

my code is like this

function(req, res){
longPoll()
function longPoll(){
    async.waterfall([
         connectDB,
         getNotification             
],function(err,data){
    if(there's no notification timestamp larger than user_read){
          setTimeout(longPoll, 1000);
    }else if(there's new data){
          res.json(data);
    }

    if(con)
       con.close();
})
}
};

here's my question:

  1. I'm using setTimeout here, is it appropiate? maybe use nextTick, or setInterval?
  2. should I close the connection everytime after I query from DB, or just one time when I respond?
  3. I want to optimize, and optimize suggestion?

Solution

  • It depends, nextTick is usually more adequate, but think of it from a different perspective, basically you're "short-polling" the DB every second for every user who is connected to your long-poll.

    So even if your webserver isn't getting unnecessary polls because of long-polling (btw, is there an exit condition for that with empty answer as well at you?) you're still short-polling the database.