On Stack Overflow, the profile page lists a "last seen" property. This doesn't seem to be updated on every page view (for performance reasons, obviously). How would you implement it in a heavy-traffic web app? Would you update it only on certain pages? Or cache the last time you logged the user's last visit and wait a specific amount of time before updating the database? Or something completely different?
4 Answers
On a heavy-traffic site like Stack Overflow, I would only update the "last seen" variable when a user actually does something. Lurking around and reading questions and answers shouldn't count as a user being "seen" by the system. Asking and answering questions, or voting on them should be actions that update when a user is last seen.
I won't talk about the implementation details because that's already covered by other answers (and I would probably get it wrong).

- 398,270
- 210
- 566
- 880
You'll probably find "What strategy would you use for tracking user recent activity?" to be helpful. The issues are similar.
I would use a SESSION. And only set it the first visit of the session. Also resetting it every hour or so for if people leave the browser open. In php something like this:
if(!isset(!_SESSION['lastSeen'])){
$_SESSION['lastSeen'] = time();
updateLastSeenInDatabaseOrSomething();
}
else{
if($_SESSION['lastSeen'] < time() + 2 * 60 * 60){ //2 hours
$_SESSION['lastSeen'] = time();
updateLastSeenInDatabaseOrSomething();
}
}
Something like that but then with OO and not doing the same thing twice.

- 31,965
- 17
- 72
- 98
Consider using the "Command" design pattern for this. It will help you two ways - answer the question at hand and also implement an "undo/redo" feature. You should maintain a list of command objects designed per that pattern.

- 5,993
- 4
- 30
- 39