Jakub Jarabica
Jakub Jarabica

Reputation: 29

storing online users php + memcache

I am thinking of storing online users in memcached.

First I thought about having array of key => value pairs where key will be user id and value timestamp of last access.

My problem is that it will be quite large array when there are many users currently online(and there will be).

As memcached is not built to store large data, how would you solve it? What is the best practice!

Thanks for your input!

Upvotes: 1

Views: 1144

Answers (1)

Chris
Chris

Reputation: 1753

The problem with this approach is memcache is only queriable if you know the key in advance. This means you would have to keep the entire online user list under a single known key. Each time a user came online or went offline, it would become necessary to read the list, adjust it, and rewrite it. There is serious potential for a race condition there so you would have to use the check-and-set locking mechanism.

I don't think you should do this. Consider keeping a database table of recent user hits:

user_id: int
last_seen: timestamp

Index on timestamp and user_id. Query friends online using:

SELECT user_id FROM online WHERE user_id IN (...) AND timestamp > (10 minutes ago);

Periodically go through the table and batch remove old timestamp rows.

When your site becomes big you can shard this table on the user_id.

EDIT:

Actually, you can do this if you don't need to query all the users who are currently online, but just need to know if certain users are online.

  1. When a user hits a page,

    memcache.set("online."+user_id, true, 600 /* 10 mins */);

  2. To see if a user is online,

    online = memcache.get("online."+user_id);

There should also be a way to multikey query memcache, look that up. Some strange things could happen if you add a memcache server, but if you use this information for putting an "online" marker next to user names that shouldn't be a big deal.

Upvotes: 4

Related Questions