Track or Count Online Users List
During interview, this is the common question which are asked by the interviewer that How can we track or count total number of online users. This is tricky but really simple question and most of the times interviewee is not able to response on this simple question.
There are two solutions by which you can get the number of online users.
SOLUTION I:
Whenever user come on your site and logged-in on the site. Then set a flag value in DB. And reset the flag whenever user logged-out the site. But this is a major issue in this case. You are totally dependent on the user’s logged-out step. But if user left the site and close the browser or directly goes to other site you can’t reset the flag in the DB. DB state will show that the user is online while he/she is not online. So, this is not recommended.
SOLUTION II:
Make another table for this purpose and add at least 4 fields in this table which are
- username
- datetime
- ipAddress
- session value
Whenever user logged-in on the site insert a record in this table. Also store the session values in COOKIE. Now, on each page first try to read the COOKIE contains the value of session. If the session value found then update the table row with the current datetime where the session value exist.
Now, at this point you can get the information that how many people are currently logged In. Also by the username you can also get the user’s information. But you need to fix you timings that for how long the user’s session should alive. It means if you think that if there is no activity on the site by user within last 10 minutes then it suppose that user has left the site. So, you must get only count of people in last 10 minutes.
You can implement this in any server site scripting like PHP, ASP .Net, CGI, Perl, Ruby etc.


Hmm.. interesting, That’s my favorite question but most of the experienced candidates doesn’t know about this.
Yes, solution#2 is the only option we are left with. That said, this doesn’t give 100% accurate results since we have to make an assumption about the period of inactivity which cannot always be correct. User can navigate away or close the browser and until session times out, we see that user online.
HTTP is a stateless protocol; to count online users, we can’t go beyond the sessions and their expiry time.
Agree about the 2nd method its reliable. Only downside is that it requires number of DB transactions, and that’s an overhead even of you use heap tables etc.
I once used another way, in a scenario where millions of users are online at a time, to closely predict the number of users. This method used request status information from Apache’s mod_status module to closely show the number of online users. Here are a few helpful links for this:
http://httpd.apache.org/docs/1.3/mod/mod_status.html
http://www.phpclasses.org/browse/package/3613.html