0

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?
williamC
  • 176
  • 2
  • 12

1 Answers1

0

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.

Aadaam
  • 3,579
  • 1
  • 14
  • 9
  • you're right! I'm still short-polling the DB so, I thing I should close the connection when I respond – williamC Jul 25 '12 at 16:35
  • or you should know which users are waiting for answer, and ask them in batch... Think of it like in real life: do you want a clerk for each of the users to run to a post office and check if they have new mails, or do you want a single clerk, and a list to which anyone can subscribe while the clerk is away, so that the clerk runs off with the list, asks out all the mailboxes on the list, and returns for those who have anything new? – Aadaam Jul 25 '12 at 23:33
  • I try to make a real-time web,like facebook so I have to assume every users waiting for new notifications but I think I should know which users idle, and stop the long-polling – williamC Jul 26 '12 at 10:49