What is the best way to implement a 'last seen' function in a django web app? What is the best way to implement a 'last seen' function in a django web app? django django

What is the best way to implement a 'last seen' function in a django web app?


An approach might be:

you create a middleware that does the following on process_response:

  • check for a cookie called 'online', but only if the user is authenticated
  • if the cookie is not there,
    • set a cookie called 'online' with value '1'
    • set the lifespan of the cookie to 10 minutes
    • update the 'last_login' field of auth.User for this user with the current datetime

now you have all currently logged in users in your auth.User table. All Users that have a last_login newer than datetime.now()-interval(15minutes) might be considered "online".

The database will be written for every logged in user about every 10 minutes. Adjust the values "10" and "15" to your needs.

The advantage here is that database writes are rare (according to your two numeric settings 10/15). And for speed optimization make sure that last_login is indexed, so a filter on this field including Count is really fast.

Hope this helps.


A hashmap or a queue in memory with a task running every hour or so to persist it.


You need to persist the info server-side, integrity isn't critical, throughput and latency are important. That means you should use some sort of key-value store.

Memcached and redis have keys that expire. You probably have memcached already installed, so use that.

You can reset expiry time of the user:last-seen:$username key every visit, or you can use mawimawi's cookie technique and have expiry = 4 * cookie-lifetime.