The biggest problem with the presence of user tracking (onine / offline) via HTTP is to determine when the user is disconnected.
It is easy to determine when a user has entered the network - the mere presence of an authenticated request assumes that the user is active. However, since HTTP is stagnant, the absence of a subsequent request can mean either that the user is offline or the user is online, but recently did nothing with your application.
Thus, the best thing you can do is to have a timeout, and if the user did not make a request during this timeout, switch to offline.
The simplest implementation would be to have lastTimeActive, as suggested by Jonathan Sampson. However, this will not give you the length of a user session, only an approximation of who is online at the moment.
A more complex approach would be to have lastTimeActive and lastTimeLoggedIn. LastTimeLoggedIn is set during the first auth request, which exceeds 5 minutes from the previous auth request. A user is considered online if there has been an authenticated request in the last five minutes. The session duration for the user is the time difference between lastTimeActive and lastTimeLoggedIn.
If your application also offers the choice of logging out to the user, you also think that this action is also disabled. However, if your application is not a banking application, most likely, users simply close the browser.
Also, avoid any background threads to update the offline / online status of your users. You should use the above logic only when there is an explicit request for the status of a specific user, and you should only update the users that you requested.
source share